text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as request from 'request'; import { Buffer } from 'buffer'; import { merge, Observable, of, throwError } from 'rxjs'; import { filter, flatMap, map, tap } from 'rxjs/operators'; import { Cookie, RxCookieJar } from './rx-cookie-jar'; import RequestAPI = request.RequestAPI; import Request = request.Request; import CoreOptions = request.CoreOptions; import RequiredUriUrl = request.RequiredUriUrl; import RequestResponse = request.RequestResponse; import RequestCallback = request.RequestCallback; // native javascript's objects typings declare const Object: any; /** * Class definition */ export class RxHttpRequest { // private property to store singleton instance private static _instance: RxHttpRequest; // private property to store request API object private readonly _request: RequestAPI<Request, CoreOptions, RequiredUriUrl>; /** * Returns singleton instance * * @return {RxHttpRequest} */ static instance(): RxHttpRequest { if (!(RxHttpRequest._instance instanceof RxHttpRequest)) { RxHttpRequest._instance = new RxHttpRequest(request); } return RxHttpRequest._instance; } /** * Class constructor */ constructor(req: RequestAPI<Request, CoreOptions, RequiredUriUrl>) { // check request parameter this._checkRequestParam(req); // set request object this._request = req; } /** * Returns private attribute _request * * @return {RequestAPI<Request, CoreOptions, RequiredUriUrl>} */ get request(): RequestAPI<Request, CoreOptions, RequiredUriUrl> { return this._request; } /** * This method returns a wrapper around the normal rx-http-request API that defaults to whatever options * you pass to it. * It does not modify the global rx-http-request API; instead, it returns a wrapper that has your default settings * applied to it. * You can _call .defaults() on the wrapper that is returned from rx-http-request.defaults to add/override defaults * that were previously defaulted. * * @param options * * @return {RxHttpRequest} */ defaults(options: CoreOptions): RxHttpRequest { return new RxHttpRequest(this._request.defaults(options)); } /** * Function to do a GET HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ get<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('get', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a GET HTTP request and to return a buffer * * @param uri * @param options * * @return {Observable<RxHttpRequestResponse<Buffer>>} */ getBuffer<R = Buffer>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<Buffer>> { return <Observable<RxHttpRequestResponse<Buffer>>>new Observable((observer) => { try { this._request.get(<string>uri, <CoreOptions>Object.assign({}, options || {})) .on('response', (response: RequestResponse) => { let res: Buffer; response.on('data', (data: Buffer) => res = res ? Buffer.concat([].concat(res, data)) : data); response.on('end', () => { observer.next(<RxHttpRequestResponse<Buffer>>Object.assign({}, { response: <RequestResponse>response, body: <Buffer>res })); observer.complete(); }); }) .on('error', /* istanbul ignore next */ error => observer.error(error)); } catch (error) { observer.error(error); } }); } /** * Function to do a POST HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ post<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('post', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a PUT HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ put<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('put', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a PATCH HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ patch<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('patch', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a DELETE HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ delete<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('del', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a HEAD HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ head<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('head', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function to do a OPTIONS HTTP request * * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} */ options<R = any>(uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>this._call<R>('options', <string>uri, <CoreOptions>Object.assign({}, options || {})); } /** * Function that creates a new rx cookie jar * * @return {Observable<RxCookieJar>} */ jar(): Observable<RxCookieJar> { return <Observable<RxCookieJar>>of(new RxCookieJar(this._request.jar())); } /** * Function that creates a new cookie * * @param str {string} * * @return {Observable<Cookie>} */ cookie(str: string): Observable<Cookie> { return <Observable<Cookie>>of(this._request.cookie(<string>str)); } /** * Function to do a HTTP request for given method * * @param method {string} * @param uri {string} * @param options {CoreOptions} * * @return {Observable<RxHttpRequestResponse<R>>} * * @private */ private _call<R = any>(method: string, uri: string, options?: CoreOptions): Observable<RxHttpRequestResponse<R>> { return <Observable<RxHttpRequestResponse<R>>>new Observable((observer) => { of([].concat(<string>uri, <CoreOptions>Object.assign({}, options || {}), <RequestCallback>((error: any, response: RequestResponse, body: R) => { of(of(error)) .pipe( flatMap(obsError => merge( obsError .pipe( filter(_ => !!_), tap(err => observer.error(err)) ), obsError .pipe( filter(_ => !_), flatMap(() => !!response ? <Observable<RequestResponse>>of(response) : throwError(new Error('No response found')) ), flatMap(_ => of({ response: <RequestResponse>_, body: <R>body }) ), tap(_ => observer.next(_)), tap(() => observer.complete()) ) ) ) ) .subscribe(() => undefined, err => observer.error(err)); }))) .pipe( map(_ => this._request[<string>method].apply(<RequestAPI<Request, CoreOptions, RequiredUriUrl>>this._request, _)), ) .subscribe(() => undefined, err => observer.error(err)); }); } /** * Function to check existing function in request API passed in parameter for a new instance * * @param req {RequestAPI<Request, CoreOptions, RequiredUriUrl>} * * @private */ private _checkRequestParam(req: RequestAPI<Request, CoreOptions, RequiredUriUrl>) { // check existing function in API if (!req || Object.prototype.toString.call(req.get) !== '[object Function]' || Object.prototype.toString.call(req.head) !== '[object Function]' || Object.prototype.toString.call(req.post) !== '[object Function]' || Object.prototype.toString.call(req.put) !== '[object Function]' || Object.prototype.toString.call(req.patch) !== '[object Function]' || Object.prototype.toString.call(req.del) !== '[object Function]' || Object.prototype.toString.call(req.defaults) !== '[object Function]' || Object.prototype.toString.call(req.jar) !== '[object Function]' || Object.prototype.toString.call(req.cookie) !== '[object Function]') { throw new TypeError('Parameter must be a valid `request` module API'); } } } /** * Export {RxHttpRequest} instance */ export const RxHR: RxHttpRequest = RxHttpRequest.instance(); /** * Export response interface */ export interface RxHttpRequestResponse<R = any> { response: RequestResponse; body: R; } /** * Export all initial elements */ export { RequestAPI, Request, CoreOptions, RequiredUriUrl, RequestResponse };
the_stack
import { minifyJSON } from './helpers/json.util'; import { minifyCSS } from './helpers/css.util'; const postcss = require('postcss'); const fs = require('fs-extra'); const THEMIFY = 'themify'; const JSToSass = require('./helpers/js-sass'); export interface ThemifyOptions { /** * Whether we would like to generate the CSS variables. * This should be true, unless you want to inject them yourself. */ createVars: boolean; /** * Palette configuration */ palette: any; /** * A class prefix to append to the generated themes classes */ classPrefix: string; /** * Whether to generate a fallback for legacy browsers (ahm..ahm..) that do not supports CSS Variables */ screwIE11: boolean; /** * Legacy browser fallback */ fallback: { /** * An absolute path to the fallback CSS. */ cssPath: string | null; /** * An absolute path to the fallback JSON. * This file contains variable that will be replace in runtime, for legacy browsers */ dynamicPath: string | null; }; } const defaultOptions: ThemifyOptions = { createVars: true, palette: {}, classPrefix: '', screwIE11: true, fallback: { cssPath: null, dynamicPath: null } }; /** supported color variations */ const ColorVariation = { DARK: 'dark', LIGHT: 'light' }; function buildOptions(options: ThemifyOptions) { if (!options) { throw new Error(`options is required.`); } // make sure we have a palette if (!options.palette) { throw new Error(`The 'palette' option is required.`); } return { ...defaultOptions, ...options }; } /** * * @param {string} filePath * @param {string} output * @returns {Promise<any>} */ function writeToFile(filePath: string, output: string) { return fs.outputFile(filePath, output); } /** * Get the rgba as 88, 88, 33 instead rgba(88, 88, 33, 1) * @param value */ function getRgbaNumbers(value: string) { return hexToRgba(value) .replace('rgba(', '') .replace(', 1)', ''); } /** Define the default variation */ const defaultVariation = ColorVariation.LIGHT; /** An array of variation values */ const variationValues: string[] = (Object as any).values(ColorVariation); /** An array of all non-default variations */ const nonDefaultVariations: string[] = variationValues.filter(v => v !== defaultVariation); function themify(options: ThemifyOptions) { /** Regex to get the value inside the themify parenthesis */ const themifyRegExp = /themify\(([^)]+)\)/gi; /** * Define the method of color execution */ const enum ExecutionMode { CSS_VAR = 'CSS_VAR', CSS_COLOR = 'CSS_COLOR', DYNAMIC_EXPRESSION = 'DYNAMIC_EXPRESSION' } options = buildOptions(options); return root => { // process fallback CSS, without mutating the rules if (options.screwIE11 === false) { processFallbackRules(root); } // mutate the existing rules processRules(root); }; /** * @example themify({"light": ["primary-0", 0.5], "dark": "primary-700"}) * @example themify({"light": "primary-0", "dark": "primary-700"}) * @example linear-gradient(themify({"color": "primary-200", "opacity": "1"}), themify({"color": "primary-300", "opacity": "1"})) * @example themify({"light": ["primary-100", "1"], "dark": ["primary-100", "1"]}) * @example 1px solid themify({"light": ["primary-200", "1"], "dark": ["primary-200", "1"]}) */ function getThemifyValue(propertyValue: string, execMode: ExecutionMode): { [variation: string]: string } { /** Remove the start and end ticks **/ propertyValue = propertyValue.replace(/'/g, ''); const colorVariations = {}; function normalize(value, variationName) { let parsedValue; try { parsedValue = JSON.parse(value); } catch (ex) { throw new Error(`fail to parse the following expression: ${value}.`); } const currentValue = parsedValue[variationName]; /** For example: background-color: themify((light: primary-100)); */ if (!currentValue) { throw new Error(`${value} has one variation.`); } // convert to array if (!Array.isArray(currentValue)) { // color, alpha parsedValue[variationName] = [currentValue, 1]; } else if (!currentValue.length || !currentValue[0]) { throw new Error('Oops. Received an empty color!'); } if (options.palette) return parsedValue[variationName]; } // iterate through all variations variationValues.forEach(variationName => { // replace all 'themify' tokens with the right string colorVariations[variationName] = propertyValue.replace(themifyRegExp, (occurrence, value) => { // parse and normalize the color const parsedColor = normalize(value, variationName); // convert it to the right format return translateColor(parsedColor, variationName, execMode); }); }); return colorVariations; } /** * Get the underline color, according to the execution mode * @param colorArr two sized array with the color and the alpha * @param variationName the name of the variation. e.g. light / dark * @param execMode */ function translateColor(colorArr: [string, string], variationName: string, execMode: ExecutionMode) { const [colorVar, alpha] = colorArr; // returns the real color representation const underlineColor = options.palette[variationName][colorVar]; if (!underlineColor) { // variable is not mandatory in non-default variations if (variationName !== defaultVariation) { return null; } throw new Error(`The variable name '${colorVar}' doesn't exists in your palette.`); } switch (execMode) { case ExecutionMode.CSS_COLOR: // with default alpha - just returns the color if (alpha === '1') { return underlineColor; } // with custom alpha, convert it to rgba const rgbaColorArr = getRgbaNumbers(underlineColor); return `rgba(${rgbaColorArr}, ${alpha})`; case ExecutionMode.DYNAMIC_EXPRESSION: // returns it in a unique pattern, so it will be easy to replace it in runtime return `%[${variationName}, ${colorVar}, ${alpha}]%`; default: // return an rgba with the CSS variable name return `rgba(var(--${colorVar}), ${alpha})`; } } /** * Walk through all rules, and replace each themify occurrence with the corresponding CSS variable. * @example background-color: themify(primary-300, 0.5) => background-color: rgba(var(--primary-300),0.6) * @param root */ function processRules(root) { root.walkRules(rule => { if (!hasThemify(rule.toString())) { return; } let aggragatedSelectorsMap = {}; let aggragatedSelectors: string[] = []; let createdRules: any[] = []; const variationRules = { [defaultVariation]: rule }; rule.walkDecls(decl => { const propertyValue = decl.value; if (!hasThemify(propertyValue)) return; const property = decl.prop; const variationValueMap = getThemifyValue(propertyValue, ExecutionMode.CSS_VAR); const defaultVariationValue = variationValueMap[defaultVariation]; decl.value = defaultVariationValue; // indicate if we have a global rule, that cannot be nested const createNonDefaultVariationRules = isAtRule(rule); // don't create extra CSS for global rules if (createNonDefaultVariationRules) { return; } // create a new declaration and append it to each rule nonDefaultVariations.forEach(variationName => { const currentValue = variationValueMap[variationName]; // variable for non-default variation is optional if (!currentValue || currentValue === 'null') { return; } // when the declaration is the same as the default variation, // we just need to concatenate our selector to the default rule if (currentValue === defaultVariationValue) { const selector = getSelectorName(rule, variationName); // append the selector once if (!aggragatedSelectorsMap[variationName]) { aggragatedSelectorsMap[variationName] = true; aggragatedSelectors.push(selector); } } else { // creating the rule for the first time if (!variationRules[variationName]) { const clonedRule = createRuleWithVariation(rule, variationName); variationRules[variationName] = clonedRule; // append the new rule to the array, so we can append it later createdRules.push(clonedRule); } const variationDecl = createDecl(property, variationValueMap[variationName]); variationRules[variationName].append(variationDecl); } }); }); if (aggragatedSelectors.length) { rule.selectors = [...rule.selectors, ...aggragatedSelectors]; } // append each created rule if (createdRules.length) { createdRules.forEach(r => root.append(r)); } }); } /** * indicate if we have a global rule, that cannot be nested * @param rule * @return {boolean} */ function isAtRule(rule) { return rule.parent && rule.parent.type === 'atrule'; } /** * Walk through all rules, and generate a CSS fallback for legacy browsers. * Two files shall be created for full compatibility: * 1. A CSS file, contains all the rules with the original color representation. * 2. A JSON with the themify rules, in the following form: * themify(primary-100, 0.5) => %[light,primary-100,0.5)% * @param root */ function processFallbackRules(root) { // an output for each execution mode const output = { [ExecutionMode.CSS_COLOR]: [], [ExecutionMode.DYNAMIC_EXPRESSION]: {} }; // initialize DYNAMIC_EXPRESSION with all existing variations variationValues.forEach(variation => (output[ExecutionMode.DYNAMIC_EXPRESSION][variation] = [])); // define which modes need to be processed const execModes = [ExecutionMode.CSS_COLOR, ExecutionMode.DYNAMIC_EXPRESSION]; walkFallbackAtRules(root, execModes, output); walkFallbackRules(root, execModes, output); writeFallbackCSS(output); } function writeFallbackCSS(output) { // write the CSS & JSON to external files if (output[ExecutionMode.CSS_COLOR].length) { // write CSS fallback; const fallbackCss = output[ExecutionMode.CSS_COLOR].join(''); writeToFile(options.fallback.cssPath as string, minifyCSS(fallbackCss)); // creating a JSON for the dynamic expressions const jsonOutput = {}; variationValues.forEach(variationName => { jsonOutput[variationName] = output[ExecutionMode.DYNAMIC_EXPRESSION][variationName] || []; jsonOutput[variationName] = minifyJSON(jsonOutput[variationName].join('')); // minify the CSS output jsonOutput[variationName] = minifyCSS(jsonOutput[variationName]); }); // stringify and save const dynamicCss = JSON.stringify(jsonOutput); writeToFile(options.fallback.dynamicPath as string, dynamicCss); } } function walkFallbackAtRules(root, execModes, output) { root.walkAtRules(atRule => { if (atRule.nodes && hasThemify(atRule.toString())) { execModes.forEach(mode => { const clonedAtRule = atRule.clone(); clonedAtRule.nodes.forEach(rule => { rule.walkDecls(decl => { const propertyValue = decl.value; // replace the themify token, if exists if (hasThemify(propertyValue)) { const colorMap = getThemifyValue(propertyValue, mode); decl.value = colorMap[defaultVariation]; } }); }); let rulesOutput = mode === ExecutionMode.DYNAMIC_EXPRESSION ? output[mode][defaultVariation] : output[mode]; rulesOutput.push(clonedAtRule); }); } }); } function walkFallbackRules(root, execModes, output) { root.walkRules(rule => { if (isAtRule(rule) || !hasThemify(rule.toString())) { return; } const ruleModeMap = {}; rule.walkDecls(decl => { const propertyValue = decl.value; if (!hasThemify(propertyValue)) return; const property = decl.prop; execModes.forEach(mode => { const colorMap = getThemifyValue(propertyValue, mode); // lazily creating a new rule for each variation, for the specific mode if (!ruleModeMap.hasOwnProperty(mode)) { ruleModeMap[mode] = {}; variationValues.forEach(variationName => { let newRule; if (variationName === defaultVariation) { newRule = cloneEmptyRule(rule); } else { newRule = createRuleWithVariation(rule, variationName); } // push the new rule into the right place, // so we can write them later to external file let rulesOutput = mode === ExecutionMode.DYNAMIC_EXPRESSION ? output[mode][variationName] : output[mode]; rulesOutput.push(newRule); ruleModeMap[mode][variationName] = newRule; }); } // create and append a new declaration variationValues.forEach(variationName => { const underlineColor = colorMap[variationName]; if (underlineColor && underlineColor !== 'null') { const newDecl = createDecl(property, colorMap[variationName]); ruleModeMap[mode][variationName].append(newDecl); } }); }); }); }); } function createDecl(prop, value) { return postcss.decl({ prop, value }); } /** * check if there's a themify keyword in this declaration * @param propertyValue */ function hasThemify(propertyValue) { return propertyValue.indexOf(THEMIFY) > -1; } /** * Create a new rule for the given variation, out of the original rule * @param rule * @param variationName */ function createRuleWithVariation(rule, variationName) { const selector = getSelectorName(rule, variationName); return postcss.rule({ selector }); } /** * Get a selector name for the given rule and variation * @param rule * @param variationName */ function getSelectorName(rule, variationName) { const selectorPrefix = `.${options.classPrefix || ''}${variationName}`; return rule.selectors .map(selector => { return `${selectorPrefix} ${selector}`; }) .join(','); } function cloneEmptyRule(rule, overrideConfig?) { const clonedRule = rule.clone(overrideConfig); // remove all the declaration from this rule clonedRule.removeAll(); return clonedRule; } } /** * Generating a SASS definition file with the palette map and the CSS variables. * This file should be injected into your bundle. */ function init(options) { options = buildOptions(options); return root => { const palette = options.palette; const css = generateVars(palette, options.classPrefix); const parsedCss = postcss.parse(css); root.prepend(parsedCss); }; /** * This function responsible for creating the CSS variable. * * The output should look like the following: * * .light { --primary-700: 255, 255, 255; --primary-600: 248, 248, 249; --primary-500: 242, 242, 244; * } * * .dark { --primary-700: 255, 255, 255; --primary-600: 248, 248, 249; --primary-500: 242, 242, 244; * } * */ function generateVars(palette, prefix) { let cssOutput = ''; prefix = prefix || ''; // iterate through the different variations Object.keys(palette).forEach(variationName => { const selector = variationName === ColorVariation.LIGHT ? ':root' : `.${prefix}${variationName}`; const variationColors = palette[variationName]; // make sure we got colors for this variation if (!variationColors) { throw new Error(`Expected map of colors for the variation name ${variationName}`); } const variationKeys = Object.keys(variationColors); // generate CSS variables const vars = variationKeys .map(varName => { return `--${varName}: ${getRgbaNumbers(variationColors[varName])};`; }) .join(' '); // concatenate the variables to the output const output = `${selector} {${vars}}`; cssOutput = `${cssOutput} ${output}`; }); // generate the $palette variable cssOutput += `$palette: ${JSToSass(palette)};`; return cssOutput; } } function hexToRgba(hex, alpha = 1): string { hex = hex.replace('#', ''); const r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16); const g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16); const b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16); return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; } module.exports = { initThemify: postcss.plugin('datoThemes', init), themify: postcss.plugin('datoThemes', themify) };
the_stack
import fetch from "node-fetch"; import TasitAction from "@tasit/action"; const { ConfigLoader, ERC20, ERC721, Marketplace: MarketplaceContracts, ProviderFactory } = TasitAction; const { Mana } = ERC20; const { Estate, Land } = ERC721; const { Decentraland } = MarketplaceContracts; import TasitContracts from ".."; // because we're in the contracts package import { duration, constants, accounts, // etherFaucet, // expectExactEtherBalances, erc20Faucet, // expectExactTokenBalances, bigNumberify, } from "@tasit/test-helpers"; const { // TEN, BILLION, WEI_PER_ETHER } = constants; let network = process.env.NETWORK; if (!network) { throw new Error( `Use NETWORK env argument to choose which chain will be populated.` ); } else { console.info(`Populating data to the '${network}' chain...`); } let EVENTS_TIMEOUT; let ASSETS_TO_CREATE; import configGoerli from "../config/goerli.js"; import configDevelopment from "../config/goerli.js"; import configRinkeby from "../config/goerli.js"; import configRopsten from "../config/goerli.js"; const config = (() => { if (network === "goerli") { return configGoerli; } if (network === "development") { return configDevelopment; } if (network === "ropsten") { return configRopsten; } if (network === "rinkeby") { return configRinkeby; } })(); if (network === "development") { network = "local"; EVENTS_TIMEOUT = 2500; // 2.5 seconds ASSETS_TO_CREATE = 20; } else { // non-local chains EVENTS_TIMEOUT = 5 * 60 * 1000; ASSETS_TO_CREATE = 100; } const { LANDProxy, EstateRegistry, Marketplace, GnosisSafe: GnosisSafeInfo, MANAToken, } = TasitContracts[network]; const { address: MANA_ADDRESS } = MANAToken; const { address: LAND_PROXY_ADDRESS } = LANDProxy; const { address: ESTATE_ADDRESS } = EstateRegistry; const { address: MARKETPLACE_ADDRESS } = Marketplace; const { address: GNOSIS_SAFE_ADDRESS } = GnosisSafeInfo; ConfigLoader.setConfig(config); const [minterAccount, sellerAccount] = accounts; const { address: sellerAddress } = sellerAccount; const manaContract = new Mana(MANA_ADDRESS); const landContract = new Land(LAND_PROXY_ADDRESS); const estateContract = new Estate(ESTATE_ADDRESS); const marketplaceContract = new Decentraland(MARKETPLACE_ADDRESS); const provider = ProviderFactory.getProvider(); const cancelSellOrder = async (nftAddress, id) => { const action = marketplaceContract.cancelOrder(nftAddress, `${id}`); await action.send(); await action.waitForOneConfirmation(); }; const cancelOrdersOfEstatesWithoutImage = async (estatesIds) => { const getImageDataFromEstateId = async (id) => { const image = await fetch( `https://api.decentraland.org/v1/estates/${id}/map.png` ); const data = (await image.buffer()).toString("base64"); return data; }; // Note: Estate with 5 is one of the estates with blank image const blankImageData = await getImageDataFromEstateId(5); marketplaceContract.setAccount(sellerAccount); for (const id of estatesIds) { const imageData = await getImageDataFromEstateId(id); if (imageData === blankImageData) { console.info( `Removing order of estate (id: ${id}) because it has a blank image.` ); await cancelSellOrder(ESTATE_ADDRESS, id); } } }; const extractParcelsFromEstates = (estates) => { let estatesParcels = []; estates.forEach((estate) => { const { parcels } = estate; estatesParcels = [...estatesParcels, ...parcels]; }); return estatesParcels; }; const updateParcelsData = async (parcels) => { console.info("Updating parcels with metadata..."); landContract.setAccount(sellerAccount); for (const parcel of parcels) { const { x, y, metadata: parcelName } = parcel; console.info(`Setting metadata for parcel (${x},${y})...`); if (parcelName && parcelName !== "") { const updateAction = landContract.updateLandData(x, y, parcelName); await updateAction.send(); await updateAction.waitForOneConfirmation(); console.info("Done"); } console.info("Skipped because this parcel has no metadata."); } }; // Tech-debt: Use `assignMultipleParcels` to save gas cost. // The amount of parcels per call should be short enough to avoid out-of-gas. const createParcels = async (parcels) => { console.info("Creating parcels..."); const parcelIds = []; for (const parcel of parcels) { try { const id = await createParcel(parcel); parcelIds.push(id); } catch (error) { console.info("Parcel creation failed"); } } await updateParcelsData(parcels); return parcelIds; }; const createParcel = async (parcel) => { const { x, y } = parcel; landContract.setAccount(minterAccount); const action = landContract.assignNewParcel(`${x}`, `${y}`, sellerAddress); await action.send(); console.info(`Creating parcel (${x},${y})...`); const parcelId = await new Promise((resolve, reject) => { const timeout = setTimeout(() => { console.info(`Timeout reached for parcel (${x},${y}) creation.`); action.unsubscribe(); reject(); }, EVENTS_TIMEOUT); action.on("confirmation", async () => { const id = await landContract.encodeTokenId(`${x}`, `${y}`); action.unsubscribe(); clearTimeout(timeout); resolve(id); }); action.on("error", (error) => { const { message } = error; console.warn(message); action.unsubscribe(); reject(); }); }); await action.waitForOneConfirmation(); console.info(`Parcel ID = ${parcelId}`); return parcelId; }; const createEstate = async (estate) => { const { metadata: estateName, parcels } = estate; const { address: beneficiaryAddress } = sellerAccount; const xArray = []; const yArray = []; parcels.forEach((parcel) => { xArray.push(parcel.x); yArray.push(parcel.y); }); console.info(`Creating estate (${xArray} - ${yArray})...`); landContract.setAccount(sellerAccount); const action = landContract.createEstateWithMetadata( xArray, yArray, beneficiaryAddress, `${estateName}` ); await action.send(); const estateId = await new Promise((resolve, reject) => { const timeout = setTimeout(() => { console.warn( `Timeout reached for estate (${xArray} - ${yArray}) creation.` ); estateContract.unsubscribe(); action.unsubscribe(); reject(); }, EVENTS_TIMEOUT); // Some error (orphan block, failed tx) events are being triggered only from the confirmationListener // See more: https://github.com/tasitlabs/tasit-sdk/issues/253 action.on("confirmation", () => { // do nothing }); action.on("error", (error) => { const { message } = error; console.warn(message); action.unsubscribe(); reject(); }); estateContract.on("error", (error) => { const { message } = error; console.warn(message); estateContract.unsubscribe(); reject(); }); estateContract.on("CreateEstate", (message) => { const { data } = message; const { args } = data; action.unsubscribe(); estateContract.unsubscribe(); clearTimeout(timeout); resolve(args._estateId); }); }); await action.waitForOneConfirmation(); console.info(`Estate ID = ${estateId}`); return estateId; }; const createEstates = async (estates) => { console.info("Creating estates..."); const estateIds = []; for (const estate of estates) { try { const id = await createEstate(estate); estateIds.push(id); } catch (error) { console.warn("Estate creation failed"); } } return estateIds; }; const approveMarketplace = async () => { console.info("Approving Marketplace..."); // Set false to remove approval const authorized = true; estateContract.setAccount(sellerAccount); const estateApproval = estateContract.setApprovalForAll( MARKETPLACE_ADDRESS, authorized ); await estateApproval.send(); await estateApproval.waitForOneConfirmation(); landContract.setAccount(sellerAccount); const landApproval = landContract.setApprovalForAll( MARKETPLACE_ADDRESS, authorized ); await landApproval.send(); await landApproval.waitForOneConfirmation(); }; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } const placeAssetOrders = async (estateIds, parcelIds) => { console.info(`Placing sell orders...`); const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5); const estatesToSell = estateIds.map((id) => { return { nftAddress: ESTATE_ADDRESS, id }; }); const parcelsToSell = parcelIds.map((id) => { return { nftAddress: LAND_PROXY_ADDRESS, id }; }); const assetsToSell = shuffleArray([...estatesToSell, ...parcelsToSell]); for (const asset of assetsToSell) { const { nftAddress, id } = asset; await placeAssetSellOrder(nftAddress, id); } }; const placeAssetSellOrder = async (nftAddress, assetId) => { const expireAt = Date.now() + duration.years(5); const price = getRandomInt(10, 100) + "000"; const priceInWei = bigNumberify(price).mul(WEI_PER_ETHER); const type = nftAddress == ESTATE_ADDRESS ? "estate" : "parcel"; console.info(`placing sell order for the ${type} with id ${assetId}`); marketplaceContract.setAccount(sellerAccount); const action = marketplaceContract.createOrder( nftAddress, assetId, priceInWei, expireAt ); await action.send(); await action.waitForOneConfirmation(); }; const parcelsAreEqual = (p1, p2) => p1.x === p2.x && p1.y === p2.y; const findParcel = (parcel, listOfParcels) => { return listOfParcels.find((p) => parcelsAreEqual(p, parcel)); }; const getEstatesFromAPI = async () => { // Note: In the future, we can get the same data from Decentraland contracts // to move away from this point of centralization const assetsToCreate = ASSETS_TO_CREATE / 2; const res = await fetch( `https://api.decentraland.org/v1/estates?status=open&limit=${assetsToCreate}` ); const json = await res.json(); const { data: jsonData } = json; const { estates: estatesFromAPI } = jsonData; const allEstates = estatesFromAPI.map((estate) => { const { data } = estate; const { name: metadata, parcels } = data; return { metadata, parcels }; }); // Keep estates with small number of parcels to avoid out-of-gas on creation const estates = allEstates.filter((e) => e.parcels.length < 10); return estates; }; const getParcelsFromAPI = async () => { // Note: In the future, we can get the same data from Decentraland contracts // to move away from this point of centralization const assetsToCreate = ASSETS_TO_CREATE / 2; const res = await fetch( `https://api.decentraland.org/v1/parcels?status=open&limit=${assetsToCreate}` ); const json = await res.json(); const { data: jsonData } = json; const { parcels: parcelsFromAPI } = jsonData; const parcels = parcelsFromAPI.map((parcel) => { const { x, y, data } = parcel; let { name: metadata } = data; if (!metadata) metadata = ""; return { x, y, metadata }; }); return parcels; }; (async () => { try { // Fund Gnosis Safe account with Mana tokens and ethers console.info("minter account", minterAccount.signingKey.address); console.info({ GNOSIS_SAFE_ADDRESS }); console.info({ provider }); console.info("About to send ether from minter to Safe"); // await etherFaucet(provider, minterAccount, GNOSIS_SAFE_ADDRESS, TEN); console.info("About to check ether amount"); // await expectExactEtherBalances(provider, [GNOSIS_SAFE_ADDRESS], [TEN]); console.info("About to send MANA"); await erc20Faucet( manaContract, minterAccount, GNOSIS_SAFE_ADDRESS, BILLION ); console.info("About to check MANA amount"); // await expectExactTokenBalances( // manaContract, // [GNOSIS_SAFE_ADDRESS], // [BILLION] // ); const [parcels, estates] = await Promise.all([ getParcelsFromAPI(), getEstatesFromAPI(), ]); const estatesParcels = extractParcelsFromEstates(estates).filter( (estateParcel) => !findParcel(estateParcel, parcels) ); console.info("About to create parcels and estates"); const parcelIds = await createParcels(parcels); await createParcels(estatesParcels); const estateIds = await createEstates(estates); await approveMarketplace(); await placeAssetOrders(estateIds, parcelIds); // Removing orders from non-development chains if (network !== "local") await cancelOrdersOfEstatesWithoutImage(estateIds); } catch (err) { console.error(err); } })();
the_stack
import { getTests, Test } from "./tests" import colors from 'colors/safe' import util from 'util' import fs from 'fs' import os from 'os' import temp from 'temp' import defaultPrint from './print' import Streams from 'memory-streams' import { compare as compareAsync, compareSync as compareSync, Statistics, Result } from "../src" import untar from './untar' import semver from 'semver' // Usage: node runTests [unpacked] [test001_1] [showresult] [skipasync] [noReport] interface RunOptions { // Use ./testdir instead of testdir.tar as test data. // Run 'node extract.js' to initialize ./testdir. // (note that regular untar will not work as it contains symlink loops) unpacked: boolean, // Specify a single test to run ie. 'test000_0' // If defined, represents the test name to be executed in format // 00otherwise all tests are executed singleTestName: string, // Shows actual/expected for each test showResult: boolean, // Do not run async tests skipAsync: boolean, // Do not create report.txt noReport: boolean } let count = 0, failed = 0, successful = 0 let syncCount = 0, syncFailed = 0, syncSuccessful = 0 let asyncCount = 0, asyncFailed = 0, asyncSuccessful = 0 // Automatically track and cleanup files at exit temp.track() function passed(value, type) { count++ if (value) { successful++ } else { failed++ } if (type === 'sync') { syncCount++ if (value) { syncSuccessful++ } else { syncFailed++ } } if (type === 'async') { asyncCount++ if (value) { asyncSuccessful++ } else { asyncFailed++ } } return value ? colors.green('Passed') : colors.yellow('!!!!FAILED!!!!') } // Matches date (ie 2014-11-18T21:32:39.000Z) const normalizeDateRegexp = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/gm function normalize(str) { str = str.replace(normalizeDateRegexp, 'x') str = str.replace(/\r\n/g, '\n') str = str.replace(/\\/g, '/') return str } function checkStatistics(statistics, test) { if (test.skipStatisticsCheck) { return true } if (statistics.differences !== statistics.left + statistics.right + statistics.distinct) { return false } if (statistics.differencesFiles !== statistics.leftFiles + statistics.rightFiles + statistics.distinctFiles) { return false } if (statistics.differencesDirs !== statistics.leftDirs + statistics.rightDirs + statistics.distinctDirs) { return false } if (statistics.total !== statistics.equal + statistics.differences) { return false } if (statistics.totalFiles !== statistics.equalFiles + statistics.differencesFiles) { return false } if (statistics.totalDirs !== statistics.equalDirs + statistics.differencesDirs) { return false } const brokenLinksStats = statistics.brokenLinks if (brokenLinksStats.totalBrokenLinks !== brokenLinksStats.leftBrokenLinks + brokenLinksStats.rightBrokenLinks + brokenLinksStats.distinctBrokenLinks) { return false } if (statistics.total !== statistics.totalDirs + statistics.totalFiles + brokenLinksStats.totalBrokenLinks) { return false } if (statistics.equal !== statistics.equalDirs + statistics.equalFiles) { return false } if (statistics.left !== statistics.leftDirs + statistics.leftFiles + brokenLinksStats.leftBrokenLinks) { return false } if (statistics.right !== statistics.rightDirs + statistics.rightFiles + brokenLinksStats.rightBrokenLinks) { return false } if (statistics.distinct !== statistics.distinctDirs + statistics.distinctFiles + brokenLinksStats.distinctBrokenLinks) { return false } return true } function getExpected(test) { if (test.expected) { return test.expected.trim() } else { return normalize(fs.readFileSync(__dirname + '/expected/' + test.name + '.txt', 'utf8')).trim() } } function testSync(test, testDirPath, saveReport, runOptions: Partial<RunOptions>): Promise<void> { process.chdir(testDirPath) let path1, path2 if (test.withRelativePath) { path1 = test.path1 path2 = test.path2 } else { path1 = test.path1 ? testDirPath + '/' + test.path1 : '' path2 = test.path2 ? testDirPath + '/' + test.path2 : '' } return new Promise<Result>(resolve => resolve(compareSync(path1, path2, test.options))) .then((result: Result) => { // PRINT DETAILS const writer = new Streams.WritableStream() const print = test.print ? test.print : defaultPrint print(result, writer, test.displayOptions) const output = normalize(writer.toString()).trim() const expected = getExpected(test) if (runOptions.showResult) { printResult(output, expected) } const statisticsCheck = checkStatistics(result, test) const validated = runCustomValidator(test, result) const res = expected === output && statisticsCheck && validated report(test.name, 'sync', output, null, res, saveReport) console.log(test.name + ' sync: ' + passed(res, 'sync')) }) .catch(error => { report(test.name, 'sync', error instanceof Error ? error.stack : error, null, false, saveReport) console.log(test.name + ' sync: ' + passed(false, 'sync') + '. Error: ' + printError(error)) }) } function testAsync(test: Partial<Test>, testDirPath, saveReport, runOptions: Partial<RunOptions>): Promise<void> { if (runOptions.skipAsync) { return Promise.resolve() } process.chdir(testDirPath) let path1, path2 if (test.withRelativePath) { path1 = test.path1 path2 = test.path2 } else { path1 = test.path1 ? testDirPath + '/' + test.path1 : '' path2 = test.path2 ? testDirPath + '/' + test.path2 : '' } let promise if (test.runAsync) { promise = test.runAsync() .then(result => ({ output: result, statisticsCheck: true, validated: true })) } else { promise = compareAsync(path1, path2, test.options) .then(result => { const writer = new Streams.WritableStream() const print = test.print ? test.print : defaultPrint print(result, writer, test.displayOptions) const statisticsCheck = checkStatistics(result, test) const output = normalize(writer.toString()).trim() const validated = runCustomValidator(test, result) return { output, statisticsCheck, validated } }) } return promise .then(result => { const output = result.output const expected = getExpected(test) if (runOptions.showResult) { printResult(output, expected) } const res = expected === output && result.statisticsCheck && result.validated report(test.name, 'async', output, null, res, saveReport) console.log(test.name + ' async: ' + passed(res, 'async')) }) .catch(error => { report(test.name, 'async', error instanceof Error ? error.stack : error, null, false, saveReport) console.log(test.name + ' async: ' + passed(false, 'async') + '. Error: ' + printError(error)) }) } function printError(error) { return error instanceof Error ? error.stack : error } function initReport(saveReport) { if (saveReport) { if (fs.existsSync(REPORT_FILE)) { fs.unlinkSync(REPORT_FILE) } fs.appendFileSync(REPORT_FILE, util.format('Date: %s, Node version: %s. OS platform: %s, OS release: %s\n', new Date(), process.version, os.platform(), os.release())) } } const REPORT_FILE = __dirname + "/report.txt" function report(testName, testDescription, output, exitCode, result, saveReport) { if (saveReport && !result) { fs.appendFileSync(REPORT_FILE, util.format( "\n%s %s failed - result: %s, exitCode: %s, output: %s\n", testName, testDescription, result, exitCode ? exitCode : 'n/a', output ? output : 'n/a')) } } function endReport(saveReport) { if (saveReport) { fs.appendFileSync(REPORT_FILE, 'Tests: ' + count + ', failed: ' + failed + ', succeeded: ' + successful) } } function printResult(output, expected) { console.log('Actual:') console.log(output) console.log('Expected:') console.log(expected) console.log('Result: ' + (output === expected)) } function validatePlatform(test: Partial<Test>) { if (!test.excludePlatform || test.excludePlatform.length === 0) { return true } return !includes(test.excludePlatform, os.platform()) } function includes<T>(arr: T[], item: T): boolean { return arr.filter(v => v === item).length === 1 } function runCustomValidator(test: Partial<Test>, statistics: Statistics) { if (!test.customValidator) { return true } return test.customValidator(statistics) } /** * @param testDirPath path to test data */ function executeTests(testDirPath, runOptions: Partial<RunOptions>) { console.log('Test dir: ' + testDirPath) const saveReport = !runOptions.noReport initReport(saveReport) Promise.resolve() .then(() => { // Run sync tests const syncTestsPromises: Promise<void>[] = [] getTests(testDirPath) .filter(test => !test.onlyAsync) .filter(test => runOptions.singleTestName ? test.name === runOptions.singleTestName : true) .filter(test => test.nodeVersionSupport === undefined || semver.satisfies(process.version, test.nodeVersionSupport)) .filter(test => validatePlatform(test)) .forEach(test => syncTestsPromises.push(testSync(test, testDirPath, saveReport, runOptions))) return Promise.all(syncTestsPromises) }) .then(() => { console.log() console.log('Sync tests: ' + syncCount + ', failed: ' + colors.yellow(syncFailed.toString()) + ', succeeded: ' + colors.green(syncSuccessful.toString())) console.log() }) .then(() => { // Run async tests const asyncTestsPromises: Promise<void>[] = [] getTests(testDirPath) .filter(test => !test.onlySync) .filter(test => test.nodeVersionSupport === undefined || semver.satisfies(process.version, test.nodeVersionSupport)) .filter(test => validatePlatform(test)) .filter(test => runOptions.singleTestName ? test.name === runOptions.singleTestName : true) .forEach(test => asyncTestsPromises.push(testAsync(test, testDirPath, saveReport, runOptions))) return Promise.all(asyncTestsPromises) }) .then(() => { console.log() console.log('Async tests: ' + asyncCount + ', failed: ' + colors.yellow(asyncFailed.toString()) + ', succeeded: ' + colors.green(asyncSuccessful.toString())) console.log() }).then(() => { console.log() console.log('All tests: ' + count + ', failed: ' + colors.yellow(failed.toString()) + ', succeeded: ' + colors.green(successful.toString())) endReport(saveReport) process.exitCode = failed > 0 ? 1 : 0 process.chdir(__dirname) // allow temp dir to be removed }).catch(error => { console.error(error); process.exit(1) }) } function main() { const args = process.argv const runOptions: Partial<RunOptions> = { unpacked: false, showResult: false, skipAsync: false, noReport: false, singleTestName: undefined } args.forEach(arg => { if (arg.match('unpacked')) { runOptions.unpacked = true } if (arg.match('showresult')) { runOptions.showResult = true } if (arg.match('skipasync')) { runOptions.skipAsync = true } if (arg.match('noreport')) { runOptions.noReport = true } if (arg.match(/test\d\d\d_\d/)) { runOptions.singleTestName = arg } }) if (runOptions.unpacked) { executeTests(__dirname + '/testdir', runOptions) } else { temp.mkdir('dircompare-test', (err, testDirPath) => { if (err) { throw err } const onError = (error) => { console.error('Error occurred:', error) } untar(__dirname + "/testdir.tar", testDirPath, () => { executeTests(testDirPath, runOptions) }, onError) }) } } main()
the_stack
interface ServiceWorkerEvent extends Event { waitUntil<U>(promise: Promise<U>): void; respondWith(response: Promise<Response>): void; request: Request; } interface ServiceWorkerScope { clients: ServiceWorkerClients; } interface ServiceWorkerClients { matchAll(): Promise<ServiceWorkerClient[]>; claim(): Promise<void>; } interface ServiceWorkerClient { readonly id: string; readonly type: "window" | "worker" | "sharedworker"; readonly url: string; postMessage(message: pxt.ServiceWorkerEvent | pxt.ServiceWorkerMessage): void; } enum DisconnectResponse { Disconnected, Waiting, TimedOut } initWebappServiceWorker(); initWebUSB(); function initWebappServiceWorker() { // Empty string for released, otherwise contains the ref or version path const ref = `@relprefix@`.replace("---", "").replace(/^\//, ""); // We don't do offline for version paths, only named releases const isNamedEndpoint = ref.indexOf("/") === -1; // pxtRelId is replaced with the commit hash for this release const refCacheName = "makecode;" + ref + ";@pxtRelId@"; const cdnUrl = `@cdnUrl@`; const webappUrls = [ // The current page `@targetUrl@/` + ref, `@simUrl@`, // webapp files `/blb/semantic.js`, `/blb/main.js`, `/blb/pxtapp.js`, `/blb/typescript.js`, `/blb/marked/marked.min.js`, `/blb/highlight.js/highlight.pack.js`, `/blb/jquery.js`, `/blb/pxtlib.js`, `/blb/pxtcompiler.js`, `/blb/pxtpy.js`, `/blb/pxtblockly.js`, `/blb/pxtwinrt.js`, `/blb/pxteditor.js`, `/blb/pxtsim.js`, `/blb/pxtembed.js`, `/blb/pxtworker.js`, `/blb/pxtweb.js`, `/blb/blockly.css`, `/blb/semantic.css`, `/blb/rtlsemantic.css`, // blockly `/cdn/blockly/media/sprites.png`, `/cdn/blockly/media/click.mp3`, `/cdn/blockly/media/disconnect.wav`, `/cdn/blockly/media/delete.mp3`, // monaco; keep in sync with webapp/public/index.html `/blb/vs/loader.js`, `/blb/vs/base/worker/workerMain.js`, `/blb/vs/basic-languages/bat/bat.js`, `/blb/vs/basic-languages/cpp/cpp.js`, `/blb/vs/basic-languages/python/python.js`, `/blb/vs/basic-languages/markdown/markdown.js`, `/blb/vs/editor/editor.main.css`, `/blb/vs/editor/editor.main.js`, `/blb/vs/editor/editor.main.nls.js`, `/blb/vs/language/json/jsonMode.js`, `/blb/vs/language/json/jsonWorker.js`, // charts `/blb/smoothie/smoothie_compressed.js`, `/blb/images/Bars_black.gif`, // gifjs `/blb/gifjs/gif.js`, // ai `/blb/ai.0.js`, // target `/blb/target.js`, // These macros should be replaced by the backend `@targetFieldEditorsJs@`, `@targetEditorJs@`, `@defaultLocaleStrings@`, `@targetUrl@@monacoworkerjs@`, `@targetUrl@@workerjs@` ]; // Replaced by the backend by a list of encoded urls separated by semicolons const cachedHexFiles = decodeURLs(`@cachedHexFilesEncoded@`); const cachedTargetImages = decodeURLs(`@targetImagesEncoded@`); // Duplicate entries in this list will cause an exception so call dedupe // just in case const allFiles = dedupe(webappUrls.concat(cachedTargetImages) .map(url => url.trim()) .filter(url => !!url && url.indexOf("@") !== 0)); let didInstall = false; self.addEventListener("install", (ev: ServiceWorkerEvent) => { if (!isNamedEndpoint) { console.log("Skipping service worker install for unnamed endpoint"); return; } didInstall = true; console.log("Installing service worker...") ev.waitUntil(caches.open(refCacheName) .then(cache => { console.log("Opened cache"); console.log("Caching:\n" + allFiles.join("\n")); return cache.addAll(allFiles).then(() => cache); }) .then(cache => cache.addAll(cachedHexFiles).catch(e => { // Hex files might return a 404 if they haven't hit the backend yet. We // need to catch the exception or the service worker will fail to install console.log("Failed to cache hexfiles") }) ) .then(() => (self as any).skipWaiting())) }); self.addEventListener("activate", (ev: ServiceWorkerEvent) => { if (!isNamedEndpoint) { console.log("Skipping service worker activate for unnamed endpoint"); return; } console.log("Activating service worker...") ev.waitUntil(caches.keys() .then(cacheNames => { // Delete all caches that "belong" to this ref except for the current version const toDelete = cacheNames.filter(c => { const cacheRef = getRefFromCacheName(c); return cacheRef === null || (cacheRef === ref && c !== refCacheName); }) return Promise.all( toDelete.map(name => caches.delete(name)) ); }) .then(() => { if (didInstall) { // Only notify clients for the first activation didInstall = false; return notifyAllClientsAsync(); } return Promise.resolve(); })) }); self.addEventListener("fetch", (ev: ServiceWorkerEvent) => { ev.respondWith(caches.match(ev.request) .then(response => { return response || fetch(ev.request) })) }); function dedupe(urls: string[]) { const res: string[] = []; for (const url of urls) { if (res.indexOf(url) === -1) res.push(url) } return res; } function getRefFromCacheName(name: string) { const parts = name.split(";"); if (parts.length !== 3) return null; return parts[1]; } function decodeURLs(encodedURLs: string) { // Charcode 64 is '@', we need to calculate it because otherwise the minifier // will combine the string concatenation into @cdnUrl@ and get mangled by the backend const cdnEscaped = String.fromCharCode(64) + "cdnUrl" + String.fromCharCode(64); return dedupe( encodedURLs.split(";") .map(encoded => decodeURIComponent(encoded).replace(cdnEscaped, cdnUrl).trim() ) ); } function notifyAllClientsAsync() { const scope = (self as unknown as ServiceWorkerScope); return scope.clients.claim().then(() => scope.clients.matchAll()).then(clients => { clients.forEach(client => client.postMessage({ type: "serviceworker", state: "activated", ref: ref })) }); } } // The ServiceWorker manages the webUSB sharing between tabs/windows in the browser. Only // one client can connect to webUSB at a time function initWebUSB() { // Webusb doesn't love it when we connect/reconnect too quickly const minimumLockWaitTime = 4000; // The ID of the client who currently has the lock on webUSB let lockGranted: string; let lastLockTime = 0; let waitingLock: string; let state: "waiting" | "granting" | "idle" = "idle"; let pendingDisconnectResolver: (resp: DisconnectResponse) => void; let statusResolver: (lock: string) => void; self.addEventListener("message", async (ev: MessageEvent) => { const message: pxt.ServiceWorkerClientMessage = ev.data; if (message?.type === "serviceworkerclient") { if (message.action === "request-packet-io-lock") { if (!lockGranted) lockGranted = await checkForExistingLockAsync(); // Deny the lock if we are in the process of granting it to someone else if (state === "granting") { await sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-lock-granted", granted: false, lock: message.lock }); return; } console.log("Received lock request " + message.lock); // Throttle reconnect requests const timeSinceLastLock = Date.now() - lastLockTime; waitingLock = message.lock; if (timeSinceLastLock < minimumLockWaitTime) { state = "waiting"; console.log("Waiting to grant lock request " + message.lock); await delay(minimumLockWaitTime - timeSinceLastLock); } // We received a more recent request while we were waiting, so abandon this one if (waitingLock !== message.lock) { console.log("Rejecting old lock request " + message.lock); await sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-lock-granted", granted: false, lock: message.lock }); return; } state = "granting"; // First we need to tell whoever currently has the lock to disconnect // and poll until they have finished if (lockGranted) { let resp: DisconnectResponse; do { console.log("Sending disconnect request " + message.lock); resp = await waitForLockDisconnectAsync(); if (resp === DisconnectResponse.Waiting) { console.log("Waiting on disconnect request " + message.lock); await delay(1000); } } while (resp === DisconnectResponse.Waiting) } // Now we can notify that the request has been granted console.log("Granted lock request " + message.lock); lockGranted = message.lock; await sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-lock-granted", granted: true, lock: message.lock }); lastLockTime = Date.now(); state = "idle"; } else if (message.action === "release-packet-io-lock") { // The client released the webusb lock for some reason (e.g. went to home screen) console.log("Received disconnect for " + lockGranted); lockGranted = undefined; if (pendingDisconnectResolver) pendingDisconnectResolver(DisconnectResponse.Disconnected); } else if (message.action === "packet-io-lock-disconnect") { // Response to a disconnect request we sent console.log("Received disconnect response for " + lockGranted); if (message.didDisconnect) lockGranted = undefined; if (pendingDisconnectResolver) pendingDisconnectResolver(message.didDisconnect ? DisconnectResponse.Disconnected : DisconnectResponse.Waiting); } else if (message.action === "packet-io-supported") { await sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-supported", supported: true }); } else if (message.action === "packet-io-status" && message.hasLock && statusResolver) { statusResolver(message.lock); } } }); async function sendToAllClientsAsync(message: pxt.ServiceWorkerMessage) { const clients = await (self as unknown as ServiceWorkerScope).clients.matchAll() clients.forEach(c => c.postMessage(message)) } // Waits for the disconnect and times-out after 5 seconds if there is no response function waitForLockDisconnectAsync() { let ref: any; const promise = new Promise<DisconnectResponse>((resolve) => { console.log("Waiting for disconnect " + lockGranted); pendingDisconnectResolver = resolve; sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-lock-disconnect", lock: lockGranted }); }) const timeoutPromise = new Promise<DisconnectResponse>(resolve => { ref = setTimeout(() => { console.log("Timed-out disconnect request " + lockGranted); resolve(DisconnectResponse.TimedOut); }, 5000) }); return Promise.race([ promise, timeoutPromise ]) .then(resp => { clearTimeout(ref); pendingDisconnectResolver = undefined return resp; }); } function checkForExistingLockAsync() { if (lockGranted) return Promise.resolve(lockGranted); let ref: any; const promise = new Promise<string>(resolve => { console.log("check for existing lock"); statusResolver = resolve; sendToAllClientsAsync({ type: "serviceworker", action: "packet-io-status" }); }) const timeoutPromise = new Promise<string>(resolve => { ref = setTimeout(() => { console.log("Timed-out check for existing lock"); resolve(undefined); }, 1000) }); return Promise.race([ promise, timeoutPromise ]) .then(resp => { clearTimeout(ref); statusResolver = undefined return resp; }); } function delay(millis: number): Promise<void> { return new Promise(resolve => { setTimeout(resolve, millis); }); } }
the_stack
import { Parameters } from "./parameters"; interface URIObject { scheme: string; user: string | undefined; host: string; port: number | undefined; } /** * URI. * @public */ export class URI extends Parameters { public headers: {[name: string]: Array<string>} = {}; private normal: URIObject; private raw: URIObject; /** * Constructor * @param scheme - * @param user - * @param host - * @param port - * @param parameters - * @param headers - */ constructor( scheme = "sip", user: string, host: string, port?: number, parameters?: { [name: string]: string | number | null }, headers?: {[name: string]: Array<string>} ) { super(parameters || {}); // Checks if (!host) { throw new TypeError('missing or invalid "host" parameter'); } for (const header in headers) { // eslint-disable-next-line no-prototype-builtins if (headers.hasOwnProperty(header)) { this.setHeader(header, headers[header]); } } // Raw URI this.raw = { scheme, user, host, port }; // Normalized URI this.normal = { scheme: scheme.toLowerCase(), user, host: host.toLowerCase(), port }; } get scheme(): string { return this.normal.scheme; } set scheme(value: string) { this.raw.scheme = value; this.normal.scheme = value.toLowerCase(); } get user(): string | undefined { return this.normal.user; } set user(value: string | undefined) { this.normal.user = this.raw.user = value; } get host(): string { return this.normal.host; } set host(value: string) { this.raw.host = value; this.normal.host = value.toLowerCase(); } get aor(): string { return this.normal.user + "@" + this.normal.host; } get port(): number | undefined { return this.normal.port; } set port(value: number | undefined) { this.normal.port = this.raw.port = value === 0 ? value : value; } public setHeader(name: string, value: Array<string> | string): void { this.headers[this.headerize(name)] = (value instanceof Array) ? value : [value]; } public getHeader(name: string): Array<string> | undefined { if (name) { return this.headers[this.headerize(name)]; } } public hasHeader(name: string): boolean { // eslint-disable-next-line no-prototype-builtins return !!name && !!this.headers.hasOwnProperty(this.headerize(name)); } public deleteHeader(header: string): Array<string> | undefined { header = this.headerize(header); // eslint-disable-next-line no-prototype-builtins if (this.headers.hasOwnProperty(header)) { const value = this.headers[header]; delete this.headers[header]; return value; } } public clearHeaders(): void { this.headers = {}; } public clone(): URI { return new URI( this._raw.scheme, this._raw.user || "", this._raw.host, this._raw.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); } public toRaw(): string { return this._toString(this._raw); } public toString(): string { return this._toString(this._normal); } private get _normal(): URIObject { return this.normal; } private get _raw(): URIObject { return this.raw; } private _toString(uri: any): string { let uriString: string = uri.scheme + ":"; // add slashes if it's not a sip(s) URI if (!uri.scheme.toLowerCase().match("^sips?$")) { uriString += "//"; } if (uri.user) { uriString += this.escapeUser(uri.user) + "@"; } uriString += uri.host; if (uri.port || uri.port === 0) { uriString += ":" + uri.port; } for (const parameter in this.parameters) { // eslint-disable-next-line no-prototype-builtins if (this.parameters.hasOwnProperty(parameter)) { uriString += ";" + parameter; if (this.parameters[parameter] !== null) { uriString += "=" + this.parameters[parameter]; } } } const headers: Array<string> = []; for (const header in this.headers) { // eslint-disable-next-line no-prototype-builtins if (this.headers.hasOwnProperty(header)) { // eslint-disable-next-line @typescript-eslint/no-for-in-array for (const idx in this.headers[header]) { // eslint-disable-next-line no-prototype-builtins if (this.headers[header].hasOwnProperty(idx)) { headers.push(header + "=" + this.headers[header][idx]); } } } } if (headers.length > 0) { uriString += "?" + headers.join("&"); } return uriString; } /* * Hex-escape a SIP URI user. * @private * @param {String} user */ private escapeUser(user: string): string { let decodedUser: string; // FIXME: This is called by toString above which should never throw, but // decodeURIComponent can throw and I've seen one case in production where // it did throw resulting in a cascading failure. This class should be // fixed so that decodeURIComponent is not called at this point (in toString). // The user should be decoded when the URI is constructor or some other // place where we can catch the error before the URI is created or somesuch. // eslint-disable-next-line no-useless-catch try { decodedUser = decodeURIComponent(user); } catch (error) { throw error; } // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). return encodeURIComponent(decodedUser) .replace(/%3A/ig, ":") .replace(/%2B/ig, "+") .replace(/%3F/ig, "?") .replace(/%2F/ig, "/"); } private headerize(str: string): string { const exceptions: any = { "Call-Id": "Call-ID", "Cseq": "CSeq", "Min-Se": "Min-SE", "Rack": "RAck", "Rseq": "RSeq", "Www-Authenticate": "WWW-Authenticate", }; const name: Array<string> = str.toLowerCase().replace(/_/g, "-").split("-"); const parts: number = name.length; let hname = ""; for (let part = 0; part < parts; part++) { if (part !== 0) { hname += "-"; } hname += name[part].charAt(0).toUpperCase() + name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; } } /** * Returns true if URIs are equivalent per RFC 3261 Section 19.1.4. * @param a URI to compare * @param b URI to compare * * @remarks * 19.1.4 URI Comparison * Some operations in this specification require determining whether two * SIP or SIPS URIs are equivalent. * * https://tools.ietf.org/html/rfc3261#section-19.1.4 * @internal */ export function equivalentURI(a: URI, b: URI): boolean { // o A SIP and SIPS URI are never equivalent. if (a.scheme !== b.scheme) { return false; } // o Comparison of the userinfo of SIP and SIPS URIs is case- // sensitive. This includes userinfo containing passwords or // formatted as telephone-subscribers. Comparison of all other // components of the URI is case-insensitive unless explicitly // defined otherwise. // // o The ordering of parameters and header fields is not significant // in comparing SIP and SIPS URIs. // // o Characters other than those in the "reserved" set (see RFC 2396 // [5]) are equivalent to their ""%" HEX HEX" encoding. // // o An IP address that is the result of a DNS lookup of a host name // does not match that host name. // // o For two URIs to be equal, the user, password, host, and port // components must match. // // A URI omitting the user component will not match a URI that // includes one. A URI omitting the password component will not // match a URI that includes one. // // A URI omitting any component with a default value will not // match a URI explicitly containing that component with its // default value. For instance, a URI omitting the optional port // component will not match a URI explicitly declaring port 5060. // The same is true for the transport-parameter, ttl-parameter, // user-parameter, and method components. // // Defining sip:user@host to not be equivalent to // sip:user@host:5060 is a change from RFC 2543. When deriving // addresses from URIs, equivalent addresses are expected from // equivalent URIs. The URI sip:user@host:5060 will always // resolve to port 5060. The URI sip:user@host may resolve to // other ports through the DNS SRV mechanisms detailed in [4]. // FIXME: TODO: // - character compared to hex encoding is not handled // - password does not exist on URI currently if (a.user !== b.user || a.host !== b.host || a.port !== b.port) { return false; } // o URI uri-parameter components are compared as follows: function compareParameters(a: URI, b: URI): boolean { // - Any uri-parameter appearing in both URIs must match. const parameterKeysA = Object.keys(a.parameters); const parameterKeysB = Object.keys(b.parameters); const intersection = parameterKeysA.filter(x => parameterKeysB.includes(x)); if (!intersection.every(key => a.parameters[key] === b.parameters[key])) { return false; } // - A user, ttl, or method uri-parameter appearing in only one // URI never matches, even if it contains the default value. if (!["user", "ttl", "method", "transport"].every(key => a.hasParam(key) && b.hasParam(key) || !a.hasParam(key) && !b.hasParam(key))) { return false; } // - A URI that includes an maddr parameter will not match a URI // that contains no maddr parameter. if (!["maddr"].every(key => a.hasParam(key) && b.hasParam(key) || !a.hasParam(key) && !b.hasParam(key))) { return false; } // - All other uri-parameters appearing in only one URI are // ignored when comparing the URIs. return true; } if (!compareParameters(a, b)) { return false; } // o URI header components are never ignored. Any present header // component MUST be present in both URIs and match for the URIs // to match. The matching rules are defined for each header field // in Section 20. const headerKeysA = Object.keys(a.headers); const headerKeysB = Object.keys(b.headers); // No need to check if no headers if (headerKeysA.length !== 0 || headerKeysB.length !== 0) { // Must have same number of headers if (headerKeysA.length !== headerKeysB.length) { return false; } // Must have same headers const intersection = headerKeysA.filter(x => headerKeysB.includes(x)); if (intersection.length !== headerKeysB.length) { return false; } // FIXME: Not to spec. But perhaps not worth fixing? // Must have same header values // It seems too much to consider multiple headers with same name. // It seems too much to compare two header params according to the rule of each header. // We'll assume a single header and compare them string to string... if (!intersection.every(key => a.headers[key].length && b.headers[key].length && a.headers[key][0] === b.headers[key][0])) { return false; } } return true; }
the_stack
import * as path from 'path'; import * as util from 'util'; import * as os from 'os'; import * as crypto from 'crypto'; import * as BBPromise from 'bluebird'; import * as _ from 'lodash'; // Local // New messages (move to this) import { LoggerLevel, Messages, SfdxError } from '@salesforce/core'; BBPromise.promisifyAll(require('fs-extra')); BBPromise.promisifyAll(require('xml2js')); Messages.importMessagesDirectory(__dirname); import ux from 'cli-ux'; import MessagesLocal = require('../messages'); import SettingsGenerator = require('../org/scratchOrgSettingsGenerator'); import ProfileApi = require('../package/profileApi'); import SourceConvertCommand = require('../source/sourceConvertCommand'); import srcDevUtil = require('../core/srcDevUtil'); import logApi = require('../core/logApi'); import * as almError from '../core/almError'; import pkgUtils = require('./packageUtils'); import PackageVersionCreateRequestApi = require('./packageVersionCreateRequestApi'); const fs = BBPromise.promisifyAll(require('fs-extra')); const xml2js = BBPromise.promisifyAll(require('xml2js')); import consts = require('../core/constants'); const messages = MessagesLocal(); const DESCRIPTOR_FILE = 'package2-descriptor.json'; let logger; const POLL_INTERVAL_WITHOUT_VALIDATION_SECONDS = 5; class PackageVersionCreateCommand { // TODO: proper property typing // eslint-disable-next-line no-undef [property: string]: any; constructor() { this.pollInterval = pkgUtils.POLL_INTERVAL_SECONDS; this.maxRetries = 0; logger = logApi.child('package:version:create'); } // convert source to mdapi format and copy to tmp dir packaging up _generateMDFolderForArtifact(options) { const convertCmd = new SourceConvertCommand(); const context = { flags: { rootdir: options.sourcedir, outputdir: options.deploydir, }, }; return BBPromise.resolve() .then(() => convertCmd.validate(context)) .then((fixedcontext) => convertCmd.execute(fixedcontext)); } _validateDependencyValues(dependency) { // If valid 04t package, just return it to be used straight away. if (dependency.subscriberPackageVersionId) { pkgUtils.validateId(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, dependency.subscriberPackageVersionId); return BBPromise.resolve(); } if (dependency.packageId && dependency.package) { throw new Error(messages.getMessage('errorPackageAndPackageIdCollision', [], 'package_version_create')); } const packageIdFromAlias = pkgUtils.getPackageIdFromAlias(dependency.packageId || dependency.package, this.force); // If valid 04t package, just return it to be used straight away. if (pkgUtils.validateIdNoThrow(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, packageIdFromAlias)) { dependency.subscriberPackageVersionId = packageIdFromAlias; return BBPromise.resolve(); } if (!packageIdFromAlias || !dependency.versionNumber) { throw new Error( messages.getMessage('errorDependencyPair', [JSON.stringify(dependency)], 'package_version_create') ); } // Just override dependency.packageId value to the resolved alias. dependency.packageId = packageIdFromAlias; pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, dependency.packageId); pkgUtils.validateVersionNumber( dependency.versionNumber, pkgUtils.LATEST_BUILD_NUMBER_TOKEN, pkgUtils.RELEASED_BUILD_NUMBER_TOKEN ); // Validate that the Package2 id exists on the server const query = `SELECT Id FROM Package2 WHERE Id = '${dependency.packageId}'`; return this.force.toolingQuery(this.org, query).then((pkgQueryResult) => { const subRecords = pkgQueryResult.records; if (!subRecords || subRecords.length !== 1) { throw new Error(messages.getMessage('errorNoIdInHub', [dependency.packageId], 'package_version_create')); } }); } /** * A dependency in the workspace config file may be specified using either a subscriber package version id (04t) * or a package Id (0Ho) + a version number. Additionally, a build number may be the actual build number, or a * keyword: LATEST or RELEASED (meaning the latest or released build number for a given major.minor.patch). * * This method resolves a package Id + version number to a subscriber package version id (04t) * and adds it as a SubscriberPackageVersionId parameter in the dependency object. */ _retrieveSubscriberPackageVersionId(dependency, branchFromFlagOrDef) { return BBPromise.resolve().then(() => this._validateDependencyValues(dependency).then(() => { if (dependency.subscriberPackageVersionId) { delete dependency.package; // if an 04t id is specified just use it. return dependency; } const versionNumber = dependency.versionNumber.split(pkgUtils.VERSION_NUMBER_SEP); const buildNumber = versionNumber[3]; // use the dependency.branch if present otherwise use the branch of the version being created const branch = dependency.branch || dependency.branch === '' ? dependency.branch : branchFromFlagOrDef; const branchString = _.isNil(branch) || branch === '' ? 'null' : `'${branch}'`; // resolve a build number keyword to an actual number, if needed return this._resolveBuildNumber(versionNumber, dependency.packageId, branch).then((queryResult) => { const records = queryResult.records; if (!records || records.length === 0 || records[0].expr0 == null) { if (buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN) { throw new Error( `No released version was found in Dev Hub for package id ${ dependency.packageId } and version number ${versionNumber.join(pkgUtils.VERSION_NUMBER_SEP)}` ); } else { throw new Error( `No version number was found in Dev Hub for package id ${ dependency.packageId } and branch ${branchString} and version number ${versionNumber.join(pkgUtils.VERSION_NUMBER_SEP)}` ); } } // now that we have a full build number, query for the associated 04t. // because the build number may not be unique across versions, add in conditionals for // the branch or the RELEASED token (if used) const resolvedBuildNumber = records[0].expr0; const branchOrReleasedCondition = buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN ? 'AND IsReleased = true' : `AND Branch = ${branchString}`; const query = `SELECT SubscriberPackageVersionId FROM Package2Version WHERE Package2Id = '${dependency.packageId}' AND MajorVersion = ${versionNumber[0]} AND MinorVersion = ${versionNumber[1]} AND PatchVersion = ${versionNumber[2]} AND BuildNumber = ${resolvedBuildNumber} ${branchOrReleasedCondition}`; return this.force.toolingQuery(this.org, query).then((pkgVerQueryResult) => { const subRecords = pkgVerQueryResult.records; if (!subRecords || subRecords.length !== 1) { throw new Error( `No version number was found in Dev Hub for package id ${ dependency.packageId } and branch ${branchString} and version number ${versionNumber.join( pkgUtils.VERSION_NUMBER_SEP )} that resolved to build number ${resolvedBuildNumber}` ); } dependency.subscriberPackageVersionId = pkgVerQueryResult.records[0].SubscriberPackageVersionId; // warn user of the resolved build number when LATEST and RELEASED keywords are used if (Number.isNaN(parseInt(buildNumber))) { versionNumber[3] = resolvedBuildNumber; if (buildNumber === pkgUtils.LATEST_BUILD_NUMBER_TOKEN) { logger.log( messages.getMessage( 'buildNumberResolvedForLatest', [ dependency.package, versionNumber.join(pkgUtils.VERSION_NUMBER_SEP), branchString, dependency.subscriberPackageVersionId, ], 'package_version_create' ) ); } else if (buildNumber === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN) { logger.log( messages.getMessage( 'buildNumberResolvedForReleased', [ dependency.package, versionNumber.join(pkgUtils.VERSION_NUMBER_SEP), dependency.subscriberPackageVersionId, ], 'package_version_create' ) ); } } delete dependency.packageId; delete dependency.package; delete dependency.versionNumber; delete dependency.branch; return dependency; }); }); }) ); } _resolveBuildNumber(versionNumber, packageId, branch) { return BBPromise.resolve().then(() => { if (!Number.isNaN(parseInt(versionNumber[3]))) { // The build number is already specified so just return it using the tooling query result obj structure return { records: [{ expr0: versionNumber[3] }] }; } // query for the LATEST or RELEASED build number let branchCondition = ''; let releasedCondition = ''; if (versionNumber[3] === pkgUtils.LATEST_BUILD_NUMBER_TOKEN) { // respect the branch when querying for LATEST const branchString = _.isNil(branch) || branch === '' ? 'null' : `'${branch}'`; branchCondition = `AND Branch = ${branchString}`; } else if (versionNumber[3] === pkgUtils.RELEASED_BUILD_NUMBER_TOKEN) { releasedCondition = 'AND IsReleased = true'; } const query = `SELECT MAX(BuildNumber) FROM Package2Version WHERE Package2Id = '${packageId}' AND MajorVersion = ${versionNumber[0]} AND MinorVersion = ${versionNumber[1]} AND PatchVersion = ${versionNumber[2]} ${branchCondition} ${releasedCondition}`; return this.force.toolingQuery(this.org, query); }); } _createRequestObject(packageId, context, preserveFiles, packageVersTmpRoot, packageVersBlobZipFile) { const zipFileBase64 = fs.readFileSync(packageVersBlobZipFile).toString('base64'); const requestObject = { Package2Id: packageId, VersionInfo: zipFileBase64, Tag: context.flags.tag, Branch: context.flags.branch, InstallKey: context.flags.installationkey, Instance: context.flags.buildinstance, SourceOrg: context.flags.sourceorg, CalculateCodeCoverage: context.flags.codecoverage, SkipValidation: context.flags.skipvalidation, }; if (preserveFiles) { logger.log(messages.getMessage('tempFileLocation', [packageVersTmpRoot], 'package_version_create')); return requestObject; } else { return fs.removeAsync(packageVersTmpRoot).then(() => requestObject); } } _getPackageDescriptorJsonFromPackageId(packageId, flags) { const artDir = flags.path; const packageDescriptorJson = this.packageDirs.find((packageDir) => { const packageDirPackageId = pkgUtils.getPackageIdFromAlias(packageDir.package, this.force); return !_.isNil(packageDirPackageId) && packageDirPackageId === packageId ? packageDir : null; }); if (!packageDescriptorJson) { throw new Error(`${consts.WORKSPACE_CONFIG_FILENAME} does not contain a packaging directory for ${artDir}`); } return packageDescriptorJson; } /** * Convert the list of command line options to a JSON object that can be used to create an Package2VersionCreateRequest entity. * * @param context * @param packageId * @returns {{Package2Id: (*|p|boolean), Package2VersionMetadata: *, Tag: *, Branch: number}} * @private */ _createPackageVersionCreateRequestFromOptions(context, packageId) { const artDir = context.flags.path; const preserveFiles = !util.isNullOrUndefined( context.flags.preserve || process.env.SFDX_PACKAGE2_VERSION_CREATE_PRESERVE ); const uniqueHash = crypto.createHash('sha1').update(`${Date.now()}${Math.random()}`).digest('hex'); const packageVersTmpRoot = path.join(os.tmpdir(), `${packageId}-${uniqueHash}`); const packageVersMetadataFolder = path.join(packageVersTmpRoot, 'md-files'); const unpackagedMetadataFolder = path.join(packageVersTmpRoot, 'unpackaged-md-files'); const packageVersProfileFolder = path.join(packageVersMetadataFolder, 'profiles'); const packageVersBlobDirectory = path.join(packageVersTmpRoot, 'package-version-info'); const metadataZipFile = path.join(packageVersBlobDirectory, 'package.zip'); const unpackagedMetadataZipFile = path.join(packageVersBlobDirectory, 'unpackaged-metadata-package.zip'); const settingsZipFile = path.join(packageVersBlobDirectory, 'settings.zip'); const packageVersBlobZipFile = path.join(packageVersTmpRoot, 'package-version-info.zip'); const sourceBaseDir = path.join(context.org.force.getConfig().getProjectPath(), artDir); const mdOptions = { deploydir: packageVersMetadataFolder, sourcedir: sourceBaseDir, }; // Stores any additional client side info that might be needed later on in the process const clientSideInfo = new Map(); const settingsGenerator = new SettingsGenerator(); let hasUnpackagedMetadata = false; // Copy all of the metadata from the workspace to a tmp folder return ( this._generateMDFolderForArtifact(mdOptions) .then(async () => { const packageDescriptorJson = this._getPackageDescriptorJsonFromPackageId(packageId, context.flags); if (Object.prototype.hasOwnProperty.call(packageDescriptorJson, 'package')) { delete packageDescriptorJson.package; packageDescriptorJson.id = packageId; } const definitionFile = context.flags.definitionfile ? context.flags.definitionfile : packageDescriptorJson['definitionFile']; if (definitionFile) { // package2-descriptor.json sent to the server should contain only the features, snapshot & orgPreferences // defined in the definition file. delete packageDescriptorJson.features; delete packageDescriptorJson.orgPreferences; delete packageDescriptorJson.definitionFile; delete packageDescriptorJson.snapshot; const definitionFilePayload = await fs.readFileAsync(definitionFile, 'utf8'); const definitionFileJson = JSON.parse(definitionFilePayload); const pkgProperties = [ 'country', 'edition', 'language', 'features', 'orgPreferences', 'snapshot', 'release', ]; // Load any settings from the definition await settingsGenerator.extract(definitionFileJson); if (settingsGenerator.hasSettings() && definitionFileJson['orgPreferences']) { // this is not allowed, exit with an error return BBPromise.reject(almError('signupDuplicateSettingsSpecified')); } pkgProperties.forEach((prop) => { const propValue = definitionFileJson[prop]; if (propValue) { packageDescriptorJson[prop] = propValue; } }); } return [packageDescriptorJson]; }) .spread((packageDescriptorJson) => { let unpackagedPromise = null; // Add the Unpackaged Metadata, if any, to the output directory, only when code coverage is specified if ( packageDescriptorJson.unpackagedMetadata && packageDescriptorJson.unpackagedMetadata.path && context.flags.codecoverage ) { hasUnpackagedMetadata = true; const unpackagedPath = path.join(process.cwd(), packageDescriptorJson.unpackagedMetadata.path); try { fs.statSync(unpackagedPath); } catch (err) { throw new Error( `Unpackaged metadata directory '${packageDescriptorJson.unpackagedMetadata.path}' was specified but does not exist` ); } srcDevUtil.ensureDirectoryExistsSync(unpackagedMetadataFolder); unpackagedPromise = this._generateMDFolderForArtifact({ deploydir: unpackagedMetadataFolder, sourcedir: unpackagedPath, }); // Set which package is the "unpackaged" package clientSideInfo.set('UnpackagedMetadataPath', packageDescriptorJson.unpackagedMetadata.path); } return [packageDescriptorJson, unpackagedPromise]; }) .spread((packageDescriptorJson) => { // Process permissionSet and permissionSetLicenses that should be enabled when running Apex tests // This only applies if code coverage is enabled if (context.flags.codecoverage) { // Assuming no permission sets are named 0, 0n, null, undefined, false, NaN, and the empty string if (packageDescriptorJson.apexTestAccess && packageDescriptorJson.apexTestAccess.permissionSets) { let permSets = packageDescriptorJson.apexTestAccess.permissionSets; if (!Array.isArray(permSets)) { permSets = permSets.split(','); } packageDescriptorJson.permissionSetNames = permSets.map((s) => s.trim()); } if (packageDescriptorJson.apexTestAccess && packageDescriptorJson.apexTestAccess.permissionSetLicenses) { let permissionSetLicenses = packageDescriptorJson.apexTestAccess.permissionSetLicenses; if (!Array.isArray(permissionSetLicenses)) { permissionSetLicenses = permissionSetLicenses.split(','); } packageDescriptorJson.permissionSetLicenseDeveloperNames = permissionSetLicenses.map((s) => s.trim()); } } delete packageDescriptorJson.apexTestAccess; return [packageDescriptorJson]; }) .spread((packageDescriptorJson) => { // All dependencies for the packaging dir should be resolved to an 04t id to be passed to the server. // (see _retrieveSubscriberPackageVersionId for details) const dependencies = packageDescriptorJson.dependencies; // branch can be set via flag or descriptor; flag takes precedence context.flags.branch = context.flags.branch ? context.flags.branch : packageDescriptorJson.branch; const operations = _.isNil(dependencies) ? [] : dependencies.map((dependency) => this._retrieveSubscriberPackageVersionId(dependency, context.flags.branch) ); return [ BBPromise.all(operations), pkgUtils.getAncestorId(packageDescriptorJson, this.force, this.org), packageDescriptorJson, ]; }) // eslint-disable-next-line @typescript-eslint/require-await .spread(async (resultValues, ancestorId, packageDescriptorJson) => { // If dependencies exist, the resultValues array will contain the dependencies populated with a resolved // subscriber pkg version id. if (resultValues.length > 0) { packageDescriptorJson.dependencies = resultValues; } this._cleanPackageDescriptorJson(packageDescriptorJson); this._setPackageDescriptorJsonValues(packageDescriptorJson, context); srcDevUtil.ensureDirectoryExistsSync(packageVersTmpRoot); srcDevUtil.ensureDirectoryExistsSync(packageVersBlobDirectory); if (Object.prototype.hasOwnProperty.call(packageDescriptorJson, 'ancestorVersion')) { delete packageDescriptorJson.ancestorVersion; } packageDescriptorJson.ancestorId = ancestorId; return fs.writeJSONAsync(path.join(packageVersBlobDirectory, DESCRIPTOR_FILE), packageDescriptorJson); }) // As part of the source convert process, the package.xml has been written into the tmp metadata directory. // The package.xml may need to be manipulated due to processing profiles in the workspace or additional // metadata exclusions. If necessary, read the existing package.xml and then re-write it. .then(() => fs.readFileAsync(path.join(packageVersMetadataFolder, 'package.xml'), 'utf8')) .then((currentPackageXml) => // convert to json xml2js.parseStringAsync(currentPackageXml) ) .then((packageJson) => { srcDevUtil.ensureDirectoryExistsSync(packageVersMetadataFolder); srcDevUtil.ensureDirectoryExistsSync(packageVersProfileFolder); // Apply any necessary exclusions to typesArr. let typesArr = packageJson.Package.types; // if we're using unpackaged metadata, don't package the profiles located there if (hasUnpackagedMetadata) { typesArr = this.profileApi.filterAndGenerateProfilesForManifest(typesArr, [ clientSideInfo.get('UnpackagedMetadataPath'), ]); } else { typesArr = this.profileApi.filterAndGenerateProfilesForManifest(typesArr); } // Next generate profiles and retrieve any profiles that were excluded because they had no matching nodes. const excludedProfiles = this.profileApi.generateProfiles( packageVersProfileFolder, { Package: { types: typesArr }, }, [clientSideInfo.get('UnpackagedMetadataPath')] ); if (excludedProfiles.length > 0) { const profileIdx = typesArr.findIndex((e) => e.name[0] === 'Profile'); typesArr[profileIdx].members = typesArr[profileIdx].members.filter( (e) => excludedProfiles.indexOf(e) === -1 ); } packageJson.Package.types = typesArr; // Re-write the package.xml in case profiles have been added or removed const xmlBuilder = new xml2js.Builder({ xmldec: { version: '1.0', encoding: 'UTF-8' }, }); const xml = xmlBuilder.buildObject(packageJson); // Log information about the profiles being packaged up let profiles = this.profileApi.getProfileInformation(); profiles.forEach((profile) => { if (logger.shouldLog(LoggerLevel.DEBUG)) { logger.log(profile.logDebug()); } else if (logger.shouldLog(LoggerLevel.INFO)) { logger.log(profile.logInfo()); } }); return fs.writeFileAsync(path.join(packageVersMetadataFolder, 'package.xml'), xml); }) .then(() => // Zip the packageVersMetadataFolder folder and put the zip in {packageVersBlobDirectory}/package.zip srcDevUtil.zipDir(packageVersMetadataFolder, metadataZipFile) ) .then(() => { if (hasUnpackagedMetadata) { // Zip the unpackagedMetadataFolder folder and put the zip in {packageVersBlobDirectory}/{unpackagedMetadataZipFile} return srcDevUtil.zipDir(unpackagedMetadataFolder, unpackagedMetadataZipFile); } }) .then(() => { // Zip up the expanded settings (if present) if (settingsGenerator.hasSettings()) { return settingsGenerator .createDeployDir(context.org.force.config.apiVersion) .then((settingsRoot) => srcDevUtil.zipDir(settingsRoot, settingsZipFile)); } return BBPromise.resolve(); }) // Zip the Version Info and package.zip files into another zip .then(() => srcDevUtil.zipDir(packageVersBlobDirectory, packageVersBlobZipFile)) .then(() => this._createRequestObject(packageId, context, preserveFiles, packageVersTmpRoot, packageVersBlobZipFile) ) ); } _getPackagePropertyFromPackage(packageDirs, packageValue, context) { let foundByPackage = packageDirs.find((x) => x['package'] === packageValue); let foundById = packageDirs.find((x) => x['id'] === packageValue); if (foundByPackage && foundById) { throw new Error(messages.getMessage('errorPackageAndIdCollision', [], 'package_version_create')); } // didn't find anything? let's see if we can reverse look up if (!foundByPackage && !foundById) { // is it an alias? const pkgId = pkgUtils.getPackageIdFromAlias(packageValue, this.force); if (pkgId === packageValue) { // not an alias, or not a valid one, try to reverse lookup an alias in case this is an id const aliases = pkgUtils.getPackageAliasesFromId(packageValue, this.force); // if we found an alias, try to look that up in the config. foundByPackage = aliases.some((alias) => packageDirs.find((x) => x['package'] === alias)); } else { // it is an alias; try to lookup it's id in the config foundByPackage = packageDirs.find((x) => x['package'] === pkgId); foundById = packageDirs.find((x) => x['id'] === pkgId); if (!foundByPackage && !foundById) { // check if any configs use a different alias to that same id const aliases = pkgUtils.getPackageAliasesFromId(pkgId, this.force); foundByPackage = aliases.some((alias) => { const pd = packageDirs.find((x) => x['package'] === alias); if (pd) { // if so, set context.flags.package to be this alias instead of the alternate context.flags.package = alias; } return pd; }); } } // if we still didn't find anything, throw the error if (!foundByPackage && !foundById) { throw new Error(messages.getMessage('errorMissingPackage', [pkgId], 'package_version_create')); } } return foundByPackage ? 'package' : 'id'; } _getPackageValuePropertyFromDirectory(context, directoryFlag) { const packageValue = this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'package', 'path', context.flags.path, directoryFlag ); const packageIdValue = this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'id', 'path', context.flags.path, directoryFlag ); let packagePropVal: any = {}; if (!packageValue && !packageIdValue) { throw new Error(messages.getMessage('errorMissingPackage', [], 'package_version_create')); } else if (packageValue && packageIdValue) { throw new Error(messages.getMessage('errorPackageAndIdCollision', [], 'package_version_create')); } else if (packageValue) { packagePropVal = { packageProperty: 'package', packageValue, }; } else { packagePropVal = { packageProperty: 'id', packageValue: packageIdValue, }; } return packagePropVal; } /** * Returns the property value that corresponds to the propertyToLookup. This value found for a particular * package directory element that matches the knownProperty and knownValue. In other words, we locate a package * directory element whose knownProperty matches the knownValue, then we grab the value for the propertyToLookup * and return it. * * @param context * @param packageDirs The list of all the package directories from the sfdx-project.json * @param propertyToLookup The property ID whose value we want to find * @param knownProperty The JSON property in the packageDirectories that is already known * @param knownValue The value that corresponds to the knownProperty in the packageDirectories JSON * @param knownFlag The flag details e.g. short/long name, etc. Only used for the error message */ _getConfigPackageDirectoriesValue(context, packageDirs, propertyToLookup, knownProperty, knownValue, knownFlag) { let value; let packageDir = packageDirs.find((x) => x[knownProperty] === knownValue); if (!packageDir && knownFlag.name === 'path' && knownValue.endsWith(path.sep)) { // if this is the directory flag, try removing the trailing slash added by CLI auto-complete const dirWithoutTrailingSlash = knownValue.slice(0, -1); packageDir = packageDirs.find((x) => x[knownProperty] === dirWithoutTrailingSlash); if (packageDir) { context.flags.path = dirWithoutTrailingSlash; } } // didn't find it with the package property, try a reverse lookup with alias and id if (!packageDir && knownProperty === 'package') { const pkgId = pkgUtils.getPackageIdFromAlias(knownValue, this.force); if (pkgId !== knownValue) { packageDir = packageDirs.find((x) => x[knownProperty] === pkgId); } else { const aliases = pkgUtils.getPackageAliasesFromId(knownValue, this.force); aliases.some((alias) => { packageDir = packageDirs.find((x) => x[knownProperty] === alias); return packageDir; }); } } if (packageDir) { value = packageDir[propertyToLookup]; } else { throw new Error( messages.getMessage( 'errorNoMatchingPackageDirectory', [`--${knownFlag.name} (-${knownFlag.char})`, knownValue, knownProperty], 'package_version_create' ) ); } return value; } execute(context) { return this._execute(context).catch((err) => { // TODO // until package2 is GA, wrap perm-based errors w/ 'contact sfdc' action (REMOVE once package2 is GA'd) err = pkgUtils.massageErrorMessage(err); throw pkgUtils.applyErrorAction(err); }); } // eslint-disable-next-line @typescript-eslint/require-await async _execute(context) { this.org = context.org; this.force = this.org.force; this.packageVersionCreateRequestApi = new PackageVersionCreateRequestApi(this.force, this.org); logger.setLevel(context.flags.loglevel); if (!context.flags.json && context.flags.skipvalidation === true) { ux.warn(messages.getMessage('skipValidationWarning', [], 'package_version_create')); } if (context.flags.wait) { if (context.flags.skipvalidation === true) { this.pollInterval = POLL_INTERVAL_WITHOUT_VALIDATION_SECONDS; } this.maxRetries = (60 / this.pollInterval) * context.flags.wait; } // This command requires either the ID flag or path flag. The // other needed value can be looked up from sfdx-project.json. As // this concept is not supported by the framework, manually check if // we have at least one of the flags const pathFlag = context.command.flags.find((x) => x.name === 'path'); const packageFlag = context.command.flags.find((x) => x.name === 'package'); if (!context.flags.package && !context.flags.path) { const errorString = messages.getMessage( 'errorMissingFlags', [`--${packageFlag.name} (-${packageFlag.char})`, `--${pathFlag.name} (-${pathFlag.char})`], 'package_version_create' ); const error = new Error(errorString); error['name'] = 'requiredFlagMissing'; return BBPromise.reject(error); } // This command does not allow --codecoverage and --skipvalidation at the same time if (context.flags.skipvalidation && context.flags.codecoverage) { const codeCovFlag = context.command.flags.find((x) => x.name === 'codecoverage'); const skipValFlag = context.command.flags.find((x) => x.name === 'skipvalidation'); const errorString = messages.getMessage( 'errorCannotSupplyCodeCoverageAndSkipValidation', [ `--${codeCovFlag.name} (-${codeCovFlag.char})`, `--${skipValFlag.name}`, `--${codeCovFlag.name} (-${codeCovFlag.char})`, `--${skipValFlag.name}`, ], 'package_version_create' ); const error = new Error(errorString); error['name'] = 'requiredFlagMissing'; return BBPromise.reject(error); } // This command also requires either the installationkey flag or installationkeybypass flag if (!context.flags.installationkey && !context.flags.installationkeybypass) { const installationKeyFlag = context.command.flags.find((x) => x.name === 'installationkey'); const installationKeyBypassFlag = context.command.flags.find((x) => x.name === 'installationkeybypass'); const errorString = messages.getMessage( 'errorMissingFlagsInstallationKey', [ `--${installationKeyFlag.name} (-${installationKeyFlag.char})`, `--${installationKeyBypassFlag.name} (-${installationKeyBypassFlag.char})`, ], 'package_version_create' ); const error = new Error(errorString); error['name'] = 'requiredFlagMissing'; return BBPromise.reject(error); } // For the first rollout of validating sfdx-project.json data against schema, make it optional and defaulted // to false. Validation only occurs if the hidden -j (--validateschema) flag has been specified. let configContentPromise; if (context.flags.validateschema) { configContentPromise = context.org.force.config.getConfigContentWithValidation(); } else { configContentPromise = BBPromise.resolve(context.org.force.config.getConfigContent()); } let canonicalPackageProperty; // Look up the missing value or confirm a match return configContentPromise.then(async (configContent) => { this.packageDirs = configContent.packageDirectories; // Check for empty packageDirectories if (!this.packageDirs) { throw new Error(messages.getMessage('errorEmptyPackageDirs', null, 'package_version_create')); } if (!context.flags.package) { const packageValProp = this._getPackageValuePropertyFromDirectory(context, pathFlag); context.flags.package = packageValProp.packageValue; canonicalPackageProperty = packageValProp.packageProperty; } else if (!context.flags.path) { canonicalPackageProperty = this._getPackagePropertyFromPackage( this.packageDirs, context.flags.package, context ); context.flags.path = this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'path', canonicalPackageProperty, context.flags.package, packageFlag ); } else { canonicalPackageProperty = this._getPackagePropertyFromPackage( this.packageDirs, context.flags.package, context ); this._getConfigPackageDirectoriesValue( context, this.packageDirs, canonicalPackageProperty, 'path', context.flags.path, pathFlag ); const expectedPackageId = this._getConfigPackageDirectoriesValue( context, this.packageDirs, canonicalPackageProperty, 'path', context.flags.path, pathFlag ); // This will thrown an error if the package id flag value doesn't match // any of the :id values in the package dirs. this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'path', canonicalPackageProperty, context.flags.package, packageFlag ); // This will thrown an error if the package id flag value doesn't match // the correct corresponding directory with that packageId. if (context.flags.package !== expectedPackageId) { throw new Error( messages.getMessage( 'errorDirectoryIdMismatch', [ `--${pathFlag.name} (-${pathFlag.char})`, context.flags.path, `--${packageFlag.name} (-${packageFlag.char})`, context.flags.package, ], 'package_version_create' ) ); } } const resolvedPackageId = pkgUtils.getPackageIdFromAlias(context.flags.package, this.force); // At this point, the packageIdFromAlias should have been resolved to an Id. Now, we // need to validate that the Id is correct. pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, resolvedPackageId); await this._validateFlagsForPackageType(resolvedPackageId, context.flags); // validate the versionNumber flag value if specified, otherwise the descriptor value const versionNumber = context.flags.versionnumber ? context.flags.versionnumber : this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'versionNumber', canonicalPackageProperty, context.flags.package, packageFlag ); pkgUtils.validateVersionNumber(versionNumber, pkgUtils.NEXT_BUILD_NUMBER_TOKEN, null); await pkgUtils.validatePatchVersion(this.force, this.org, versionNumber, resolvedPackageId); try { fs.statSync(path.join(process.cwd(), context.flags.path)); } catch (err) { throw new Error(`Directory '${context.flags.path}' does not exist`); } // Check for an includeProfileUserLiceneses flag in the packageDirectory const includeProfileUserLicenses = this._getConfigPackageDirectoriesValue( context, this.packageDirs, 'includeProfileUserLicenses', canonicalPackageProperty, context.flags.package, packageFlag ); if ( includeProfileUserLicenses !== undefined && includeProfileUserLicenses !== true && includeProfileUserLicenses !== false ) { throw new Error( messages.getMessage( 'errorProfileUserLicensesInvalidValue', [includeProfileUserLicenses], 'package_version_create' ) ); } const shouldGenerateProfileInformation = logger.shouldLog(LoggerLevel.INFO) || logger.shouldLog(LoggerLevel.DEBUG); this.profileApi = new ProfileApi(this.org, includeProfileUserLicenses, shouldGenerateProfileInformation); // If we are polling check to see if the package is Org-Dependent, if so, update the poll time if (context.flags.wait) { const query = `SELECT IsOrgDependent FROM Package2 WHERE Id = '${resolvedPackageId}'`; this.force.toolingQuery(this.org, query).then((pkgQueryResult) => { const subRecords = pkgQueryResult.records; if (subRecords && subRecords.length === 1 && subRecords[0].IsOrgDependent) { this.pollInterval = POLL_INTERVAL_WITHOUT_VALIDATION_SECONDS; this.maxRetries = (60 / this.pollInterval) * context.flags.wait; } }); } return Promise.resolve().then(() => this._createPackageVersionCreateRequestFromOptions(context, resolvedPackageId) .then((request) => this.force.toolingCreate(this.org, 'Package2VersionCreateRequest', request)) .then((createResult) => { if (createResult.success) { return createResult.id; } else { const errStr = createResult.errors && createResult.errors.length ? createResult.errors.join(', ') : createResult.errors; throw new Error(`Failed to create request${createResult.id ? ` [${createResult.id}]` : ''}: ${errStr}`); } }) .then((id) => { if (context.flags.wait) { if (this.pollInterval) { return pkgUtils.pollForStatusWithInterval( context, id, this.maxRetries, resolvedPackageId, logger, true, this.force, this.org, this.pollInterval ); } else { return pkgUtils.pollForStatus( context, id, this.maxRetries, resolvedPackageId, logger, true, this.force, this.org ); } } else { return this.packageVersionCreateRequestApi.byId(id); } }) .then((result) => (util.isArray(result) ? result[0] : result)) ); }); } public rejectWithInstallKeyError(context: any) { // This command also requires either the installationkey flag or installationkeybypass flag const installationKeyFlag = context.command.flags.find((x) => x.name === 'installationkey'); const installationKeyBypassFlag = context.command.flags.find((x) => x.name === 'installationkeybypass'); const errorString = messages.getMessage( 'errorMissingFlagsInstallationKey', [ `--${installationKeyFlag.name} (-${installationKeyFlag.char})`, `--${installationKeyBypassFlag.name} (-${installationKeyBypassFlag.char})`, ], 'package_version_create' ); const error = new Error(errorString); error['name'] = 'requiredFlagMissing'; return BBPromise.reject(error); } async _validateFlagsForPackageType(packageId: string, flags: any) { const packageType = await pkgUtils.getPackage2Type(packageId, this.force, this.org); if (packageType == 'Unlocked') { if (flags.postinstallscript || flags.uninstallscript) { throw SfdxError.create( 'salesforce-alm', 'packaging', 'version_create.errorScriptsNotApplicableToUnlockedPackage' ); } // Don't allow ancestor in unlocked packages const packageDescriptorJson = this._getPackageDescriptorJsonFromPackageId(packageId, flags); const ancestorId = packageDescriptorJson.ancestorId; const ancestorVersion = packageDescriptorJson.ancestorVersion; if (ancestorId || ancestorVersion) { throw SfdxError.create( 'salesforce-alm', 'packaging', 'version_create.errorAncestorNotApplicableToUnlockedPackage' ); } } } /** * * @param result - the data representing the Package Version, must include a 'Status' property * @returns {string} a human readable message for CLI output */ getHumanSuccessMessage(result) { switch (result.Status) { case 'Error': return result.Error.length > 0 ? result.Error.join('\n') : messages.getMessage('unknownError', [], 'package_version_create'); case 'Success': return messages.getMessage( result.Status, [result.Id, result.SubscriberPackageVersionId, pkgUtils.INSTALL_URL_BASE, result.SubscriberPackageVersionId], 'package_version_create' ); default: return messages.getMessage( 'InProgress', [pkgUtils.convertCamelCaseStringToSentence(result.Status), result.Id], 'package_version_create' ); } } /** * Cleans invalid attribute(s) from the packageDescriptorJSON */ _cleanPackageDescriptorJson(packageDescriptorJson) { if (typeof packageDescriptorJson.default !== 'undefined') { delete packageDescriptorJson.default; // for client-side use only, not needed } if (typeof packageDescriptorJson.includeProfileUserLicenses !== 'undefined') { delete packageDescriptorJson.includeProfileUserLicenses; // for client-side use only, not needed } if (typeof packageDescriptorJson.unpackagedMetadata !== 'undefined') { delete packageDescriptorJson.unpackagedMetadata; // for client-side use only, not needed } if (typeof packageDescriptorJson.branch !== 'undefined') { delete packageDescriptorJson.branch; // for client-side use only, not needed } } /** * Sets default or override values for packageDescriptorJSON attribs */ _setPackageDescriptorJsonValues(packageDescriptorJson, context) { if (context.flags.versionname) { packageDescriptorJson.versionName = context.flags.versionname; } if (context.flags.versiondescription) { packageDescriptorJson.versionDescription = context.flags.versiondescription; } if (context.flags.versionnumber) { packageDescriptorJson.versionNumber = context.flags.versionnumber; } // default versionName to versionNumber if unset, stripping .NEXT if present if (!packageDescriptorJson.versionName) { const versionNumber = packageDescriptorJson.versionNumber; packageDescriptorJson.versionName = versionNumber.split(pkgUtils.VERSION_NUMBER_SEP)[3] === pkgUtils.NEXT_BUILD_NUMBER_TOKEN ? versionNumber.substring( 0, versionNumber.indexOf(pkgUtils.VERSION_NUMBER_SEP + pkgUtils.NEXT_BUILD_NUMBER_TOKEN) ) : versionNumber; logger.warnUser( context, messages.getMessage('defaultVersionName', packageDescriptorJson.versionName, 'package_version_create') ); } if (context.flags.releasenotesurl) { packageDescriptorJson.releaseNotesUrl = context.flags.releasenotesurl; } if (packageDescriptorJson.releaseNotesUrl && !pkgUtils.validUrl(packageDescriptorJson.releaseNotesUrl)) { throw new Error( messages.getMessage( 'malformedUrl', ['releaseNotesUrl', packageDescriptorJson.releaseNotesUrl], 'package_version_create' ) ); } if (context.flags.postinstallurl) { packageDescriptorJson.postInstallUrl = context.flags.postinstallurl; } if (packageDescriptorJson.postInstallUrl && !pkgUtils.validUrl(packageDescriptorJson.postInstallUrl)) { throw new Error( messages.getMessage( 'malformedUrl', ['postInstallUrl', packageDescriptorJson.postInstallUrl], 'package_version_create' ) ); } if (context.flags.postinstallscript) { packageDescriptorJson.postInstallScript = context.flags.postinstallscript; } if (context.flags.uninstallscript) { packageDescriptorJson.uninstallScript = context.flags.uninstallscript; } } } export = PackageVersionCreateCommand;
the_stack
import { click as untrackedClick, fillIn } from '@ember/test-helpers'; import { setupMirage } from 'ember-cli-mirage/test-support'; import { percySnapshot } from 'ember-percy'; import { module, test } from 'qunit'; import Collection from 'ember-osf-web/models/collection'; import CollectionProvider from 'ember-osf-web/models/collection-provider'; import { Permission } from 'ember-osf-web/models/osf-model'; import { visit } from 'ember-osf-web/tests/helpers'; import { setupEngineApplicationTest } from 'ember-osf-web/tests/helpers/engines'; module('Collections | Acceptance | update', hooks => { setupEngineApplicationTest(hooks, 'collections'); setupMirage(hooks); test('it works', async function(assert) { server.loadFixtures('licenses'); const licensesAcceptable = server.schema.licenses.all().models; const currentUser = server.create('user', 'loggedIn'); const primaryCollection = server.create('collection'); const nodeAdded = server.create('node', { title: 'Added to collection', license: licensesAcceptable[0], currentUserPermissions: Object.values(Permission), }); server.create('contributor', { node: nodeAdded, users: currentUser, index: 0, }); const store = this.owner.lookup('service:store'); const collection: Collection = await store.findRecord('collection', primaryCollection.id); collection.collectedTypeChoices.sort(); collection.issueChoices.sort(); collection.programAreaChoices.sort(); collection.statusChoices.sort(); collection.volumeChoices.sort(); server.create('collected-metadatum', { creator: currentUser, guid: nodeAdded, id: nodeAdded.id, collection: primaryCollection, collectedType: collection.collectedTypeChoices[0], issue: collection.issueChoices[0], programArea: collection.programAreaChoices[0], status: collection.statusChoices[0], volume: collection.volumeChoices[0], }); const provider = server.create('collection-provider', { id: 'studyswap', primaryCollection, licensesAcceptable, }); const newTitle = 'New Title'; const newDescription = 'New description.'; await visit(`/collections/${provider.id}/${nodeAdded.id}/edit`); /* Project metadata */ await fillIn('[data-test-project-metadata-title] input', newTitle); await fillIn('[data-test-project-metadata-description] textarea', newDescription); // open license picker await untrackedClick('[data-test-project-metadata-license-picker] .ember-power-select-trigger'); // select first license const firstLicenseOption = document.querySelector('.ember-power-select-option'); if (firstLicenseOption) { await untrackedClick(firstLicenseOption); } // remove third tag await untrackedClick(`[data-test-project-metadata-tag="${nodeAdded.tags[2]}"] + .emberTagInput-remove`); await percySnapshot('Collections | Acceptance | update | project metadata'); await untrackedClick('[data-test-project-metadata-save-button]'); assert.dom('[data-test-project-metadata-complete-title-value]') .hasText(newTitle, 'title is updated'); assert.dom('[data-test-project-metadata-complete-description-value]') .hasText(newDescription, 'description is updated'); const collectionProvider: CollectionProvider = store.peekRecord('collection-provider', provider.id); const licenses = await collectionProvider.get('licensesAcceptable'); const firstLicense = licenses.get('firstObject'); assert.dom('[data-test-project-metadata-complete-license-name-value]') .hasText(firstLicense ? firstLicense.name : '', 'license is updated'); assert.dom('[data-test-project-metadata-complete-tag]') .exists({ count: 4 }, 'only four tags remain'); nodeAdded.tags.forEach(tag => assert.dom(`[data-test-project-metadata-complete-tag="${tag}"]`) .exists({ count: 1 }, `found tag: "${tag}"`)); /* Project contributors */ // add contributor const userToAdd = server.create('user'); await fillIn('[data-test-project-contributors-search-box] input', userToAdd.fullName); await untrackedClick('[data-test-project-contributors-search-button]'); const userToAddSelector = `[data-test-project-contributors-search-user="${userToAdd.id}"]`; assert.dom(userToAddSelector) .exists({ count: 1 }, 'found contributor'); await untrackedClick(`${userToAddSelector} [data-test-project-contributors-add-contributor-button]`); const contribListSelector = `[data-test-project-contributors-list-item-id=${userToAdd.id}]`; assert.dom(contribListSelector) .exists({ count: 1 }, 'contributor added to list'); await percySnapshot('Collections | Acceptance | update | added project contributor'); await untrackedClick('[data-test-collection-project-contributors] [data-test-submit-section-continue]'); assert.dom(`[data-test-contributor-name="${userToAdd.id}"]`) .exists({ count: 1 }, 'contributor added to summary'); // remove contributor await untrackedClick( '[data-test-collections-submit-section="projectContributors"] [data-test-submit-section-click-to-edit]', ); await untrackedClick(`${contribListSelector} [data-test-project-contributors-list-item-remove-button]`); assert.dom(contribListSelector) .doesNotExist('contributor removed from list'); await percySnapshot('Collections | Acceptance | update | removed project contributor'); await untrackedClick('[data-test-collection-project-contributors] [data-test-submit-section-continue]'); assert.dom(`[data-test-contributor-name="${userToAdd.id}"]`) .doesNotExist('contributor removed from summary'); /* Collection metadata */ await untrackedClick('[data-test-collection-metadata] [data-test-submit-section-continue]'); const metadataValueSelector = '[data-test-collection-metadata-complete-field-value]'; // confirm original values are first option assert.dom(`[data-test-collection-metadata-complete-field="collectedType"] ${metadataValueSelector}`) .hasText(collection.collectedTypeChoices[0], 'collected type in summary is first option'); assert.dom(`[data-test-collection-metadata-complete-field="issue"] ${metadataValueSelector}`) .hasText(collection.issueChoices[0], 'issue in summary is first option'); assert.dom(`[data-test-collection-metadata-complete-field="programArea"] ${metadataValueSelector}`) .hasText(collection.programAreaChoices[0], 'program area in summary is first option'); assert.dom(`[data-test-collection-metadata-complete-field="status"] ${metadataValueSelector}`) .hasText(collection.statusChoices[0], 'status in summary is first option'); assert.dom(`[data-test-collection-metadata-complete-field="volume"] ${metadataValueSelector}`) .hasText(collection.volumeChoices[0], 'volume in summary is first option'); await untrackedClick( '[data-test-collections-submit-section="collectionMetadata"] [data-test-submit-section-click-to-edit]', ); // set collected type to second option await untrackedClick('[data-test-metadata-field="collected_type_label"] .ember-power-select-trigger'); const firstCollectedTypeOption = document.querySelector('[data-option-index="1"].ember-power-select-option'); if (firstCollectedTypeOption) { await untrackedClick(firstCollectedTypeOption); } else { throw new Error('could not find collected type option'); } // set issue to second option await untrackedClick('[data-test-metadata-field="issue_label"] .ember-power-select-trigger'); const firstIssueOption = document.querySelector('[data-option-index="1"].ember-power-select-option'); if (firstIssueOption) { await untrackedClick(firstIssueOption); } else { throw new Error('could not find issue option'); } // set program area to second option await untrackedClick('[data-test-metadata-field="program_area_label"] .ember-power-select-trigger'); const firstProgramAreaOption = document.querySelector('[data-option-index="1"].ember-power-select-option'); if (firstProgramAreaOption) { await untrackedClick(firstProgramAreaOption); } else { throw new Error('could not find program area option'); } // set status to second option await untrackedClick('[data-test-metadata-field="status_label"] .ember-power-select-trigger'); const firstStatusOption = document.querySelector('[data-option-index="1"].ember-power-select-option'); if (firstStatusOption) { await untrackedClick(firstStatusOption); } else { throw new Error('could not find status option'); } // set volume to second option await untrackedClick('[data-test-metadata-field="volume_label"] .ember-power-select-trigger'); const firstVolumeOption = document.querySelector('[data-option-index="1"].ember-power-select-option'); if (firstVolumeOption) { await untrackedClick(firstVolumeOption); } else { throw new Error('could not find volume option'); } await percySnapshot('Collections | Acceptance | update | collection metadata'); await untrackedClick('[data-test-collection-metadata] [data-test-submit-section-continue]'); // Confirm modified values are second option assert.dom(`[data-test-collection-metadata-complete-field="collectedType"] ${metadataValueSelector}`) .hasText(collection.collectedTypeChoices[1], 'collected type in summary is second option'); assert.dom(`[data-test-collection-metadata-complete-field="issue"] ${metadataValueSelector}`) .hasText(collection.issueChoices[1], 'issue in summary is second option'); assert.dom(`[data-test-collection-metadata-complete-field="programArea"] ${metadataValueSelector}`) .hasText(collection.programAreaChoices[1], 'program area in summary is second option'); assert.dom(`[data-test-collection-metadata-complete-field="status"] ${metadataValueSelector}`) .hasText(collection.statusChoices[1], 'status in summary is second option'); assert.dom(`[data-test-collection-metadata-complete-field="volume"] ${metadataValueSelector}`) .hasText(collection.volumeChoices[1], 'volume in summary is second option'); /* Finished */ await percySnapshot('Collections | Acceptance | update | finished'); }); });
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { ArrayExt } from '@lumino/algorithm'; import { ElementExt } from '@lumino/domutils'; import { getKeyboardLayout } from '@lumino/keyboard'; import { Message, MessageLoop } from '@lumino/messaging'; import { ElementARIAAttrs, ElementDataset, VirtualDOM, VirtualElement, h } from '@lumino/virtualdom'; import { Menu } from './menu'; import { Title } from './title'; import { Widget } from './widget'; /** * A widget which displays menus as a canonical menu bar. */ export class MenuBar extends Widget { /** * Construct a new menu bar. * * @param options - The options for initializing the menu bar. */ constructor(options: MenuBar.IOptions = {}) { super({ node: Private.createNode() }); this.addClass('lm-MenuBar'); /* <DEPRECATED> */ this.addClass('p-MenuBar'); /* </DEPRECATED> */ this.setFlag(Widget.Flag.DisallowLayout); this.renderer = options.renderer || MenuBar.defaultRenderer; this._forceItemsPosition = options.forceItemsPosition || { forceX: true, forceY: true }; } /** * Dispose of the resources held by the widget. */ dispose(): void { this._closeChildMenu(); this._menus.length = 0; super.dispose(); } /** * The renderer used by the menu bar. */ readonly renderer: MenuBar.IRenderer; /** * The child menu of the menu bar. * * #### Notes * This will be `null` if the menu bar does not have an open menu. */ get childMenu(): Menu | null { return this._childMenu; } /** * Get the menu bar content node. * * #### Notes * This is the node which holds the menu title nodes. * * Modifying this node directly can lead to undefined behavior. */ get contentNode(): HTMLUListElement { return this.node.getElementsByClassName('lm-MenuBar-content')[0] as HTMLUListElement; } /** * Get the currently active menu. */ get activeMenu(): Menu | null { return this._menus[this._activeIndex] || null; } /** * Set the currently active menu. * * #### Notes * If the menu does not exist, the menu will be set to `null`. */ set activeMenu(value: Menu | null) { this.activeIndex = value ? this._menus.indexOf(value) : -1; } /** * Get the index of the currently active menu. * * #### Notes * This will be `-1` if no menu is active. */ get activeIndex(): number { return this._activeIndex; } /** * Set the index of the currently active menu. * * #### Notes * If the menu cannot be activated, the index will be set to `-1`. */ set activeIndex(value: number) { // Adjust the value for an out of range index. if (value < 0 || value >= this._menus.length) { value = -1; } // Bail early if the index will not change. if (this._activeIndex === value) { return; } // Update the active index. this._activeIndex = value; // Update focus to new active index if (this._activeIndex >= 0 && this.contentNode.childNodes[this._activeIndex]) { (this.contentNode.childNodes[this._activeIndex] as HTMLElement).focus(); } // Schedule an update of the items. this.update(); } /** * A read-only array of the menus in the menu bar. */ get menus(): ReadonlyArray<Menu> { return this._menus; } /** * Open the active menu and activate its first menu item. * * #### Notes * If there is no active menu, this is a no-op. */ openActiveMenu(): void { // Bail early if there is no active item. if (this._activeIndex === -1) { return; } // Open the child menu. this._openChildMenu(); // Activate the first item in the child menu. if (this._childMenu) { this._childMenu.activeIndex = -1; this._childMenu.activateNextItem(); } } /** * Add a menu to the end of the menu bar. * * @param menu - The menu to add to the menu bar. * * #### Notes * If the menu is already added to the menu bar, it will be moved. */ addMenu(menu: Menu): void { this.insertMenu(this._menus.length, menu); } /** * Insert a menu into the menu bar at the specified index. * * @param index - The index at which to insert the menu. * * @param menu - The menu to insert into the menu bar. * * #### Notes * The index will be clamped to the bounds of the menus. * * If the menu is already added to the menu bar, it will be moved. */ insertMenu(index: number, menu: Menu): void { // Close the child menu before making changes. this._closeChildMenu(); // Look up the index of the menu. let i = this._menus.indexOf(menu); // Clamp the insert index to the array bounds. let j = Math.max(0, Math.min(index, this._menus.length)); // If the menu is not in the array, insert it. if (i === -1) { // Insert the menu into the array. ArrayExt.insert(this._menus, j, menu); // Add the styling class to the menu. menu.addClass('lm-MenuBar-menu'); /* <DEPRECATED> */ menu.addClass('p-MenuBar-menu'); /* </DEPRECATED> */ // Connect to the menu signals. menu.aboutToClose.connect(this._onMenuAboutToClose, this); menu.menuRequested.connect(this._onMenuMenuRequested, this); menu.title.changed.connect(this._onTitleChanged, this); // Schedule an update of the items. this.update(); // There is nothing more to do. return; } // Otherwise, the menu exists in the array and should be moved. // Adjust the index if the location is at the end of the array. if (j === this._menus.length) { j--; } // Bail if there is no effective move. if (i === j) { return; } // Move the menu to the new locations. ArrayExt.move(this._menus, i, j); // Schedule an update of the items. this.update(); } /** * Remove a menu from the menu bar. * * @param menu - The menu to remove from the menu bar. * * #### Notes * This is a no-op if the menu is not in the menu bar. */ removeMenu(menu: Menu): void { this.removeMenuAt(this._menus.indexOf(menu)); } /** * Remove the menu at a given index from the menu bar. * * @param index - The index of the menu to remove. * * #### Notes * This is a no-op if the index is out of range. */ removeMenuAt(index: number): void { // Close the child menu before making changes. this._closeChildMenu(); // Remove the menu from the array. let menu = ArrayExt.removeAt(this._menus, index); // Bail if the index is out of range. if (!menu) { return; } // Disconnect from the menu signals. menu.aboutToClose.disconnect(this._onMenuAboutToClose, this); menu.menuRequested.disconnect(this._onMenuMenuRequested, this); menu.title.changed.disconnect(this._onTitleChanged, this); // Remove the styling class from the menu. menu.removeClass('lm-MenuBar-menu'); /* <DEPRECATED> */ menu.removeClass('p-MenuBar-menu'); /* </DEPRECATED> */ // Schedule an update of the items. this.update(); } /** * Remove all menus from the menu bar. */ clearMenus(): void { // Bail if there is nothing to remove. if (this._menus.length === 0) { return; } // Close the child menu before making changes. this._closeChildMenu(); // Disconnect from the menu signals and remove the styling class. for (let menu of this._menus) { menu.aboutToClose.disconnect(this._onMenuAboutToClose, this); menu.menuRequested.disconnect(this._onMenuMenuRequested, this); menu.title.changed.disconnect(this._onTitleChanged, this); menu.removeClass('lm-MenuBar-menu'); /* <DEPRECATED> */ menu.removeClass('p-MenuBar-menu'); /* </DEPRECATED> */ } // Clear the menus array. this._menus.length = 0; // Schedule an update of the items. this.update(); } /** * Handle the DOM events for the menu bar. * * @param event - The DOM event sent to the menu bar. * * #### Notes * This method implements the DOM `EventListener` interface and is * called in response to events on the menu bar's DOM nodes. It * should not be called directly by user code. */ handleEvent(event: Event): void { switch (event.type) { case 'keydown': this._evtKeyDown(event as KeyboardEvent); break; case 'mousedown': this._evtMouseDown(event as MouseEvent); break; case 'mousemove': this._evtMouseMove(event as MouseEvent); break; case 'mouseleave': this._evtMouseLeave(event as MouseEvent); break; case 'contextmenu': event.preventDefault(); event.stopPropagation(); break; } } /** * A message handler invoked on a `'before-attach'` message. */ protected onBeforeAttach(msg: Message): void { this.node.addEventListener('keydown', this); this.node.addEventListener('mousedown', this); this.node.addEventListener('mousemove', this); this.node.addEventListener('mouseleave', this); this.node.addEventListener('contextmenu', this); } /** * A message handler invoked on an `'after-detach'` message. */ protected onAfterDetach(msg: Message): void { this.node.removeEventListener('keydown', this); this.node.removeEventListener('mousedown', this); this.node.removeEventListener('mousemove', this); this.node.removeEventListener('mouseleave', this); this.node.removeEventListener('contextmenu', this); this._closeChildMenu(); } /** * A message handler invoked on an `'activate-request'` message. */ protected onActivateRequest(msg: Message): void { if (this.isAttached) { this.node.focus(); } } /** * A message handler invoked on an `'update-request'` message. */ protected onUpdateRequest(msg: Message): void { let menus = this._menus; let renderer = this.renderer; let activeIndex = this._activeIndex; let content = new Array<VirtualElement>(menus.length); for (let i = 0, n = menus.length; i < n; ++i) { let title = menus[i].title; let active = i === activeIndex; content[i] = renderer.renderItem({ title, active, onfocus: () => { this.activeIndex = i; } }); } VirtualDOM.render(content, this.contentNode); } /** * Handle the `'keydown'` event for the menu bar. */ private _evtKeyDown(event: KeyboardEvent): void { // A menu bar handles all keydown events. event.preventDefault(); event.stopPropagation(); // Fetch the key code for the event. let kc = event.keyCode; // Enter, Up Arrow, Down Arrow if (kc === 13 || kc === 38 || kc === 40) { this.openActiveMenu(); return; } // Escape if (kc === 27) { this._closeChildMenu(); this.activeIndex = -1; this.node.blur(); return; } // Left Arrow if (kc === 37) { let i = this._activeIndex; let n = this._menus.length; this.activeIndex = i === 0 ? n - 1 : i - 1; return; } // Right Arrow if (kc === 39) { let i = this._activeIndex; let n = this._menus.length; this.activeIndex = i === n - 1 ? 0 : i + 1; return; } // Get the pressed key character. let key = getKeyboardLayout().keyForKeydownEvent(event); // Bail if the key is not valid. if (!key) { return; } // Search for the next best matching mnemonic item. let start = this._activeIndex + 1; let result = Private.findMnemonic(this._menus, key, start); // Handle the requested mnemonic based on the search results. // If exactly one mnemonic is matched, that menu is opened. // Otherwise, the next mnemonic is activated if available, // followed by the auto mnemonic if available. if (result.index !== -1 && !result.multiple) { this.activeIndex = result.index; this.openActiveMenu(); } else if (result.index !== -1) { this.activeIndex = result.index; } else if (result.auto !== -1) { this.activeIndex = result.auto; } } /** * Handle the `'mousedown'` event for the menu bar. */ private _evtMouseDown(event: MouseEvent): void { // Bail if the mouse press was not on the menu bar. This can occur // when the document listener is installed for an active menu bar. if (!ElementExt.hitTest(this.node, event.clientX, event.clientY)) { return; } // Stop the propagation of the event. Immediate propagation is // also stopped so that an open menu does not handle the event. event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); // Check if the mouse is over one of the menu items. let index = ArrayExt.findFirstIndex(this.contentNode.children, node => { return ElementExt.hitTest(node, event.clientX, event.clientY); }); // If the press was not on an item, close the child menu. if (index === -1) { this._closeChildMenu(); return; } // If the press was not the left mouse button, do nothing further. if (event.button !== 0) { return; } // Otherwise, toggle the open state of the child menu. if (this._childMenu) { this._closeChildMenu(); this.activeIndex = index; } else { this.activeIndex = index; this._openChildMenu(); } } /** * Handle the `'mousemove'` event for the menu bar. */ private _evtMouseMove(event: MouseEvent): void { // Check if the mouse is over one of the menu items. let index = ArrayExt.findFirstIndex(this.contentNode.children, node => { return ElementExt.hitTest(node, event.clientX, event.clientY); }); // Bail early if the active index will not change. if (index === this._activeIndex) { return; } // Bail early if a child menu is open and the mouse is not over // an item. This allows the child menu to be kept open when the // mouse is over the empty part of the menu bar. if (index === -1 && this._childMenu) { return; } // Update the active index to the hovered item. this.activeIndex = index; // Open the new menu if a menu is already open. if (this._childMenu) { this._openChildMenu(); } } /** * Handle the `'mouseleave'` event for the menu bar. */ private _evtMouseLeave(event: MouseEvent): void { // Reset the active index if there is no open menu. if (!this._childMenu) { this.activeIndex = -1; } } /** * Open the child menu at the active index immediately. * * If a different child menu is already open, it will be closed, * even if there is no active menu. */ private _openChildMenu(): void { // If there is no active menu, close the current menu. let newMenu = this.activeMenu; if (!newMenu) { this._closeChildMenu(); return; } // Bail if there is no effective menu change. let oldMenu = this._childMenu; if (oldMenu === newMenu) { return; } // Swap the internal menu reference. this._childMenu = newMenu; // Close the current menu, or setup for the new menu. if (oldMenu) { oldMenu.close(); } else { this.addClass('lm-mod-active'); /* <DEPRECATED> */ this.addClass('p-mod-active'); /* </DEPRECATED> */ document.addEventListener('mousedown', this, true); } // Ensure the menu bar is updated and look up the item node. MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest); let itemNode = this.contentNode.children[this._activeIndex]; // Get the positioning data for the new menu. let { left, bottom } = (itemNode as HTMLElement).getBoundingClientRect(); // Open the new menu at the computed location. newMenu.open(left, bottom, this._forceItemsPosition); } /** * Close the child menu immediately. * * This is a no-op if a child menu is not open. */ private _closeChildMenu(): void { // Bail if no child menu is open. if (!this._childMenu) { return; } // Remove the active class from the menu bar. this.removeClass('lm-mod-active'); /* <DEPRECATED> */ this.removeClass('p-mod-active'); /* </DEPRECATED> */ // Remove the document listeners. document.removeEventListener('mousedown', this, true); // Clear the internal menu reference. let menu = this._childMenu; this._childMenu = null; // Close the menu. menu.close(); // Reset the active index. this.activeIndex = -1; } /** * Handle the `aboutToClose` signal of a menu. */ private _onMenuAboutToClose(sender: Menu): void { // Bail if the sender is not the child menu. if (sender !== this._childMenu) { return; } // Remove the active class from the menu bar. this.removeClass('lm-mod-active'); /* <DEPRECATED> */ this.removeClass('p-mod-active'); /* </DEPRECATED> */ // Remove the document listeners. document.removeEventListener('mousedown', this, true); // Clear the internal menu reference. this._childMenu = null; // Reset the active index. this.activeIndex = -1; } /** * Handle the `menuRequested` signal of a child menu. */ private _onMenuMenuRequested(sender: Menu, args: 'next' | 'previous'): void { // Bail if the sender is not the child menu. if (sender !== this._childMenu) { return; } // Look up the active index and menu count. let i = this._activeIndex; let n = this._menus.length; // Active the next requested index. switch (args) { case 'next': this.activeIndex = i === n - 1 ? 0 : i + 1; break; case 'previous': this.activeIndex = i === 0 ? n - 1 : i - 1; break; } // Open the active menu. this.openActiveMenu(); } /** * Handle the `changed` signal of a title object. */ private _onTitleChanged(): void { this.update(); } private _activeIndex = -1; private _forceItemsPosition: Menu.IOpenOptions; private _menus: Menu[] = []; private _childMenu: Menu | null = null; } /** * The namespace for the `MenuBar` class statics. */ export namespace MenuBar { /** * An options object for creating a menu bar. */ export interface IOptions { /** * A custom renderer for creating menu bar content. * * The default is a shared renderer instance. */ renderer?: IRenderer; /** * Whether to force the position of the menu. The MenuBar forces the * coordinates of its menus by default. With this option you can disable it. * * Setting to `false` will enable the logic which repositions the * coordinates of the menu if it will not fit entirely on screen. * * The default is `true`. */ forceItemsPosition?: Menu.IOpenOptions; } /** * An object which holds the data to render a menu bar item. */ export interface IRenderData { /** * The title to be rendered. */ readonly title: Title<Widget>; /** * Whether the item is the active item. */ readonly active: boolean; readonly onfocus?: (event: FocusEvent) => void; } /** * A renderer for use with a menu bar. */ export interface IRenderer { /** * Render the virtual element for a menu bar item. * * @param data - The data to use for rendering the item. * * @returns A virtual element representing the item. */ renderItem(data: IRenderData): VirtualElement; } /** * The default implementation of `IRenderer`. * * #### Notes * Subclasses are free to reimplement rendering methods as needed. */ export class Renderer implements IRenderer { /** * Construct a new renderer. */ constructor() { } /** * Render the virtual element for a menu bar item. * * @param data - The data to use for rendering the item. * * @returns A virtual element representing the item. */ renderItem(data: IRenderData): VirtualElement { let className = this.createItemClass(data); let dataset = this.createItemDataset(data); let aria = this.createItemARIA(data); return ( h.li({ className, dataset, tabindex: '0', onfocus: data.onfocus, ...aria }, this.renderIcon(data), this.renderLabel(data) ) ); } /** * Render the icon element for a menu bar item. * * @param data - The data to use for rendering the icon. * * @returns A virtual element representing the item icon. */ renderIcon(data: IRenderData): VirtualElement { let className = this.createIconClass(data); /* <DEPRECATED> */ if (typeof data.title.icon === 'string') { return h.div({className}, data.title.iconLabel); } /* </DEPRECATED> */ // if data.title.icon is undefined, it will be ignored return h.div({className}, data.title.icon!, data.title.iconLabel); } /** * Render the label element for a menu item. * * @param data - The data to use for rendering the label. * * @returns A virtual element representing the item label. */ renderLabel(data: IRenderData): VirtualElement { let content = this.formatLabel(data); return h.div({ className: 'lm-MenuBar-itemLabel' /* <DEPRECATED> */ + ' p-MenuBar-itemLabel' /* </DEPRECATED> */ }, content); } /** * Create the class name for the menu bar item. * * @param data - The data to use for the class name. * * @returns The full class name for the menu item. */ createItemClass(data: IRenderData): string { let name = 'lm-MenuBar-item'; /* <DEPRECATED> */ name += ' p-MenuBar-item'; /* </DEPRECATED> */ if (data.title.className) { name += ` ${data.title.className}`; } if (data.active) { name += ' lm-mod-active'; /* <DEPRECATED> */ name += ' p-mod-active'; /* </DEPRECATED> */ } return name; } /** * Create the dataset for a menu bar item. * * @param data - The data to use for the item. * * @returns The dataset for the menu bar item. */ createItemDataset(data: IRenderData): ElementDataset { return data.title.dataset; } /** * Create the aria attributes for menu bar item. * * @param data - The data to use for the aria attributes. * * @returns The aria attributes object for the item. */ createItemARIA(data: IRenderData): ElementARIAAttrs { return {role: 'menuitem', 'aria-haspopup': 'true'}; } /** * Create the class name for the menu bar item icon. * * @param data - The data to use for the class name. * * @returns The full class name for the item icon. */ createIconClass(data: IRenderData): string { let name = 'lm-MenuBar-itemIcon'; /* <DEPRECATED> */ name += ' p-MenuBar-itemIcon'; /* </DEPRECATED> */ let extra = data.title.iconClass; return extra ? `${name} ${extra}` : name; } /** * Create the render content for the label node. * * @param data - The data to use for the label content. * * @returns The content to add to the label node. */ formatLabel(data: IRenderData): h.Child { // Fetch the label text and mnemonic index. let { label, mnemonic } = data.title; // If the index is out of range, do not modify the label. if (mnemonic < 0 || mnemonic >= label.length) { return label; } // Split the label into parts. let prefix = label.slice(0, mnemonic); let suffix = label.slice(mnemonic + 1); let char = label[mnemonic]; // Wrap the mnemonic character in a span. let span = h.span({ className: 'lm-MenuBar-itemMnemonic' /* <DEPRECATED> */ + ' p-MenuBar-itemMnemonic' /* </DEPRECATED> */ }, char); // Return the content parts. return [prefix, span, suffix]; } } /** * The default `Renderer` instance. */ export const defaultRenderer = new Renderer(); } /** * The namespace for the module implementation details. */ namespace Private { /** * Create the DOM node for a menu bar. */ export function createNode(): HTMLDivElement { let node = document.createElement('div'); let content = document.createElement('ul'); content.className = 'lm-MenuBar-content'; /* <DEPRECATED> */ content.classList.add('p-MenuBar-content'); /* </DEPRECATED> */ node.appendChild(content); content.setAttribute('role', 'menubar'); node.tabIndex = 0; content.tabIndex = 0; return node; } /** * The results of a mnemonic search. */ export interface IMnemonicResult { /** * The index of the first matching mnemonic item, or `-1`. */ index: number; /** * Whether multiple mnemonic items matched. */ multiple: boolean; /** * The index of the first auto matched non-mnemonic item. */ auto: number; } /** * Find the best matching mnemonic item. * * The search starts at the given index and wraps around. */ export function findMnemonic(menus: ReadonlyArray<Menu>, key: string, start: number): IMnemonicResult { // Setup the result variables. let index = -1; let auto = -1; let multiple = false; // Normalize the key to upper case. let upperKey = key.toUpperCase(); // Search the items from the given start index. for (let i = 0, n = menus.length; i < n; ++i) { // Compute the wrapped index. let k = (i + start) % n; // Look up the menu title. let title = menus[k].title; // Ignore titles with an empty label. if (title.label.length === 0) { continue; } // Look up the mnemonic index for the label. let mn = title.mnemonic; // Handle a valid mnemonic index. if (mn >= 0 && mn < title.label.length) { if (title.label[mn].toUpperCase() === upperKey) { if (index === -1) { index = k; } else { multiple = true; } } continue; } // Finally, handle the auto index if possible. if (auto === -1 && title.label[0].toUpperCase() === upperKey) { auto = k; } } // Return the search results. return { index, multiple, auto }; } }
the_stack
import path from 'path' import { Plugin } from '../plugin' import { ViteDevServer } from '../server' import { OutputAsset, OutputBundle, OutputChunk } from 'rollup' import { cleanUrl, generateCodeFrame, isDataUrl, isExternalUrl, normalizePath, processSrcSet, slash } from '../utils' import { ResolvedConfig } from '../config' import MagicString from 'magic-string' import { checkPublicFile, assetUrlRE, urlToBuiltUrl, getAssetFilename } from './asset' import { isCSSRequest, chunkToEmittedCssFileMap } from './css' import { modulePreloadPolyfillId } from './modulePreloadPolyfill' import { AttributeNode, NodeTransform, NodeTypes, ElementNode } from '@vue/compiler-dom' const htmlProxyRE = /\?html-proxy&index=(\d+)\.js$/ export const isHTMLProxy = (id: string): boolean => htmlProxyRE.test(id) // HTML Proxy Caches are stored by config -> filePath -> index export const htmlProxyMap = new WeakMap< ResolvedConfig, Map<string, Array<string>> >() export function htmlInlineScriptProxyPlugin(config: ResolvedConfig): Plugin { return { name: 'vite:html-inline-script-proxy', resolveId(id) { if (htmlProxyRE.test(id)) { return id } }, buildStart() { htmlProxyMap.set(config, new Map()) }, load(id) { const proxyMatch = id.match(htmlProxyRE) if (proxyMatch) { const index = Number(proxyMatch[1]) const file = cleanUrl(id) const url = file.replace(normalizePath(config.root), '') const result = htmlProxyMap.get(config)!.get(url)![index] if (result) { return result } else { throw new Error(`No matching HTML proxy module found from ${id}`) } } } } } /** Add script to cache */ export function addToHTMLProxyCache( config: ResolvedConfig, filePath: string, index: number, code: string ): void { if (!htmlProxyMap.get(config)) { htmlProxyMap.set(config, new Map()) } if (!htmlProxyMap.get(config)!.get(filePath)) { htmlProxyMap.get(config)!.set(filePath, []) } htmlProxyMap.get(config)!.get(filePath)![index] = code } // this extends the config in @vue/compiler-sfc with <link href> export const assetAttrsConfig: Record<string, string[]> = { link: ['href'], video: ['src', 'poster'], source: ['src', 'srcset'], img: ['src', 'srcset'], image: ['xlink:href', 'href'], use: ['xlink:href', 'href'] } export const isAsyncScriptMap = new WeakMap< ResolvedConfig, Map<string, boolean> >() export async function traverseHtml( html: string, filePath: string, visitor: NodeTransform ): Promise<void> { // lazy load compiler const { parse, transform } = await import('@vue/compiler-dom') // @vue/compiler-core doesn't like lowercase doctypes html = html.replace(/<!doctype\s/i, '<!DOCTYPE ') try { const ast = parse(html, { comments: true }) transform(ast, { nodeTransforms: [visitor] }) } catch (e) { const parseError = { loc: filePath, frame: '', ...formatParseError(e, filePath, html) } throw new Error( `Unable to parse ${JSON.stringify(parseError.loc)}\n${parseError.frame}` ) } } export function getScriptInfo(node: ElementNode): { src: AttributeNode | undefined isModule: boolean isAsync: boolean } { let src: AttributeNode | undefined let isModule = false let isAsync = false for (let i = 0; i < node.props.length; i++) { const p = node.props[i] if (p.type === NodeTypes.ATTRIBUTE) { if (p.name === 'src') { src = p } else if (p.name === 'type' && p.value && p.value.content === 'module') { isModule = true } else if (p.name === 'async') { isAsync = true } } } return { src, isModule, isAsync } } function formatParseError(e: any, id: string, html: string): Error { // normalize the error to rollup format if (e.loc) { e.frame = generateCodeFrame(html, e.loc.start.offset) e.loc = { file: id, line: e.loc.start.line, column: e.loc.start.column } } return e } /** * Compiles index.html into an entry js module */ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { const [preHooks, postHooks] = resolveHtmlTransforms(config.plugins) const processedHtml = new Map<string, string>() const isExcludedUrl = (url: string) => url.startsWith('#') || isExternalUrl(url) || isDataUrl(url) || checkPublicFile(url, config) return { name: 'vite:build-html', buildStart() { isAsyncScriptMap.set(config, new Map()) }, async transform(html, id) { if (id.endsWith('.html')) { const publicPath = `/${slash(path.relative(config.root, id))}` // pre-transform html = await applyHtmlTransforms(html, preHooks, { path: publicPath, filename: id }) let js = '' const s = new MagicString(html) const assetUrls: AttributeNode[] = [] let inlineModuleIndex = -1 let everyScriptIsAsync = true let someScriptsAreAsync = false let someScriptsAreDefer = false await traverseHtml(html, id, (node) => { if (node.type !== NodeTypes.ELEMENT) { return } let shouldRemove = false // script tags if (node.tag === 'script') { const { src, isModule, isAsync } = getScriptInfo(node) const url = src && src.value && src.value.content const isPublicFile = !!(url && checkPublicFile(url, config)) if (isPublicFile) { // referencing public dir url, prefix with base s.overwrite( src!.value!.loc.start.offset, src!.value!.loc.end.offset, `"${config.base + url.slice(1)}"` ) } if (isModule) { inlineModuleIndex++ if (url && !isExcludedUrl(url)) { // <script type="module" src="..."/> // add it as an import js += `\nimport ${JSON.stringify(url)}` shouldRemove = true } else if (node.children.length) { const contents = node.children .map((child: any) => child.content || '') .join('') // <script type="module">...</script> const filePath = id.replace(normalizePath(config.root), '') addToHTMLProxyCache( config, filePath, inlineModuleIndex, contents ) js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"` shouldRemove = true } everyScriptIsAsync &&= isAsync someScriptsAreAsync ||= isAsync someScriptsAreDefer ||= !isAsync } else if (url && !isPublicFile) { config.logger.warn( `<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute` ) } } // For asset references in index.html, also generate an import // statement for each - this will be handled by the asset plugin const assetAttrs = assetAttrsConfig[node.tag] if (assetAttrs) { for (const p of node.props) { if ( p.type === NodeTypes.ATTRIBUTE && p.value && assetAttrs.includes(p.name) ) { const url = p.value.content if (!isExcludedUrl(url)) { if (node.tag === 'link' && isCSSRequest(url)) { // CSS references, convert to import js += `\nimport ${JSON.stringify(url)}` shouldRemove = true } else { assetUrls.push(p) } } else if (checkPublicFile(url, config)) { s.overwrite( p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"` ) } } } } if (shouldRemove) { // remove the script tag from the html. we are going to inject new // ones in the end. s.remove(node.loc.start.offset, node.loc.end.offset) } }) isAsyncScriptMap.get(config)!.set(id, everyScriptIsAsync) if (someScriptsAreAsync && someScriptsAreDefer) { config.logger.warn( `\nMixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.` ) } // for each encountered asset url, rewrite original html so that it // references the post-build location. for (const attr of assetUrls) { const value = attr.value! try { const url = attr.name === 'srcset' ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this) ) : await urlToBuiltUrl(value.content, id, config, this) s.overwrite( value.loc.start.offset, value.loc.end.offset, `"${url}"` ) } catch (e) { // #1885 preload may be pointing to urls that do not exist // locally on disk if (e.code !== 'ENOENT') { throw e } } } processedHtml.set(id, s.toString()) // inject module preload polyfill only when configured and needed if ( config.build.polyfillModulePreload && (someScriptsAreAsync || someScriptsAreDefer) ) { js = `import "${modulePreloadPolyfillId}";\n${js}` } return js } }, async generateBundle(options, bundle) { const analyzedChunk: Map<OutputChunk, number> = new Map() const getImportedChunks = ( chunk: OutputChunk, seen: Set<string> = new Set() ): OutputChunk[] => { const chunks: OutputChunk[] = [] chunk.imports.forEach((file) => { const importee = bundle[file] if (importee?.type === 'chunk' && !seen.has(file)) { seen.add(file) // post-order traversal chunks.push(...getImportedChunks(importee, seen)) chunks.push(importee) } }) return chunks } const toScriptTag = ( chunk: OutputChunk, isAsync: boolean ): HtmlTagDescriptor => ({ tag: 'script', attrs: { ...(isAsync ? { async: true } : {}), type: 'module', crossorigin: true, src: toPublicPath(chunk.fileName, config) } }) const toPreloadTag = (chunk: OutputChunk): HtmlTagDescriptor => ({ tag: 'link', attrs: { rel: 'modulepreload', href: toPublicPath(chunk.fileName, config) } }) const getCssTagsForChunk = ( chunk: OutputChunk, seen: Set<string> = new Set() ): HtmlTagDescriptor[] => { const tags: HtmlTagDescriptor[] = [] if (!analyzedChunk.has(chunk)) { analyzedChunk.set(chunk, 1) chunk.imports.forEach((file) => { const importee = bundle[file] if (importee?.type === 'chunk') { tags.push(...getCssTagsForChunk(importee, seen)) } }) } const cssFiles = chunkToEmittedCssFileMap.get(chunk) if (cssFiles) { cssFiles.forEach((file) => { if (!seen.has(file)) { seen.add(file) tags.push({ tag: 'link', attrs: { rel: 'stylesheet', href: toPublicPath(file, config) } }) } }) } return tags } for (const [id, html] of processedHtml) { const isAsync = isAsyncScriptMap.get(config)!.get(id)! // resolve asset url references let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { return config.base + getAssetFilename(fileHash, config) + postfix }) // find corresponding entry chunk const chunk = Object.values(bundle).find( (chunk) => chunk.type === 'chunk' && chunk.isEntry && chunk.facadeModuleId === id ) as OutputChunk | undefined let canInlineEntry = false // inject chunk asset links if (chunk) { // an entry chunk can be inlined if // - it's an ES module (e.g. not generated by the legacy plugin) // - it contains no meaningful code other than import statements if (options.format === 'es' && isEntirelyImport(chunk.code)) { canInlineEntry = true } // when not inlined, inject <script> for entry and modulepreload its dependencies // when inlined, discard entry chunk and inject <script> for everything in post-order const imports = getImportedChunks(chunk) const assetTags = canInlineEntry ? imports.map((chunk) => toScriptTag(chunk, isAsync)) : [toScriptTag(chunk, isAsync), ...imports.map(toPreloadTag)] assetTags.push(...getCssTagsForChunk(chunk)) result = injectToHead(result, assetTags) } // inject css link when cssCodeSplit is false if (!config.build.cssCodeSplit) { const cssChunk = Object.values(bundle).find( (chunk) => chunk.type === 'asset' && chunk.name === 'style.css' ) as OutputAsset | undefined if (cssChunk) { result = injectToHead(result, [ { tag: 'link', attrs: { rel: 'stylesheet', href: toPublicPath(cssChunk.fileName, config) } } ]) } } const shortEmitName = path.posix.relative(config.root, id) result = await applyHtmlTransforms(result, postHooks, { path: '/' + shortEmitName, filename: id, bundle, chunk }) if (chunk && canInlineEntry) { // all imports from entry have been inlined to html, prevent rollup from outputting it delete bundle[chunk.fileName] } this.emitFile({ type: 'asset', fileName: shortEmitName, source: result }) } } } } export interface HtmlTagDescriptor { tag: string attrs?: Record<string, string | boolean | undefined> children?: string | HtmlTagDescriptor[] /** * default: 'head-prepend' */ injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend' } export type IndexHtmlTransformResult = | string | HtmlTagDescriptor[] | { html: string tags: HtmlTagDescriptor[] } export interface IndexHtmlTransformContext { /** * public path when served */ path: string /** * filename on disk */ filename: string server?: ViteDevServer bundle?: OutputBundle chunk?: OutputChunk originalUrl?: string } export type IndexHtmlTransformHook = ( html: string, ctx: IndexHtmlTransformContext ) => IndexHtmlTransformResult | void | Promise<IndexHtmlTransformResult | void> export type IndexHtmlTransform = | IndexHtmlTransformHook | { enforce?: 'pre' | 'post' transform: IndexHtmlTransformHook } export function resolveHtmlTransforms( plugins: readonly Plugin[] ): [IndexHtmlTransformHook[], IndexHtmlTransformHook[]] { const preHooks: IndexHtmlTransformHook[] = [] const postHooks: IndexHtmlTransformHook[] = [] for (const plugin of plugins) { const hook = plugin.transformIndexHtml if (hook) { if (typeof hook === 'function') { postHooks.push(hook) } else if (hook.enforce === 'pre') { preHooks.push(hook.transform) } else { postHooks.push(hook.transform) } } } return [preHooks, postHooks] } export async function applyHtmlTransforms( html: string, hooks: IndexHtmlTransformHook[], ctx: IndexHtmlTransformContext ): Promise<string> { const headTags: HtmlTagDescriptor[] = [] const headPrependTags: HtmlTagDescriptor[] = [] const bodyTags: HtmlTagDescriptor[] = [] const bodyPrependTags: HtmlTagDescriptor[] = [] for (const hook of hooks) { const res = await hook(html, ctx) if (!res) { continue } if (typeof res === 'string') { html = res } else { let tags: HtmlTagDescriptor[] if (Array.isArray(res)) { tags = res } else { html = res.html || html tags = res.tags } for (const tag of tags) { if (tag.injectTo === 'body') { bodyTags.push(tag) } else if (tag.injectTo === 'body-prepend') { bodyPrependTags.push(tag) } else if (tag.injectTo === 'head') { headTags.push(tag) } else { headPrependTags.push(tag) } } } } // inject tags if (headPrependTags.length) { html = injectToHead(html, headPrependTags, true) } if (headTags.length) { html = injectToHead(html, headTags) } if (bodyPrependTags.length) { html = injectToBody(html, bodyPrependTags, true) } if (bodyTags.length) { html = injectToBody(html, bodyTags) } return html } const importRE = /\bimport\s*("[^"]*[^\\]"|'[^']*[^\\]');*/g const commentRE = /\/\*[\s\S]*?\*\/|\/\/.*$/gm function isEntirelyImport(code: string) { // only consider "side-effect" imports, which match <script type=module> semantics exactly // the regexes will remove too little in some exotic cases, but false-negatives are alright return !code.replace(importRE, '').replace(commentRE, '').trim().length } function toPublicPath(filename: string, config: ResolvedConfig) { return isExternalUrl(filename) ? filename : config.base + filename } const headInjectRE = /([ \t]*)<\/head>/i const headPrependInjectRE = /([ \t]*)<head[^>]*>/i const htmlInjectRE = /<\/html>/i const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i const bodyInjectRE = /([ \t]*)<\/body>/i const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i const doctypePrependInjectRE = /<!doctype html>/i function injectToHead( html: string, tags: HtmlTagDescriptor[], prepend = false ) { if (prepend) { // inject as the first element of head if (headPrependInjectRE.test(html)) { return html.replace( headPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}` ) } } else { // inject before head close if (headInjectRE.test(html)) { // respect indentation of head tag return html.replace( headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}` ) } // try to inject before the body tag if (bodyPrependInjectRE.test(html)) { return html.replace( bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}` ) } } // if no head tag is present, we prepend the tag for both prepend and append return prependInjectFallback(html, tags) } function injectToBody( html: string, tags: HtmlTagDescriptor[], prepend = false ) { if (prepend) { // inject after body open if (bodyPrependInjectRE.test(html)) { return html.replace( bodyPrependInjectRE, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}` ) } // if no there is no body tag, inject after head or fallback to prepend in html if (headInjectRE.test(html)) { return html.replace( headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}` ) } return prependInjectFallback(html, tags) } else { // inject before body close if (bodyInjectRE.test(html)) { return html.replace( bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}` ) } // if no body tag is present, append to the html tag, or at the end of the file if (htmlInjectRE.test(html)) { return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`) } return html + `\n` + serializeTags(tags) } } function prependInjectFallback(html: string, tags: HtmlTagDescriptor[]) { // prepend to the html tag, append after doctype, or the document start if (htmlPrependInjectRE.test(html)) { return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`) } if (doctypePrependInjectRE.test(html)) { return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`) } return serializeTags(tags) + html } const unaryTags = new Set(['link', 'meta', 'base']) function serializeTag( { tag, attrs, children }: HtmlTagDescriptor, indent: string = '' ): string { if (unaryTags.has(tag)) { return `<${tag}${serializeAttrs(attrs)}>` } else { return `<${tag}${serializeAttrs(attrs)}>${serializeTags( children, incrementIndent(indent) )}</${tag}>` } } function serializeTags( tags: HtmlTagDescriptor['children'], indent: string = '' ): string { if (typeof tags === 'string') { return tags } else if (tags && tags.length) { return tags.map((tag) => `${indent}${serializeTag(tag, indent)}\n`).join('') } return '' } function serializeAttrs(attrs: HtmlTagDescriptor['attrs']): string { let res = '' for (const key in attrs) { if (typeof attrs[key] === 'boolean') { res += attrs[key] ? ` ${key}` : `` } else { res += ` ${key}=${JSON.stringify(attrs[key])}` } } return res } function incrementIndent(indent: string = '') { return `${indent}${indent[0] === '\t' ? '\t' : ' '}` }
the_stack
import Displayable, { DisplayableProps, CommonStyleProps, DEFAULT_COMMON_STYLE, DisplayableStatePropNames, DEFAULT_COMMON_ANIMATION_PROPS } from './Displayable'; import Element, { ElementAnimateConfig } from '../Element'; import PathProxy from '../core/PathProxy'; import * as pathContain from '../contain/path'; import { PatternObject } from './Pattern'; import { Dictionary, PropType, MapToType } from '../core/types'; import BoundingRect from '../core/BoundingRect'; import { LinearGradientObject } from './LinearGradient'; import { RadialGradientObject } from './RadialGradient'; import { defaults, keys, extend, clone, isString, createObject } from '../core/util'; import Animator from '../animation/Animator'; import { lum } from '../tool/color'; import { DARK_LABEL_COLOR, LIGHT_LABEL_COLOR, DARK_MODE_THRESHOLD, LIGHTER_LABEL_COLOR } from '../config'; import { REDRAW_BIT, SHAPE_CHANGED_BIT, STYLE_CHANGED_BIT } from './constants'; export interface PathStyleProps extends CommonStyleProps { fill?: string | PatternObject | LinearGradientObject | RadialGradientObject stroke?: string | PatternObject | LinearGradientObject | RadialGradientObject decal?: PatternObject /** * Still experimental, not works weel on arc with edge cases(large angle). */ strokePercent?: number strokeNoScale?: boolean fillOpacity?: number strokeOpacity?: number /** * `true` is not supported. * `false`/`null`/`undefined` are the same. * `false` is used to remove lineDash in some * case that `null`/`undefined` can not be set. * (e.g., emphasis.lineStyle in echarts) */ lineDash?: false | number[] | 'solid' | 'dashed' | 'dotted' lineDashOffset?: number lineWidth?: number lineCap?: CanvasLineCap lineJoin?: CanvasLineJoin miterLimit?: number /** * Paint order, if do stroke first. Similar to SVG paint-order * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/paint-order */ strokeFirst?: boolean } export const DEFAULT_PATH_STYLE: PathStyleProps = defaults({ fill: '#000', stroke: null, strokePercent: 1, fillOpacity: 1, strokeOpacity: 1, lineDashOffset: 0, lineWidth: 1, lineCap: 'butt', miterLimit: 10, strokeNoScale: false, strokeFirst: false } as PathStyleProps, DEFAULT_COMMON_STYLE); export const DEFAULT_PATH_ANIMATION_PROPS: MapToType<PathProps, boolean> = { style: defaults<MapToType<PathStyleProps, boolean>, MapToType<PathStyleProps, boolean>>({ fill: true, stroke: true, strokePercent: true, fillOpacity: true, strokeOpacity: true, lineDashOffset: true, lineWidth: true, miterLimit: true } as MapToType<PathStyleProps, boolean>, DEFAULT_COMMON_ANIMATION_PROPS.style) }; export interface PathProps extends DisplayableProps { strokeContainThreshold?: number segmentIgnoreThreshold?: number subPixelOptimize?: boolean style?: PathStyleProps shape?: Dictionary<any> autoBatch?: boolean __value?: (string | number)[] | (string | number) buildPath?: ( ctx: PathProxy | CanvasRenderingContext2D, shapeCfg: Dictionary<any>, inBatch?: boolean ) => void } type PathKey = keyof PathProps type PathPropertyType = PropType<PathProps, PathKey> // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Path<Props extends PathProps = PathProps> { animate(key?: '', loop?: boolean): Animator<this> animate(key: 'style', loop?: boolean): Animator<this['style']> animate(key: 'shape', loop?: boolean): Animator<this['shape']> getState(stateName: string): PathState ensureState(stateName: string): PathState states: Dictionary<PathState> stateProxy: (stateName: string) => PathState } export type PathStatePropNames = DisplayableStatePropNames | 'shape'; export type PathState = Pick<PathProps, PathStatePropNames> & { hoverLayer?: boolean } const pathCopyParams = [ 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible', 'culling', 'z', 'z2', 'zlevel', 'parent' ] as const; class Path<Props extends PathProps = PathProps> extends Displayable<Props> { path: PathProxy strokeContainThreshold: number // This item default to be false. But in map series in echarts, // in order to improve performance, it should be set to true, // so the shorty segment won't draw. segmentIgnoreThreshold: number subPixelOptimize: boolean style: PathStyleProps /** * If element can be batched automatically */ autoBatch: boolean private _rectWithStroke: BoundingRect protected _normalState: PathState protected _decalEl: Path // Must have an initial value on shape. // It will be assigned by default value. shape: Dictionary<any> constructor(opts?: Props) { super(opts); } update() { super.update(); const style = this.style; if (style.decal) { const decalEl: Path = this._decalEl = this._decalEl || new Path(); if (decalEl.buildPath === Path.prototype.buildPath) { decalEl.buildPath = ctx => { this.buildPath(ctx, this.shape); }; } decalEl.silent = true; const decalElStyle = decalEl.style; for (let key in style) { if ((decalElStyle as any)[key] !== (style as any)[key]) { (decalElStyle as any)[key] = (style as any)[key]; } } decalElStyle.fill = style.fill ? style.decal : null; decalElStyle.decal = null; decalElStyle.shadowColor = null; style.strokeFirst && (decalElStyle.stroke = null); for (let i = 0; i < pathCopyParams.length; ++i) { (decalEl as any)[pathCopyParams[i]] = this[pathCopyParams[i]]; } decalEl.__dirty |= REDRAW_BIT; } else if (this._decalEl) { this._decalEl = null; } } getDecalElement() { return this._decalEl; } protected _init(props?: Props) { // Init default properties const keysArr = keys(props); this.shape = this.getDefaultShape(); const defaultStyle = this.getDefaultStyle(); if (defaultStyle) { this.useStyle(defaultStyle); } for (let i = 0; i < keysArr.length; i++) { const key = keysArr[i]; const value = props[key]; if (key === 'style') { if (!this.style) { // PENDING Reuse style object if possible? this.useStyle(value as Props['style']); } else { extend(this.style, value as Props['style']); } } else if (key === 'shape') { // this.shape = value; extend(this.shape, value as Props['shape']); } else { super.attrKV(key as any, value); } } // Create an empty one if no style object exists. if (!this.style) { this.useStyle({}); } // const defaultShape = this.getDefaultShape(); // if (!this.shape) { // this.shape = defaultShape; // } // else { // defaults(this.shape, defaultShape); // } } protected getDefaultStyle(): Props['style'] { return null; } // Needs to override protected getDefaultShape() { return {}; } protected canBeInsideText() { return this.hasFill(); } protected getInsideTextFill() { const pathFill = this.style.fill; if (pathFill !== 'none') { if (isString(pathFill)) { const fillLum = lum(pathFill, 0); // Determin text color based on the lum of path fill. // TODO use (1 - DARK_MODE_THRESHOLD)? if (fillLum > 0.5) { // TODO Consider background lum? return DARK_LABEL_COLOR; } else if (fillLum > 0.2) { return LIGHTER_LABEL_COLOR; } return LIGHT_LABEL_COLOR; } else if (pathFill) { return LIGHT_LABEL_COLOR; } } return DARK_LABEL_COLOR; } protected getInsideTextStroke(textFill?: string) { const pathFill = this.style.fill; // Not stroke on none fill object or gradient object if (isString(pathFill)) { const zr = this.__zr; const isDarkMode = !!(zr && zr.isDarkMode()); const isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD; // All dark or all light. if (isDarkMode === isDarkLabel) { return pathFill; } } } // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath // Like in circle buildPath( ctx: PathProxy | CanvasRenderingContext2D, shapeCfg: Dictionary<any>, inBatch?: boolean ) {} pathUpdated() { this.__dirty &= ~SHAPE_CHANGED_BIT; } getUpdatedPathProxy(inBatch?: boolean) { // Update path proxy data to latest. !this.path && this.createPathProxy(); this.path.beginPath(); this.buildPath(this.path, this.shape, inBatch); return this.path; } createPathProxy() { this.path = new PathProxy(false); } hasStroke() { const style = this.style; const stroke = style.stroke; return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0)); } hasFill() { const style = this.style; const fill = style.fill; return fill != null && fill !== 'none'; } getBoundingRect(): BoundingRect { let rect = this._rect; const style = this.style; const needsUpdateRect = !rect; if (needsUpdateRect) { let firstInvoke = false; if (!this.path) { firstInvoke = true; // Create path on demand. this.createPathProxy(); } let path = this.path; if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) { path.beginPath(); this.buildPath(path, this.shape, false); this.pathUpdated(); } rect = path.getBoundingRect(); } this._rect = rect; if (this.hasStroke() && this.path && this.path.len() > 0) { // Needs update rect with stroke lineWidth when // 1. Element changes scale or lineWidth // 2. Shape is changed const rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone()); if (this.__dirty || needsUpdateRect) { rectWithStroke.copy(rect); // PENDING, Min line width is needed when line is horizontal or vertical const lineScale = style.strokeNoScale ? this.getLineScale() : 1; // FIXME Must after updateTransform let w = style.lineWidth; // Only add extra hover lineWidth when there are no fill if (!this.hasFill()) { const strokeContainThreshold = this.strokeContainThreshold; w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold); } // Consider line width // Line scale can't be 0; if (lineScale > 1e-10) { rectWithStroke.width += w / lineScale; rectWithStroke.height += w / lineScale; rectWithStroke.x -= w / lineScale / 2; rectWithStroke.y -= w / lineScale / 2; } } // Return rect with stroke return rectWithStroke; } return rect; } contain(x: number, y: number): boolean { const localPos = this.transformCoordToLocal(x, y); const rect = this.getBoundingRect(); const style = this.style; x = localPos[0]; y = localPos[1]; if (rect.contain(x, y)) { const pathProxy = this.path; if (this.hasStroke()) { let lineWidth = style.lineWidth; let lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Line scale can't be 0; if (lineScale > 1e-10) { // Only add extra hover lineWidth when there are no fill if (!this.hasFill()) { lineWidth = Math.max(lineWidth, this.strokeContainThreshold); } if (pathContain.containStroke( pathProxy, lineWidth / lineScale, x, y )) { return true; } } } if (this.hasFill()) { return pathContain.contain(pathProxy, x, y); } } return false; } /** * Shape changed */ dirtyShape() { this.__dirty |= SHAPE_CHANGED_BIT; if (this._rect) { this._rect = null; } if (this._decalEl) { this._decalEl.dirtyShape(); } this.markRedraw(); } dirty() { this.dirtyStyle(); this.dirtyShape(); } /** * Alias for animate('shape') * @param {boolean} loop */ animateShape(loop: boolean) { return this.animate('shape', loop); } // Override updateDuringAnimation updateDuringAnimation(targetKey: string) { if (targetKey === 'style') { this.dirtyStyle(); } else if (targetKey === 'shape') { this.dirtyShape(); } else { this.markRedraw(); } } // Overwrite attrKV attrKV(key: PathKey, value: PathPropertyType) { // FIXME if (key === 'shape') { this.setShape(value as Props['shape']); } else { super.attrKV(key as keyof DisplayableProps, value); } } setShape(obj: Props['shape']): this setShape<T extends keyof Props['shape']>(obj: T, value: Props['shape'][T]): this setShape(keyOrObj: keyof Props['shape'] | Props['shape'], value?: unknown): this { let shape = this.shape; if (!shape) { shape = this.shape = {}; } // Path from string may not have shape if (typeof keyOrObj === 'string') { shape[keyOrObj] = value; } else { extend(shape, keyOrObj as Props['shape']); } this.dirtyShape(); return this; } /** * If shape changed. used with dirtyShape */ shapeChanged() { return !!(this.__dirty & SHAPE_CHANGED_BIT); } /** * Create a path style object with default values in it's prototype. * @override */ createStyle(obj?: Props['style']) { return createObject(DEFAULT_PATH_STYLE, obj); } protected _innerSaveToNormal(toState: PathState) { super._innerSaveToNormal(toState); const normalState = this._normalState; // Clone a new one. DON'T share object reference between states and current using. // TODO: Clone array in shape?. // TODO: Only save changed shape. if (toState.shape && !normalState.shape) { normalState.shape = extend({}, this.shape); } } protected _applyStateObj( stateName: string, state: PathState, normalState: PathState, keepCurrentStates: boolean, transition: boolean, animationCfg: ElementAnimateConfig ) { super._applyStateObj(stateName, state, normalState, keepCurrentStates, transition, animationCfg); const needsRestoreToNormal = !(state && keepCurrentStates); let targetShape: Props['shape']; if (state && state.shape) { // Only animate changed properties. if (transition) { if (keepCurrentStates) { targetShape = state.shape; } else { // Inherits from normal state. targetShape = extend({}, normalState.shape); extend(targetShape, state.shape); } } else { // Because the shape will be replaced. So inherits from current shape. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape); extend(targetShape, state.shape); } } else if (needsRestoreToNormal) { targetShape = normalState.shape; } if (targetShape) { if (transition) { // Clone a new shape. this.shape = extend({}, this.shape); // Only supports transition on primary props. Because shape is not deep cloned. const targetShapePrimaryProps: Props['shape'] = {}; const shapeKeys = keys(targetShape); for (let i = 0; i < shapeKeys.length; i++) { const key = shapeKeys[i]; if (typeof targetShape[key] === 'object') { (this.shape as Props['shape'])[key] = targetShape[key]; } else { targetShapePrimaryProps[key] = targetShape[key]; } } this._transitionState(stateName, { shape: targetShapePrimaryProps } as Props, animationCfg); } else { this.shape = targetShape; this.dirtyShape(); } } } protected _mergeStates(states: PathState[]) { const mergedState = super._mergeStates(states) as PathState; let mergedShape: Props['shape']; for (let i = 0; i < states.length; i++) { const state = states[i]; if (state.shape) { mergedShape = mergedShape || {}; this._mergeStyle(mergedShape, state.shape); } } if (mergedShape) { mergedState.shape = mergedShape; } return mergedState; } getAnimationStyleProps() { return DEFAULT_PATH_ANIMATION_PROPS; } /** * If path shape is zero area */ isZeroArea(): boolean { return false; } /** * 扩展一个 Path element, 比如星形,圆等。 * Extend a path element * @DEPRECATED Use class extends * @param props * @param props.type Path type * @param props.init Initialize * @param props.buildPath Overwrite buildPath method * @param props.style Extended default style config * @param props.shape Extended default shape config */ static extend<Shape extends Dictionary<any>>(defaultProps: { type?: string shape?: Shape style?: PathStyleProps beforeBrush?: Displayable['beforeBrush'] afterBrush?: Displayable['afterBrush'] getBoundingRect?: Displayable['getBoundingRect'] calculateTextPosition?: Element['calculateTextPosition'] buildPath(this: Path, ctx: CanvasRenderingContext2D | PathProxy, shape: Shape, inBatch?: boolean): void init?(this: Path, opts: PathProps): void // TODO Should be SubPathOption }): { new(opts?: PathProps & {shape: Shape}): Path } { interface SubPathOption extends PathProps { shape: Shape } class Sub extends Path { shape: Shape getDefaultStyle() { return clone(defaultProps.style); } getDefaultShape() { return clone(defaultProps.shape); } constructor(opts?: SubPathOption) { super(opts); defaultProps.init && defaultProps.init.call(this as any, opts); } } // TODO Legacy usage. Extend functions for (let key in defaultProps) { if (typeof (defaultProps as any)[key] === 'function') { (Sub.prototype as any)[key] = (defaultProps as any)[key]; } } // Sub.prototype.buildPath = defaultProps.buildPath; // Sub.prototype.beforeBrush = defaultProps.beforeBrush; // Sub.prototype.afterBrush = defaultProps.afterBrush; return Sub as any; } protected static initDefaultProps = (function () { const pathProto = Path.prototype; pathProto.type = 'path'; pathProto.strokeContainThreshold = 5; pathProto.segmentIgnoreThreshold = 0; pathProto.subPixelOptimize = false; pathProto.autoBatch = false; pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT; })() } export default Path;
the_stack
import {HttpClientModule} from '@angular/common/http'; import {HttpClientTestingModule} from '@angular/common/http/testing'; import {Component} from '@angular/core'; import {ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing'; import {DomSanitizer} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {RouterTestingModule} from '@angular/router/testing'; import {of} from 'rxjs'; import {APPLICATION_PERMISSIONS} from '../../app.config'; import {MatIconRegistry} from '../../core/material_module'; import {Dialog} from '../../services/dialog'; import {ShelfService} from '../../services/shelf'; import {UserService} from '../../services/user'; import {ShelfServiceMock, TEST_SHELF, TEST_SHELF_AUDIT_DISABLED, TEST_SHELF_SYSTEM_AUDIT_DISABLED, TEST_SHELF_SYSTEM_AUDIT_ENABLED, TEST_USER, UserServiceMock} from '../../testing/mocks'; import {ShelfDetails, ShelfDetailsModule} from './index'; @Component({ preserveWhitespaces: true, template: '', }) class DummyComponent { } describe('ShelfDetailsComponent', () => { let fixture: ComponentFixture<ShelfDetails>; let shelfDetails: ShelfDetails; beforeEach(fakeAsync(() => { TestBed .configureTestingModule({ declarations: [DummyComponent], imports: [ RouterTestingModule.withRoutes([ {path: 'shelves', component: DummyComponent}, ]), ShelfDetailsModule, HttpClientModule, HttpClientTestingModule, BrowserAnimationsModule, ], providers: [ {provide: ShelfService, useClass: ShelfServiceMock}, {provide: UserService, useClass: UserServiceMock}, ], }) .compileComponents(); flushMicrotasks(); const iconRegistry = TestBed.get(MatIconRegistry); const sanitizer = TestBed.get(DomSanitizer); iconRegistry.addSvgIcon( 'checkin', // Note: The bypassSecurity here can't be refactored: the code // is destined to be open-sourced. sanitizer.bypassSecurityTrustResourceUrl('/fakepath/checkin')); fixture = TestBed.createComponent(ShelfDetails); shelfDetails = fixture.debugElement.componentInstance; shelfDetails.shelf = TEST_SHELF; })); it('should create the ShelfDetails', () => { expect(shelfDetails).toBeDefined(); }); it('should render card title in a mat-card-title', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.mat-card-title').textContent) .toContain('Shelf Details'); }); it('should render the location inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.location').textContent) .toContain('Location'); }); it('should render the friendly location inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.friendlyName').textContent) .toContain('Friendly Name'); }); it('should render the capacity inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.capacity').textContent) .toContain('Capacity'); }); it('should render the latitude inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.latitude').textContent) .toContain('Latitude'); }); it('should render the longitude inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.longitude').textContent) .toContain('Longitude'); }); it('should render the altitude inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.altitude').textContent) .toContain('Altitude'); }); it('should render the responsible inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.responsible').textContent) .toContain('Responsible'); }); it('renders the last audit time inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.last-audit-time').textContent) .toContain('Last Audit Time'); }); it('renders the last audit by inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('.last-audit-by').textContent) .toContain('Last Audit By'); }); it('renders the shelf audit notifications inside loaner-viewonly-label', () => { fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('loaner-viewonly-label.audit-status') .textContent) .toContain('Audit notification'); }); it('should render the shelf as audits enabled by system and shelf', () => { shelfDetails.shelf = TEST_SHELF_SYSTEM_AUDIT_ENABLED; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('loaner-viewonly-label.audit-status') .textContent) .toContain('Audit notifications are enabled'); }); it('should render the shelf as audits disabled by system', () => { shelfDetails.shelf = TEST_SHELF_SYSTEM_AUDIT_DISABLED; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('loaner-viewonly-label.audit-status') .textContent) .toContain('Audit notifications are disabled by system'); }); it('should render the shelf as audits disabled by shelf', () => { shelfDetails.shelf = TEST_SHELF_AUDIT_DISABLED; fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('loaner-viewonly-label.audit-status') .textContent) .toContain('Audit notifications are disabled on shelf'); }); it('should call openDialog when button is clicked.', () => { }); it('should call disable when delete a shelf.', () => { const shelfService = TestBed.get(ShelfService); spyOn(shelfService, 'disable'); const dialog = TestBed.get(Dialog); spyOn(dialog, 'confirm').and.returnValue(of(true)); shelfDetails.openDisableDialog(); fixture.detectChanges(); expect(shelfService.disable).toHaveBeenCalled(); }); it('shows the quick audit button to auditors', fakeAsync(() => { const userService = TestBed.get(UserService); const testUser = TEST_USER; testUser.permissions.push(APPLICATION_PERMISSIONS.AUDIT_SHELF); spyOn(userService, 'whenUserLoaded').and.returnValue(of(testUser)); fixture.detectChanges(); tick(250); const compiled = fixture.debugElement.nativeElement; expect(shelfDetails.showQuickAudit).toBe(true); expect(compiled.querySelector('.quickAuditButton')).toBeTruthy(); })); it('hides the quick audit button for non-auditors', fakeAsync(() => { const userService = TestBed.get(UserService); const testUser = TEST_USER; testUser.permissions = testUser.permissions.filter(permission => { return permission !== APPLICATION_PERMISSIONS.AUDIT_SHELF; }); spyOn(userService, 'whenUserLoaded').and.returnValue(of(testUser)); fixture.detectChanges(); tick(250); const compiled = fixture.debugElement.nativeElement; expect(shelfDetails.showQuickAudit).toBe(false); expect(compiled.querySelector('.quickAuditButton')).toBeFalsy(); })); it('shows the advanced options to superadmins', fakeAsync(() => { const userService = TestBed.get(UserService); const testUser = TEST_USER; testUser.superadmin = true; spyOn(userService, 'whenUserLoaded').and.returnValue(of(testUser)); fixture.detectChanges(); tick(250); const compiled = fixture.debugElement.nativeElement; expect(shelfDetails.showAdvancedOptions).toBe(true); expect(compiled.querySelector('.actionsMenuButton')).toBeTruthy(); expect(compiled.querySelector('.quickAuditButton')).toBeFalsy(); })); it('hides the advanced options for non-superadmins', fakeAsync(() => { const userService = TestBed.get(UserService); const testUser = TEST_USER; testUser.superadmin = false; spyOn(userService, 'whenUserLoaded').and.returnValue(of(testUser)); fixture.detectChanges(); tick(250); const compiled = fixture.debugElement.nativeElement; expect(shelfDetails.showAdvancedOptions).toBe(false); expect(compiled.querySelector('.actionsMenuButton')).toBeFalsy(); })); it('hides quick audit button when user is superadmin', fakeAsync(() => { const userService = TestBed.get(UserService); const testUser = TEST_USER; testUser.superadmin = true; testUser.permissions.push(APPLICATION_PERMISSIONS.AUDIT_SHELF); spyOn(userService, 'whenUserLoaded').and.returnValue(of(testUser)); fixture.detectChanges(); tick(250); const compiled = fixture.debugElement.nativeElement; expect(shelfDetails.showAdvancedOptions).toBe(true); expect(shelfDetails.showQuickAudit).toBe(false); expect(compiled.querySelector('.actionsMenuButton')).toBeTruthy(); expect(compiled.querySelector('.quickAuditButton')).toBeFalsy(); })); });
the_stack
import Debug from 'debug'; import events from 'events'; import SerialPort from 'serialport'; import Writer from './writer'; import Parser from './parser'; import Frame from './frame'; import PARAM from './constants'; import * as Events from '../../events'; import SerialPortUtils from '../../serialPortUtils'; import SocketPortUtils from '../../socketPortUtils'; import net from 'net'; import { Command, Request, parameterT, ApsDataRequest, ReceivedDataResponse, DataStateResponse } from './constants'; // @ts-ignore import slip from 'slip'; const debug = Debug('zigbee-herdsman:deconz:driver'); const autoDetectDefinitions = [ {manufacturer: 'dresden elektronik ingenieurtechnik GmbH', vendorId: '1cf1', productId: '0030'}, // Conbee II ]; var queue: Array<object> = []; var busyQueue: Array<object> = []; var apsQueue: Array<object> = []; var apsBusyQueue: Array<object> = []; var apsConfirmIndQueue: Array<object> = []; var timeoutCounter = 0; var readyToSend: boolean = true; function enableRTS() { if (readyToSend === false) { readyToSend = true; } } function disableRTS() { readyToSend = false; } var enableRtsTimeout: ReturnType<typeof setTimeout> = null; export { busyQueue, apsBusyQueue, readyToSend, enableRTS, disableRTS, enableRtsTimeout }; var frameParser = require('./frameParser'); const littleEndian = true; class Driver extends events.EventEmitter { private path: string; private serialPort: SerialPort; private initialized: boolean; private writer: Writer; private parser: Parser; private frameParserEvent = frameParser.frameParserEvents; private seqNumber: number; private timeoutResetTimeout: any; private apsRequestFreeSlots: number; private apsDataConfirm: number; private apsDataIndication: number; private configChanged: number; private portType: 'serial' | 'socket'; private socketPort: net.Socket; private DELAY: number; private READY_TO_SEND_TIMEOUT: number; private HANDLE_DEVICE_STATUS_DELAY: number; private PROCESS_QUEUES: number; public constructor(path: string) { super(); this.path = path; this.initialized = false; this.seqNumber = 0; this.timeoutResetTimeout = null; this.portType = SocketPortUtils.isTcpPath(path) ? 'socket' : 'serial'; this.apsRequestFreeSlots = 1; this.apsDataConfirm = 0; this.apsDataIndication = 0; this.configChanged = 0; this.DELAY = 0; this.READY_TO_SEND_TIMEOUT = 1; this.HANDLE_DEVICE_STATUS_DELAY = 5; this.PROCESS_QUEUES = 5; const that = this; setInterval(() => { that.deviceStateRequest() .then(result => {}) .catch(error => {}); }, 10000); setInterval(() => { that.writeParameterRequest(0x26, 600) // reset watchdog // 10 minutes .then(result => {}) .catch(error => { //try again debug("try again to reset watchdog"); that.writeParameterRequest(0x26, 600) .then(result => {}) .catch(error => {debug("warning watchdog was not reset");}); }); }, (1000 * 60 * 8)); // 8 minutes this.onParsed = this.onParsed.bind(this); this.frameParserEvent.on('receivedDataNotification', (data: number) => {this.checkDeviceStatus(data)}); } public setDelay(delay: number): void { debug(`Set delay to ${delay}`); this.DELAY = delay; this.READY_TO_SEND_TIMEOUT = delay; this.PROCESS_QUEUES = delay; this.HANDLE_DEVICE_STATUS_DELAY = delay; if (this.READY_TO_SEND_TIMEOUT === 0) { this.READY_TO_SEND_TIMEOUT = 1; } if (this.PROCESS_QUEUES < 5) { this.PROCESS_QUEUES = 5; } if (this.HANDLE_DEVICE_STATUS_DELAY < 5) { this.HANDLE_DEVICE_STATUS_DELAY = 5; } if (this.PROCESS_QUEUES > 60) { this.PROCESS_QUEUES = 60; } if (this.HANDLE_DEVICE_STATUS_DELAY > 60) { this.HANDLE_DEVICE_STATUS_DELAY = 60; } const that = this setInterval(() => { that.processQueue(); }, this.PROCESS_QUEUES); // fire non aps requests setInterval(() => { that.processBusyQueue(); }, this.PROCESS_QUEUES); // check timeouts for non aps requests setInterval(() => { that.processApsQueue(); }, this.PROCESS_QUEUES); // fire aps request setInterval(() => { that.processApsBusyQueue(); }, this.PROCESS_QUEUES); // check timeouts for all open aps requests setInterval(() => { that.processApsConfirmIndQueue(); }, this.PROCESS_QUEUES); // fire aps indications and confirms setInterval(() => { that.handleDeviceStatus() .then(result => {}) .catch(error => {}); }, this.HANDLE_DEVICE_STATUS_DELAY); // query confirm and indication requests } public static async isValidPath(path: string): Promise<boolean> { return SerialPortUtils.is(path, autoDetectDefinitions); } public static async autoDetectPath(): Promise<string> { const paths = await SerialPortUtils.find(autoDetectDefinitions); return paths.length > 0 ? paths[0] : null; } private onPortClose(): void { debug('Port closed'); this.initialized = false; this.emit('close'); } public async open(): Promise<void> { return this.portType === 'serial' ? this.openSerialPort() : this.openSocketPort(); } public openSerialPort(): Promise<void> { debug(`Opening with ${this.path}`); this.serialPort = new SerialPort(this.path, {baudRate: 38400, autoOpen: false}); this.writer = new Writer(); // @ts-ignore this.writer.pipe(this.serialPort); this.parser = new Parser(); this.serialPort.pipe(this.parser); this.parser.on('parsed', this.onParsed); return new Promise((resolve, reject): void => { this.serialPort.open(async (error: object): Promise<void> => { if (error) { reject(new Error(`Error while opening serialport '${error}'`)); this.initialized = false; if (this.serialPort.isOpen) { this.serialPort.close(); } } else { debug('Serialport opened'); this.initialized = true; resolve(); } }); }); } private async openSocketPort(): Promise<void> { const info = SocketPortUtils.parseTcpPath(this.path); debug(`Opening TCP socket with ${info.host}:${info.port}`); this.socketPort = new net.Socket(); this.socketPort.setNoDelay(true); this.socketPort.setKeepAlive(true, 15000); this.writer = new Writer(); this.writer.pipe(this.socketPort); this.parser = new Parser(); this.socketPort.pipe(this.parser); this.parser.on('parsed', this.onParsed); return new Promise((resolve, reject): void => { this.socketPort.on('connect', function() { debug('Socket connected'); }); // eslint-disable-next-line const self = this; this.socketPort.on('ready', async function() { debug('Socket ready'); self.initialized = true; resolve(); }); this.socketPort.once('close', this.onPortClose); this.socketPort.on('error', function () { debug('Socket error'); reject(new Error(`Error while opening socket`)); self.initialized = false; }); this.socketPort.connect(info.port, info.host); }); } public close(): Promise<void> { return new Promise((resolve, reject): void => { if (this.initialized) { if (this.portType === 'serial') { this.serialPort.flush((): void => { this.serialPort.close((error): void => { this.initialized = false; error == null ? resolve() : reject(new Error(`Error while closing serialport '${error}'`)); this.emit('close'); }); }); } else { this.socketPort.destroy(); resolve(); } } else { resolve(); this.emit('close'); } }); } public readParameterRequest(parameterId: number) : Promise<Command> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push read parameter request to queue. seqNr: ${seqNumber} paramId: ${parameterId}`); const ts = 0; const commandId = PARAM.PARAM.FrameType.ReadParameter; const req: Request = {commandId, parameterId, seqNumber, resolve, reject, ts}; queue.push(req); }); } public writeParameterRequest(parameterId: number, parameter: parameterT) : Promise<void> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push write parameter request to queue. seqNr: ${seqNumber} paramId: ${parameterId} parameter: ${parameter}`); const ts = 0; const commandId = PARAM.PARAM.FrameType.WriteParameter; const req: Request = {commandId, parameterId, parameter, seqNumber, resolve, reject, ts}; queue.push(req); }); } public readFirmwareVersionRequest() : Promise<number[]> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push read firmware version request to queue. seqNr: ${seqNumber}`); const ts = 0; const commandId = PARAM.PARAM.FrameType.ReadFirmwareVersion; const req: Request = {commandId, seqNumber, resolve, reject, ts}; queue.push(req); }); } private sendReadParameterRequest(parameterId: number, seqNumber: number) { /* command id, sequence number, 0, framelength(U16), payloadlength(U16), parameter id */ const requestFrame = [PARAM.PARAM.FrameType.ReadParameter, seqNumber, 0x00, 0x08, 0x00, 0x01, 0x00, parameterId]; if (parameterId === PARAM.PARAM.Network.NETWORK_KEY) { const requestFrame2= [PARAM.PARAM.FrameType.ReadParameter, seqNumber, 0x00, 0x09, 0x00, 0x02, 0x00, parameterId, 0x00]; this.sendRequest(requestFrame2); } else { this.sendRequest(requestFrame); } } private sendWriteParameterRequest(parameterId: number, value: parameterT, seqNumber: number) { /* command id, sequence number, 0, framelength(U16), payloadlength(U16), parameter id, pameter */ let parameterLength = 0; if (parameterId === PARAM.PARAM.STK.Endpoint) { let arrayParameterValue = value as number[]; parameterLength = arrayParameterValue.length; } else { parameterLength = this.getLengthOfParameter(parameterId); } //debug("SEND WRITE_PARAMETER Request - parameter id: " + parameterId + " value: " + value.toString(16) + " length: " + parameterLength); const payloadLength = 1 + parameterLength; const frameLength = 7 + payloadLength; const fLength1 = frameLength & 0xff; const fLength2 = frameLength >> 8; const pLength1 = payloadLength & 0xff; const pLength2 = payloadLength >> 8; if (parameterId === PARAM.PARAM.Network.NETWORK_KEY) { const requestFrame2= [PARAM.PARAM.FrameType.WriteParameter, seqNumber, 0x00, 0x19, 0x00, 0x12, 0x00, parameterId, 0x00].concat(value); this.sendRequest(requestFrame2); } else { const requestframe = [PARAM.PARAM.FrameType.WriteParameter, seqNumber, 0x00, fLength1, fLength2, pLength1, pLength2, parameterId].concat(this.parameterBuffer(value, parameterLength)); this.sendRequest(requestframe); } } private getLengthOfParameter(parameterId: number) : number { switch (parameterId) { case 9: case 16: case 21: case 28: case 33: case 36: return 1; case 5: case 7: case 34: return 2; case 10: case 38: return 4; case 1: case 8: case 11: case 14: return 8; case 24: case 25: return 16; default: return 0; } } private parameterBuffer(parameter: parameterT, parameterLength: number) : Array<number> { const paramArray = new Array(); if (typeof parameter === 'number') { // for parameter <= 4 Byte if (parameterLength > 4) throw new Error("parameter to big for type number"); for (let i = 0; i < parameterLength; i++) { paramArray[i] = (parameter >> (8 * i)) & 0xff; } } else { return parameter.reverse(); } return paramArray; } private sendReadFirmwareVersionRequest(seqNumber: number) { /* command id, sequence number, 0, framelength(U16) */ const requestFrame = [PARAM.PARAM.FrameType.ReadFirmwareVersion, seqNumber, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00]; //debug(requestFrame); this.sendRequest(requestFrame); } private sendReadDeviceStateRequest(seqNumber: number) { /* command id, sequence number, 0, framelength(U16) */ const requestFrame = [PARAM.PARAM.FrameType.ReadDeviceState, seqNumber, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00]; this.sendRequest(requestFrame); } private sendRequest(buffer: number[]) { const crc = this.calcCrc(Buffer.from(buffer)); const frame = Buffer.from(buffer.concat([crc[0], crc[1]])); const slipframe = slip.encode(frame); if ( this.portType === 'serial') { this.serialPort.write(slipframe, function(err) { if (err) { debug("Error writing serial Port: " + err.message); } }); } else { this.socketPort.write(slipframe, function(err) { if (err) { debug("Error writing socket Port: " + err.message); } }); } } private processQueue() { if (queue.length === 0) { return; } if (busyQueue.length > 0) { return; } const req: Request = queue.shift(); req.ts = Date.now(); switch (req.commandId) { case PARAM.PARAM.FrameType.ReadParameter: debug(`send read parameter request from queue. seqNr: ${req.seqNumber} paramId: ${req.parameterId}`); this.sendReadParameterRequest(req.parameterId, req.seqNumber); break; case PARAM.PARAM.FrameType.WriteParameter: debug(`send write parameter request from queue. seqNr: ${req.seqNumber} paramId: ${req.parameterId} param: ${req.parameter}`); this.sendWriteParameterRequest(req.parameterId, req.parameter, req.seqNumber); break; case PARAM.PARAM.FrameType.ReadFirmwareVersion: debug(`send read firmware version request from queue. seqNr: ${req.seqNumber}`); this.sendReadFirmwareVersionRequest(req.seqNumber); break; case PARAM.PARAM.FrameType.ReadDeviceState: debug(`send read device state from queue. seqNr: ${req.seqNumber}`); this.sendReadDeviceStateRequest(req.seqNumber); break; case PARAM.PARAM.NetworkState.CHANGE_NETWORK_STATE: debug(`send change network state request from queue. seqNr: ${req.seqNumber}`); this.sendChangeNetworkStateRequest(req.seqNumber, req.networkState); break; default: throw new Error("process queue - unknown command id"); break; } busyQueue.push(req); } private async processBusyQueue() { let i = busyQueue.length; while (i--) { const req: Request = busyQueue[i]; const now = Date.now(); if ((now - req.ts) > 10000) { debug(`Timeout for request - CMD: 0x${req.commandId.toString(16)} seqNr: ${req.seqNumber}`); //remove from busyQueue busyQueue.splice(i, 1); timeoutCounter++; // after a timeout the timeoutcounter will be reset after 1 min. If another timeout happen then the timeoutcounter // will not be reset clearTimeout(this.timeoutResetTimeout); this.timeoutResetTimeout = null; this.resetTimeoutCounterAfter1min(); req.reject("TIMEOUT"); if (timeoutCounter >= 2) { timeoutCounter = 0; debug("too many timeouts - restart serial connecion"); if (this.serialPort?.isOpen) { this.serialPort.close(); } if (this.socketPort) { this.socketPort.destroy(); } await this.open(); } } } } public changeNetworkStateRequest(networkState: number) : Promise<void> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push change network state request to apsQueue. seqNr: ${seqNumber}`); const ts = 0; const commandId = PARAM.PARAM.NetworkState.CHANGE_NETWORK_STATE; const req: Request = {commandId, networkState, seqNumber, resolve, reject, ts}; queue.push(req); }); } private sendChangeNetworkStateRequest(seqNumber: number, networkState: number) { const requestFrame = [PARAM.PARAM.NetworkState.CHANGE_NETWORK_STATE, seqNumber, 0x00, 0x06, 0x00, networkState]; this.sendRequest(requestFrame); } private deviceStateRequest() { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`DEVICE_STATE Request - seqNr: ${seqNumber}`); const ts = 0; const commandId = PARAM.PARAM.FrameType.ReadDeviceState; const req: Request = {commandId, seqNumber, resolve, reject, ts}; queue.push(req); }); } private async checkDeviceStatus(currentDeviceStatus: number) { const networkState = currentDeviceStatus & 0x03; this.apsDataConfirm = (currentDeviceStatus >> 2) & 0x01; this.apsDataIndication = (currentDeviceStatus >> 3) & 0x01; this.configChanged = (currentDeviceStatus >> 4) & 0x01; this.apsRequestFreeSlots = (currentDeviceStatus >> 5) & 0x01; debug("networkstate: " + networkState + " apsDataConfirm: " + this.apsDataConfirm + " apsDataIndication: " + this.apsDataIndication + " configChanged: " + this.configChanged + " apsRequestFreeSlots: " + this.apsRequestFreeSlots); } private async handleDeviceStatus() { if (this.apsDataConfirm === 1) { try { debug("query aps data confirm"); this.apsDataConfirm = 0; const x = await this.querySendDataStateRequest(); } catch (e) { if (e.status === 5) { this.apsDataConfirm = 0; } } } if (this.apsDataIndication === 1) { try { debug("query aps data indication"); this.apsDataIndication = 0; const x = await this.readReceivedDataRequest(); } catch (e) { if (e.status === 5) { this.apsDataIndication = 0; } } } if (this.configChanged === 1) { // when network settings changed } } // DATA_IND private readReceivedDataRequest() : Promise<void> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push read received data request to apsQueue. seqNr: ${seqNumber}`); const ts = 0; const commandId = PARAM.PARAM.APS.DATA_INDICATION; const req: Request = {commandId, seqNumber, resolve, reject, ts}; apsConfirmIndQueue.push(req); }); } // DATA_REQ public enqueueSendDataRequest(request: ApsDataRequest) : Promise<void | ReceivedDataResponse> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push enqueue send data request to apsQueue. seqNr: ${seqNumber}`); const ts = 0; const requestId = request.requestId; const commandId = PARAM.PARAM.APS.DATA_REQUEST; const req: Request = {commandId, seqNumber, request, resolve, reject, ts}; apsQueue.push(req); }); } // DATA_CONF private querySendDataStateRequest() : Promise<void> { const seqNumber = this.nextSeqNumber(); return new Promise((resolve, reject): void => { //debug(`push query send data state request to apsQueue. seqNr: ${seqNumber}`); const ts = 0; const commandId = PARAM.PARAM.APS.DATA_CONFIRM; const req: Request = {commandId, seqNumber, resolve, reject, ts}; apsConfirmIndQueue.push(req); }); } private async processApsQueue() { if (apsQueue.length === 0) { return; } if (this.apsRequestFreeSlots !== 1) { debug("no free slots. Delay sending of APS Request"); await this.sleep(1000); return; } const req: Request = apsQueue.shift(); req.ts = Date.now(); switch (req.commandId) { case PARAM.PARAM.APS.DATA_REQUEST: if (readyToSend === false) { // wait until last request was confirmed or given time elapsed debug("delay sending of APS Request"); apsQueue.unshift(req); break; } else { disableRTS(); enableRtsTimeout = setTimeout(function(){enableRTS();}, this.READY_TO_SEND_TIMEOUT); apsBusyQueue.push(req); this.sendEnqueueSendDataRequest(req.request, req.seqNumber); break; } default: throw new Error("process APS queue - unknown command id"); break; } } private async processApsConfirmIndQueue() { if (apsConfirmIndQueue.length === 0) { return; } const req: Request = apsConfirmIndQueue.shift(); req.ts = Date.now(); apsBusyQueue.push(req); switch (req.commandId) { case PARAM.PARAM.APS.DATA_INDICATION: //debug(`read received data request. seqNr: ${req.seqNumber}`); if (this.DELAY === 0) { this.sendReadReceivedDataRequest(req.seqNumber); } else { await this.sendReadReceivedDataRequest(req.seqNumber); } break; case PARAM.PARAM.APS.DATA_CONFIRM: //debug(`query send data state request. seqNr: ${req.seqNumber}`); if (this.DELAY === 0) { this.sendQueryDataStateRequest(req.seqNumber); } else { await this.sendQueryDataStateRequest(req.seqNumber); } break; default: throw new Error("process APS Confirm/Ind queue - unknown command id"); break; } } private sendQueryDataStateRequest(seqNumber: number) { debug(`DATA_CONFIRM - sending data state request - SeqNr. ${seqNumber}`); const requestFrame = [PARAM.PARAM.APS.DATA_CONFIRM, seqNumber, 0x00, 0x07, 0x00, 0x00, 0x00]; this.sendRequest(requestFrame); } private sendReadReceivedDataRequest(seqNumber: number) { debug(`DATA_INDICATION - sending read data request - SeqNr. ${seqNumber}`); // payloadlength = 0, flag = none const requestFrame = [PARAM.PARAM.APS.DATA_INDICATION, seqNumber, 0x00, 0x08, 0x00, 0x01, 0x00, 0x01]; this.sendRequest(requestFrame); } private sendEnqueueSendDataRequest(request: ApsDataRequest, seqNumber: number) { const payloadLength = 12 + ((request.destAddrMode === 0x01) ? 2 : (request.destAddrMode === 0x02) ? 3 : 9) + request.asduLength; const frameLength = 7 + payloadLength; const cid1 = request.clusterId & 0xff; const cid2 = (request.clusterId >> 8) & 0xff; const asdul1 = request.asduLength & 0xff; const asdul2 = (request.asduLength >> 8) & 0xff; let destArray: Array<number> = []; let dest = ""; if (request.destAddr16 != null) { destArray[0] = request.destAddr16 & 0xff; destArray[1] = (request.destAddr16 >> 8) & 0xff; dest = request.destAddr16.toString(16); } if (request.destAddr64 != null) { dest = request.destAddr64; destArray = this.macAddrStringToArray(request.destAddr64); } if (request.destEndpoint != null) { destArray.push(request.destEndpoint); dest += " EP:"; dest += request.destEndpoint; } debug(`DATA_REQUEST - destAddr: 0x${dest} SeqNr. ${seqNumber} request id: ${request.requestId}`); const requestFrame = [PARAM.PARAM.APS.DATA_REQUEST, seqNumber, 0x00, frameLength & 0xff, (frameLength >> 8) & 0xff, payloadLength & 0xff, (payloadLength >> 8) & 0xff, request.requestId, 0x00, request.destAddrMode].concat( destArray).concat([request.profileId & 0xff, (request.profileId >> 8) & 0xff, cid1, cid2, request.srcEndpoint, asdul1, asdul2]).concat( request.asduPayload).concat([request.txOptions, request.radius]); this.sendRequest(requestFrame); } private processApsBusyQueue() { let i = apsBusyQueue.length; while (i--) { const req: Request = apsBusyQueue[i]; const now = Date.now(); let timeout = 60000; if (req.request != null && req.request.timeout != null) { timeout = req.request.timeout * 1000; // seconds * 1000 = milliseconds } if ((now - req.ts) > timeout) { debug(`Timeout for aps request CMD: 0x${req.commandId.toString(16)} seq: ${req.seqNumber}`); //remove from busyQueue apsBusyQueue.splice(i, 1); req.reject("APS TIMEOUT"); } } } private calcCrc(buffer: Uint8Array) : Array<number>{ let crc = 0; for (let i=0; i < buffer.length; i++) { crc += buffer[i]; } const crc0 = (~crc + 1) & 0xff; const crc1 = ((~crc + 1) >> 8) & 0xff; return [crc0, crc1]; } public macAddrStringToArray(addr: string) : Array<number>{ if (addr.indexOf("0x") === 0) { addr = addr.slice(2, addr.length); } if (addr.length < 16) { for (let l = 0; l < (16 - addr.length); l++) { addr = "0" + addr; } } let result: number[] = new Array<number>(); let y = 0; for (let i = 0; i < 8; i++) { result[i] = parseInt(addr.substr(y,2), 16); y += 2; } const reverse = result.reverse(); return reverse; } public macAddrArrayToString(addr: Array<number>) : string{ if (addr.length != 8) { throw new Error("invalid array length for MAC address: " + addr.length); } let result: string = "0x"; let char = ''; let i = 8; while (i--) { char = addr[i].toString(16); if (char.length < 2) { char = "0" + char; } result += char; } return result; } /** * generalArrayToString result is not reversed! */ public generalArrayToString(key: Array<number>, length: number) : string{ let result: string = "0x"; let char = ''; let i = 0; while (i < length) { char = key[i].toString(16); if (char.length < 2) { char = "0" + char; } result += char; i++; } return result; } private nextSeqNumber(): number { this.seqNumber++; if (this.seqNumber > 254) { this.seqNumber = 1; } return this.seqNumber; } private onParsed(frame: Uint8Array): void { this.emit('rxFrame', frame); } private sleep(ms: number) : Promise<void>{ return new Promise(resolve => setTimeout(resolve, ms)); } private resetTimeoutCounterAfter1min() { if (this.timeoutResetTimeout === null) { this.timeoutResetTimeout = setTimeout(() => { timeoutCounter = 0; this.timeoutResetTimeout = null; }, 60000); } } } export default Driver;
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const taskOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'task', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a task', }, { name: 'Delete', value: 'delete', description: 'Delete a task', }, { name: 'Get', value: 'get', description: 'Get a task', }, { name: 'Get All', value: 'getAll', description: 'Get all tasks', }, { name: 'Update', value: 'update', description: 'Update a task', }, ], default: 'create', description: 'Operation to perform', }, ]; export const taskFields: INodeProperties[] = [ // ---------------------------------------- // task: create // ---------------------------------------- { displayName: 'Project ID', name: 'projectId', description: 'ID of the project to which the task belongs', type: 'options', typeOptions: { loadOptionsMethod: 'getProjects', }, required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'create', ], }, }, }, { displayName: 'Subject', name: 'subject', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'create', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'task', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Assigned To', name: 'assigned_to', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUsers', }, default: '', description: 'ID of the user to whom the task is assigned', }, { displayName: 'Blocked Note', name: 'blocked_note', type: 'string', default: '', description: 'Reason why the task is blocked. Requires "Is Blocked" toggle to be enabled', }, { displayName: 'Description', name: 'description', type: 'string', default: '', }, { displayName: 'Is Blocked', name: 'is_blocked', type: 'boolean', default: false, description: 'Whether the task is blocked', }, { displayName: 'Milestone (Sprint)', name: 'milestone', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getMilestones', }, default: '', description: 'ID of the milestone of the task', }, { displayName: 'Status', name: 'status', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTaskStatuses', }, default: '', description: 'ID of the status of the task', }, { displayName: 'Tags', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'Taskboard Order', name: 'taskboard_order', type: 'number', default: 1, description: 'Order of the task in the taskboard', typeOptions: { minValue: 1, }, }, { displayName: 'User Story', name: 'user_story', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUserStories', }, default: '', description: 'ID of the user story of the task', }, { displayName: 'User Story Order', name: 'us_order', type: 'number', default: 1, description: 'Order of the task in the user story', typeOptions: { minValue: 1, }, }, ], }, // ---------------------------------------- // task: delete // ---------------------------------------- { displayName: 'Task ID', name: 'taskId', description: 'ID of the task to delete', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'delete', ], }, }, }, // ---------------------------------------- // task: get // ---------------------------------------- { displayName: 'Task ID', name: 'taskId', description: 'ID of the task to retrieve', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'get', ], }, }, }, // ---------------------------------------- // task: getAll // ---------------------------------------- { displayName: 'Project ID', name: 'projectId', description: 'ID of the project to which the task belongs', type: 'options', typeOptions: { loadOptionsMethod: 'getProjects', }, required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], }, }, }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', default: false, description: 'Whether to return all results or only up to a given limit', displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], }, }, }, { displayName: 'Limit', name: 'limit', type: 'number', default: 50, description: 'How many results to return', typeOptions: { minValue: 1, }, displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, }, { displayName: 'Filters', name: 'filters', type: 'collection', placeholder: 'Add Filter', displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], }, }, default: {}, options: [ { displayName: 'Assigned To', name: 'assigned_to', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUsers', }, default: '', description: 'ID of the user whom the task is assigned to', }, { displayName: 'Is Closed', name: 'statusIsClosed', description: 'Whether the task is closed', type: 'boolean', default: false, }, { displayName: 'Milestone (Sprint)', name: 'milestone', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getMilestones', }, default: '', description: 'ID of the milestone of the task', }, { displayName: 'Owner', name: 'owner', description: 'ID of the owner of the task', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUsers', }, default: '', }, { displayName: 'Role', name: 'role', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getRoles', }, default: '', }, { displayName: 'Status', name: 'status', description: 'ID of the status of the task', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTaskStatuses', }, default: '', }, { displayName: 'Tags', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'User Story', name: 'userStory', description: 'ID of the user story to which the task belongs', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUserStories', }, default: '', }, ], }, // ---------------------------------------- // task: update // ---------------------------------------- { displayName: 'Project ID', name: 'projectId', description: 'ID of the project to set the task to', type: 'options', typeOptions: { loadOptionsMethod: 'getProjects', }, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'update', ], }, }, }, { displayName: 'Task ID', name: 'taskId', description: 'ID of the task to update', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'task', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Assigned To', name: 'assigned_to', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTypes', }, default: '', description: 'ID of the user to assign the task to', }, { displayName: 'Blocked Note', name: 'blocked_note', type: 'string', default: '', description: 'Reason why the task is blocked. Requires "Is Blocked" toggle to be enabled', }, { displayName: 'Description', name: 'description', type: 'string', default: '', }, { displayName: 'Is Blocked', name: 'is_blocked', type: 'boolean', default: false, description: 'Whether the task is blocked', }, { displayName: 'Milestone (Sprint)', name: 'milestone', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getMilestones', }, default: '', description: 'ID of the milestone of the task', }, { displayName: 'Status', name: 'status', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTaskStatuses', }, default: '', description: 'ID of the status of the task', }, { displayName: 'Subject', name: 'subject', type: 'string', default: '', }, { displayName: 'User Story', name: 'user_story', type: 'options', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getUserStories', }, default: '', description: 'ID of the user story of the task', }, { displayName: 'User Story Order', name: 'us_order', type: 'number', default: 1, typeOptions: { minValue: 1, }, description: 'Order of the task in the user story', }, { displayName: 'Tags', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsDependsOn: [ 'projectId', ], loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'Taskboard Order', name: 'taskboard_order', type: 'number', default: 1, typeOptions: { minValue: 1, }, description: 'Order of the task in the taskboard', }, ], }, ];
the_stack
import * as svgCaptcha from 'svg-captcha' import { User, Notification, Logger, Organization, Repository } from '../models' import router from './router' import { Model } from 'sequelize-typescript' import Pagination from './utils/pagination' import { QueryInclude } from '../models' import { Op } from 'sequelize' import MailService from '../service/mail' import * as md5 from 'md5' import { isLoggedIn } from './base' import { AccessUtils } from './utils/access' import { COMMON_ERROR_RES } from './utils/const' import * as moment from 'moment' import RedisService, { CACHE_KEY, DEFAULT_CACHE_VAL } from '../service/redis' router.get('/app/get', async (ctx, next) => { let data: any = {} let query = ctx.query let hooks: any = { user: User, } for (let name in hooks) { if (!query[name]) continue data[name] = await hooks[name].findByPk(query[name], { attributes: { exclude: [] } }) } ctx.body = { data: Object.assign({}, ctx.body && ctx.body.data, data), } return next() }) router.get('/account/count', async (ctx) => { ctx.body = { data: await User.count(), } }) router.get('/account/list', isLoggedIn, async (ctx) => { // if (!AccessUtils.isAdmin(ctx.session.id)) { // ctx.body = COMMON_ERROR_RES.ACCESS_DENY // return // } let where = {} let { name } = ctx.query if (name) { Object.assign(where, { [Op.or]: [ { fullname: { [Op.like]: `%${name}%` } }, { email: name }, ], }) } let options = { where } let total = await User.count(options) let limit = Math.min(+ctx.query.limit ?? 10, 100) let pagination = new Pagination(total, ctx.query.cursor || 1, limit) ctx.body = { data: await User.findAll({ ...options, ...{ attributes: ['id', 'fullname', 'email'], offset: pagination.start, limit: pagination.limit, order: [['id', 'DESC']], } }), pagination: pagination } }) router.get('/account/info', async (ctx) => { ctx.body = { data: ctx.session.id ? await User.findByPk(ctx.session.id, { attributes: QueryInclude.User.attributes }) : undefined } }) router.post('/account/login', async (ctx) => { let { email, password, captcha } = ctx.request.body let result, errMsg if (process.env.TEST_MODE !== 'true' && (!captcha || !ctx.session.captcha || captcha.trim().toLowerCase() !== ctx.session.captcha.toLowerCase())) { errMsg = '错误的验证码' } else { result = await User.findOne({ attributes: QueryInclude.User.attributes, where: { email, password: md5(md5(password)) }, }) if (result) { ctx.session.id = result.id ctx.session.fullname = result.fullname ctx.session.email = result.email let app: any = ctx.app app.counter.users[result.fullname] = true } else { errMsg = '账号或密码错误' } } ctx.body = { data: result ? result : { errMsg }, } }) router.get('/captcha_data', ctx => { ctx.body = { data: JSON.stringify(ctx.session) } }) router.get('/account/logout', async (ctx) => { let app: any = ctx.app delete app.counter.users[ctx.session.email] let id = ctx.session.id Object.assign(ctx.session, { id: undefined, fullname: undefined, email: undefined }) ctx.body = { data: await { id }, } }) router.post('/account/register', async (ctx) => { let { fullname, email, password } = ctx.request.body let exists = await User.findAll({ where: { email }, }) if (exists && exists.length) { ctx.body = { data: { isOk: false, errMsg: '该邮件已被注册,请更换再试。', }, } return } // login automatically after register let result = await User.create({ fullname, email, password: md5(md5(password)) }) if (result) { ctx.session.id = result.id ctx.session.fullname = result.fullname ctx.session.email = result.email let app: any = ctx.app app.counter.users[result.fullname] = true } ctx.body = { data: { id: result.id, fullname: result.fullname, email: result.email, }, } }) router.post('/account/update', async (ctx) => { const { password } = ctx.request.body let errMsg = '' let isOk = false if (!ctx.session || !ctx.session.id) { errMsg = '登陆超时' } else if (password.length < 6) { errMsg = '密码长度过短' } else { const user = await User.findByPk(ctx.session.id) user.password = md5(md5(password)) await user.save() isOk = true } ctx.body = { data: { isOk, errMsg } } }) router.get('/account/remove', isLoggedIn, async (ctx) => { if (!AccessUtils.isAdmin(ctx.session.id)) { ctx.body = COMMON_ERROR_RES.ACCESS_DENY return } if (process.env.TEST_MODE === 'true') { ctx.body = { data: await User.destroy({ where: { id: ctx.query.id }, }), } } else { ctx.body = { data: { isOk: false, errMsg: 'access forbidden', }, } } }) // TODO 2.3 账户设置 router.get('/account/setting', async (ctx) => { ctx.body = { data: {}, } }) router.post('/account/setting', async (ctx) => { ctx.body = { data: {}, } }) router.post('/account/fetchUserSettings', isLoggedIn, async (ctx) => { const keys: CACHE_KEY[] = ctx.request.body.keys if (!keys || !keys.length) { ctx.body = { isOk: false, errMsg: 'error' } return } const data: { [key: string]: string } = {} for (const key of keys) { data[key] = await RedisService.getCache(key, ctx.session.id) || DEFAULT_CACHE_VAL[key] } ctx.body = { isOk: true, data, } }) router.post('/account/updateUserSetting/:key', isLoggedIn, async (ctx) => { const key: CACHE_KEY = ctx.params.key as CACHE_KEY const value: string = ctx.request.body.value await RedisService.setCache(key, value, ctx.session.id, 10 * 365 * 24 * 60 * 60) ctx.body = { isOk: true, } }) // TODO 2.3 账户通知 let NOTIFICATION_EXCLUDE_ATTRIBUTES: any = [] router.get('/account/notification/list', async (ctx) => { let total = await Notification.count() let pagination = new Pagination(total, ctx.query.cursor || 1, ctx.query.limit || 10) ctx.body = { data: await Notification.findAll({ attributes: { exclude: NOTIFICATION_EXCLUDE_ATTRIBUTES }, offset: pagination.start, limit: pagination.limit, order: [ ['id', 'DESC'], ], }), pagination: pagination, } }) router.get('/account/notification/unreaded', async (ctx) => { ctx.body = { data: [], } }) router.post('/account/notification/unreaded', async (ctx) => { ctx.body = { data: 0, } }) router.post('/account/notification/read', async (ctx) => { ctx.body = { data: 0, } }) // TODO 2.3 账户日志 router.get('/account/logger', async (ctx) => { if (!ctx.session.id) { ctx.body = { data: { isOk: false, errMsg: 'not login' } } return } let auth = await User.findByPk(ctx.session.id) let repositories: Model<Repository>[] = [...(<Model<Repository>[]>await auth.$get('ownedRepositories')), ...(<Model<Repository>[]>await auth.$get('joinedRepositories'))] let organizations: Model<Organization>[] = [...(<Model<Organization>[]>await auth.$get('ownedOrganizations')), ...(<Model<Organization>[]>await auth.$get('joinedOrganizations'))] let where: any = { [Op.or]: [ { userId: ctx.session.id }, { repositoryId: repositories.map(item => item.id) }, { organizationId: organizations.map(item => item.id) }, ], } let total = await Logger.count({ where }) let pagination = new Pagination(total, ctx.query.cursor || 1, ctx.query.limit || 100) let logs = await Logger.findAll({ where, attributes: {}, include: [ Object.assign({}, QueryInclude.Creator, { required: false }), QueryInclude.User, QueryInclude.Organization, QueryInclude.Repository, QueryInclude.Module, QueryInclude.Interface, ], offset: pagination.start, limit: pagination.limit, order: [ ['id', 'DESC'], ], paranoid: false, } as any) ctx.body = { data: logs, pagination, } }) router.get('/captcha', async (ctx) => { const captcha = svgCaptcha.create() ctx.session.captcha = captcha.text ctx.set('Content-Type', 'image/svg+xml') ctx.body = captcha.data }) router.get('/worker', async (ctx) => { ctx.body = process.env.NODE_APP_INSTANCE || 'NOT FOUND' }) router.post('/account/reset', async (ctx) => { const email = ctx.request.body.email const password = ctx.request.body.password if (password && ctx.session.resetCode && password === ctx.session.resetCode + '') { const newPassword = String(Math.floor(Math.random() * 99999999)) const user = await User.findOne({ where: { email } }) if (!user) { ctx.body = { data: { isOk: false, errMsg: '您的邮箱没被注册过。', } } return } user.password = md5(md5(newPassword)) await user.save() ctx.body = { data: { isOk: true, data: newPassword, } } } else { const resetCode = ctx.session.resetCode = Math.floor(Math.random() * 999999) MailService.send(email, 'RAP重置账户验证码', `您的验证码为:${resetCode}`) ctx.body = { data: { isOk: true, } } } }) router.post('/account/findpwd', async (ctx) => { let { email, captcha } = ctx.request.body let user, errMsg if (process.env.TEST_MODE !== 'true' && (!captcha || !ctx.session.captcha || captcha.trim().toLowerCase() !== ctx.session.captcha.toLowerCase())) { errMsg = '错误的验证码' } else { user = await User.findOne({ attributes: QueryInclude.User.attributes, where: { email }, }) if (user) { // 截取ID最后两位*日期字符串 作为返回链接的过期校验 let idstr = user.id.toString() let timeCode = (parseInt(moment().add(60, 'minutes').format('YYMMDDHHmmss')) * parseInt(idstr.substr(idstr.length - 2))).toString() let token = md5(user.email + user.id + timeCode + String(Math.floor(Math.random() * 99999999))) await RedisService.setCache(CACHE_KEY.PWDRESETTOKEN_GET, token, user.id) let link = `${ctx.headers.origin}/account/resetpwd?code=${timeCode}&email=${email}&token=${token}` let content = MailService.mailFindpwdTemp.replace(/{=EMAIL=}/g, user.email).replace(/{=URL=}/g, link).replace(/{=NAME=}/g, user.fullname) MailService.send(email, "RAP2:重新设置您的密码", content) } else { errMsg = '账号不存在' } } ctx.body = { data: !errMsg ? { isOk: true } : { isOk: false, errMsg } } }) router.post('/account/findpwd/reset', async (ctx) => { let { code, email, captcha, token, password } = ctx.request.body let user, errMsg if (!code || !email || !captcha || !token || !password) { errMsg = '参数错误' } else if (password.length < 6) { errMsg = '密码长度过短' } else if (process.env.TEST_MODE !== 'true' && (!captcha || !ctx.session.captcha || captcha.trim().toLowerCase() !== ctx.session.captcha.toLowerCase())) { errMsg = '错误的验证码' } else { user = await User.findOne({ attributes: QueryInclude.User.attributes, where: { email }, }) if (!user) { errMsg = '您的邮箱没被注册过,或用户已被锁定' } else { const tokenCache = await RedisService.getCache(CACHE_KEY.PWDRESETTOKEN_GET, user.id) if (!tokenCache || tokenCache !== token) { errMsg = "参数错误" } else { RedisService.delCache(CACHE_KEY.PWDRESETTOKEN_GET, user.id) let idstr = user.id.toString() let timespan = parseInt(code) / parseInt(idstr.substr(idstr.length - 2)) if (timespan < parseInt(moment().format('YYMMDDHHmmss'))) { errMsg = "此链接已超时,请重新发送重置密码邮件" } else { user.password = md5(md5(password)) await user.save() } } } } ctx.body = { data: !errMsg ? { isOk: true } : { isOk: false, errMsg } } }) router.post('/account/updateAccount', async ctx => { try { const { password, fullname } = ctx.request.body as { password: string, fullname: string } if (!ctx.session?.id) { throw new Error('需先登录才能操作') } const user = await User.findByPk(ctx.session.id) if (password) { user.password = md5(md5(password)) } if (fullname) { user.fullname = fullname } await user.save() ctx.body = { isOk: true } } catch (ex) { ctx.body = { isOk: false, errMsg: ex.message, } } })
the_stack
"use strict"; /* * Copyright (C) 1998-2018 by Northwoods Software Corporation. All Rights Reserved. */ import * as go from "../release/go"; export class ExtendedBrush extends go.Brush { private _UNITS: Array<string>; constructor(type: string) { super(); if (arguments.length === 0) go.Brush.call(this); else go.Brush.call(this, type); (<any>ExtendedBrush)['parse'] = (<any>ExtendedBrush)['stringify'] = this._UNITS = ["px", "pt", "pc", "in", "cm", "mm"]; } /** * This static method can be used to read in a {@link Brush} from a string that was produced by {@link ExtendedBrush.stringify}. * @param {string} str * @return {Brush} */ public parse(str: string, w: number, h: number): go.Brush { if (str.indexOf("linear") !== -1) { return this._parseLinearGradientCSS(str, w, h); } else if (str.indexOf("radial") !== -1) { return this._parseRadialGradientCSS(str, w, h); } else if (go.Brush.isValidColor(str)) { var b = new go.Brush(go.Brush.Solid); b.color = str; return b; } else { //only works with image urls right now //TODO deal with Canvas elements var b = new go.Brush(go.Brush.Pattern); var image = document.createElement("img"); image.src = str; b.pattern = image; return b; } }; /** * This static method can be used to write out a {@link Brush} as a string that can be read by {@link Brush.parse}. * @param {Brush} val * @return {string} */ public stringify(val: go.Brush): string { if (!(val instanceof go.Brush)) throw new Error("ExtendedBrush.stringify requires a Brush argument, not: " + val); var str = ""; if (val.type === go.Brush.Solid) { return val.color; } else if (val.type === go.Brush.Linear) { str = "linear-gradient("; var ang = this._angleBetweenSpots(val); if (isNaN(ang)) ang = 180; str += ang + "deg"; str += this._convertStopsToCSS(val); str += ")"; } else if (val.type === go.Brush.Radial) { str = "radial-gradient("; if (val.endRadius) str += Math.round(val.endRadius) + "px "; if ((val as any).ellipseHeight) str += Math.round((val as any).ellipseHeight) + "px "; //temp until we figure out canvas scaling str += "at "; str += val.start.x * 100 + "% "; str += val.start.y * 100 + "% "; str += this._convertStopsToCSS(val); str += ")"; } else if (val.type === go.Brush.Pattern) { if (val.pattern) str = val.pattern.getAttribute("src"); } return str; } private _convertStopsToCSS(brush: go.Brush): string { var it = brush.colorStops.iterator; var str = ""; while (it.next()) { str += ", " + it.value + " " + it.key * 100 + "%"; } return str; }; private _lengthToPX(length: number, unit: string): number { var pxPerInch = 96; var cmPerInch = 2.54; switch (unit) { case "px": return length; case "pt": return length * 3 / 4; case "pc": return length * 9; case "in": return length * pxPerInch; case "cm": return length * pxPerInch / cmPerInch; case "mm": return length * pxPerInch / (cmPerInch * 10); default: return NaN; } }; private _pxToPercent(px: number, l?: number, w?: number, angle?: number): number { angle = parseFloat(angle.toString()); if (angle % 180 === 0) return px / l; angle *= Math.PI / 180; return px / (Math.abs(w * Math.sin(angle)) + Math.abs(l * Math.cos(angle))); } private _parseLinearGradientCSS(cssstring: string, w: number, h: number) { var css = (cssstring.toString()).match(/\((.*)\)/g); if (css === null) throw new Error("Invalid CSS Linear Gradient: " + cssstring); var cssString = css[0]; //removes outer parentheses cssString = cssString.substring(1, css.length - 1); //splits string into components at commas not within parentheses //css = css.split(/,+(?![^\(]*\))/g); css = cssString.split(/,(?![^\(]*\))/g); css[0] = css[0].trim(); var isValidColor = go.Brush.isValidColor(css[0].split(/\s(?![^\(]*\))/g)[0]); if (isValidColor) { // if the first param isn't a color, it's a CSS <angle> // or a malformed attempt at a color, such as "blavk" // if input's good it works for now, TODO improve later. css.splice(0, 0, "180deg"); } //standardizes any angle measurement or direction to degrees css[0] = this._linearGradientAngleToDegrees(css[0], w, h).toString(); var angle = parseFloat(css[0]) + 180; //adjusts for css having 180 as the default start point //converts color/percent strings to array objects var colors = this._createColorStopArray(css); /* by now we have the list of color stops, and the computed angle. The color stops need to be bound in a map that the Brush class will like, and the angle needs to be computed with the dimensions of the thing that the brush is coloring, in order to supply the brush with it's start and end spots. once that stuff is computed, stick them on the Brush 'b', below, and return it. */ var b = new go.Brush(go.Brush.Linear); var spots = this._calculateLinearGradientSpots(angle, w, h); b.start = spots[0]; b.end = spots[1]; for (var i = 0; i < colors.length; i++) { b.addColorStop(colors[i].position, colors[i].color); } return b; } //parses array of gradient parameters to color stop array. used by both gradient parsers private _createColorStopArray(css: RegExpMatchArray) { var colors: Array<any> = []; for (var i = 1; i < css.length; i++) { css[i] = css[i].trim(); var arr: Array<number>; var arrStr = css[i].split(/\s+(?![^\(]*\))/g);//whitespace not within parentheses var value; var obj = {}; if (!go.Brush.isValidColor(arrStr[0])) { throw new Error("Invalid CSS Color in Linear Gradient: " + arr[0] + " in " + css); } if (arr[1] !== undefined) { // we have a measurement var unit = arrStr[1].match(/[^\d.]+/g)[0]; if (this._UNITS.indexOf(unit) !== -1) { arr[1] = parseFloat(arrStr[1]); // bites off anything not a number: "90px" -> 90.0 ... "px" is still stored in unit var len = this._lengthToPX(arr[1], unit); (<any>obj)["position"] = this._pxToPercent(len); //obj["position"] = this._pxToPercent(len, w, h, angle); } else if (unit === "%") { (<any>obj)["position"] = arr[1] / 100; } else { throw new Error("Invalid Linear Gradient Unit: " + unit + " in " + css); } } else { (<any>obj)["position"] = NaN; } (<any>obj)["color"] = arr[0]; colors[i - 1] = obj; } if (isNaN(colors[0].position)) colors[0].position = 0; if (isNaN(colors[colors.length - 1].position)) colors[colors.length - 1].position = 1; //recursively fills in missing percents in the array this._fixLinearGradientPositions(colors); return colors; } private _fixLinearGradientPositions(arr: any[], start?: number, end?: number) { if (start === undefined) start = 0; if (end === undefined) end = arr.length; while (start < end - 1 && !isNaN(arr[start + 1].position)) start++; if (start === end - 1) return; var tempEnd = start + 1; while (tempEnd < end && isNaN(arr[tempEnd].position)) tempEnd++; var step = (arr[tempEnd].position - arr[start].position) / (tempEnd - start); for (var i = 1; i < tempEnd - start; i++) { arr[i + start].position = Math.round((arr[start].position + i * step) * 1000) / 1000; } if (tempEnd < end - 1) { this._fixLinearGradientPositions(arr, tempEnd, end); } }; private _calculateLinearGradientSpots(angle: number, w: number, h: number): go.Spot[] { angle = parseFloat(angle.toString()); angle = (angle % 360 + 360) % 360; if (angle === 90) return [new go.Spot(0, 0, w, h / 2), new go.Spot(0, 0, 0, h / 2)]; if (angle === 270) return [new go.Spot(0, 0, 0, h / 2), new go.Spot(0, 0, w, h / 2)]; var tempAngle = -Math.abs((angle % 180) - 90) + 90; 90 var tan = Math.tan(tempAngle * Math.PI / 180); var x = (h * tan - w) * 0.5 / (tan * tan + 1); var y = x * tan; if (angle >= 90 && angle <= 270) y = h - y; if (angle < 180) x = w + x; else x = -x; return ([new go.Spot(0, 0, x, y), new go.Spot(0, 0, w - x, h - y)]); }; private _applyLinearGradientSpots(angle: number, w: number, h: number, brush: go.Brush): go.Brush { var spots = this._calculateLinearGradientSpots(angle, w, h); brush.start = spots[0]; brush.end = spots[1]; return brush; } private _linearGradientAngleToDegrees(string: string, w: number, h: number): number { //true if there is a "to " at the start of the first parameter, //indicating that a direction was specified rather than angle var isNumericalInput = string.indexOf("to ") < 0; //0s without units still accepted var digit_arr = string.match(/\d/g); var zero_arr = string.match(/0/g); if (zero_arr !== null && (digit_arr.length === zero_arr.length)) return 0; if (isNumericalInput) { var stringArr = string.match(/[^a-z]+|\D+/g); switch (string[1]) { case ("deg"): return parseFloat(stringArr[0]); case ("rad"): return parseFloat(stringArr[0]) * 180 / Math.PI; case ("turn"): return parseFloat(stringArr[0]) * 360; case ("grad"): return parseFloat(stringArr[0]) * 9 / 10; default: throw new Error("Invalid CSS Linear Gradient direction: " + string[1]); } } else { var direction = 0; if (string.indexOf("right") >= 0) direction = 90; else if (string.indexOf("left") >= 0) direction = -90; var sign = direction === 0 ? 0 : direction > 0 ? 1 : -1; //needed because Chrome/IE/Safari/Opera/Mosaic/Netscape don't support Math.sign() if (string.indexOf("top") >= 0) { direction -= sign * Math.atan(w / h) * 180 / Math.PI; } else if (string.indexOf("bottom") >= 0) { if (direction === 0) direction = 180; else direction += sign * Math.atan(w / h) * 180 / Math.PI } if (direction === 0 && string.indexOf("top") < 0) { throw new Error("Invalid CSS Linear Gradient direction: " + string); } return Math.round(direction); } }; private _angleBetweenSpots(brush: go.Brush): number { var start = brush.start; var end = brush.end; if (isNaN(start.x + start.y + end.x + end.y)) throw new Error("The brush does not have valid spots"); var x = end.offsetX - start.offsetX; var y = start.offsetY - end.offsetY; var angle = Math.atan((start.offsetX - end.offsetX) / (end.offsetY - start.offsetY)) * 180 / Math.PI; if (start.offsetY > end.offsetY) angle += 180; return (angle + 360) % 360; } private _parseRadialGradientCSS(css: string, w: number, h: number) { //removes browser specific tags var cssArr = css.match(/\((.*)\)/g); if (cssArr === null) { throw new Error("Invalid CSS Linear Gradient"); } css = cssArr[0]; css = css.substring(1, css.length - 1); //splits string into components at commas not within parenthesesd and removes whitespace cssArr = css.split(/,(?![^\(]*\))/g); cssArr[0] = cssArr[0].trim(); var isValidColor = go.Brush.isValidColor(css[0].split(" ")[0]); //default shape paramenters var radii = [w / 2, h / 2]; //stores two radii var center = new go.Spot(0.5, 0.5, 0, 0); //stores the center of the gradient //goes through all cases to set radii and center if (!isValidColor) { //parses only if there were intial parameters specified //could be only a partial shape/position specification var shapeArr = css[0]; //first specified parameter of gradient var shape = shapeArr.split("at") if (shape.length === 1) { center = new go.Spot(0.5, 0.5, 0, 0); //no center was specified, so it must be "at center"; } else if (shape.length === 2) { //assigns something to center. one must have been specified if length===2 center = this._parseCenter(shape[1], w, h); } else { throw new Error("invalid css radial gradient string"); } //uses center to calculate radii radii = this._parseShapeDescription(shape[0], w, h, center); } var colors = this._createColorStopArray(cssArr); // console.log("RADIAL: ", "\nCENTER: ", center, "\nRADII: ", radii, "\nCOLORS: ", colors); // assigns stops, center, and radii to a brush var b = new go.Brush(go.Brush.Radial); b.start = center; //concentric in CSS, so start and end are the same b.end = center; b.startRadius = 0; //css starts at 0 automatically b.endRadius = radii[0]; //end radius is the width of the ending shape //TEMP until we implement scaling the gradient in canvas (b as any).ellipseHeight = radii[1]; for (var i = 0; i < colors.length; i++) { b.addColorStop(colors[i].position, colors[i].color); } return b; } //parses a position string to determine where the radial gradient is centered private _parseCenter(str: string, w?: number, h?: number) { //h and w values are only needed if pixels are being used var arr: Array<number> = []; //stores the x and y coodinates str = str.trim(); var parts = str.split(/\s+/g); if (parts.length === 1) { arr = this._englishPositionToCoordinate(parts[0]); } else if (parts.length === 2) { var digits = str.match(/\d+/g); //if specified only with english, no percents/pixels, compute center if (digits === null) { arr = this._englishPositionToCoordinate(str); } else if (digits.length === 1) { //know one of the params are numbers //if the first param is a string, second is a number var num; var pos; if (parts[0].match(/\d+/g) === null) { pos = parts[0]; num = parts[1]; } else { //if second param is string and first is number pos = parts[1]; num = parts[0]; } num = this._parseLengthToPercent(num); //correctly assigns the width coordinate arr = this._englishPositionToCoordinate(pos); //overwrites height to the user specified value arr[1] = num; } else if (digits.length === 2) { //both the params are numbers arr[0] = this._parseLengthToPercent(parts[0], w); arr[1] = this._parseLengthToPercent(parts[1], h); } } else if (parts.length === 3) { //TODO must be two positions and a number //correct behavior here is not known, only works in IE. need to check css spec } else if (parts.length === 4) { switch (parts[0]) { case ("right"): arr[0] = 1 - this._parseLengthToPercent(arr[1].toString(), w); break; case ("left"): arr[0] = this._parseLengthToPercent(arr[1].toString(), w); break; default: throw new Error("invalid location keyword: " + parts[0]); } switch (parts[2]) { case ("top"): arr[0] = this._parseLengthToPercent(arr[3].toString(), h); case ("bottom"): arr[0] = 1 - this._parseLengthToPercent(arr[3].toString(), h); default: throw new Error("invalid location keyword: " + parts[2]); } } else { throw new Error("invalid CSS position description"); } return new go.Spot(arr[0], arr[1], 0, 0); } private _parseLengthToPercent(str: string, dimension?: number) { if (str.indexOf("%") < 0) {//if specified by a length unit return this._parseLengthToPX(str) / (dimension); } else { //if specified by percentage return parseFloat(str) / 100; } } private _parseLengthToPX(str: string, dimension?: go.Rect): number { var len = parseFloat(str.match(/\d+/g)[0]); var unit = str.match(/\D+/g)[0]; return this._lengthToPX(len, unit) } private _englishPositionToCoordinate(str: string) { var x = .5; var y = .5; if (str.indexOf("bottom") > -1) y = 1; else if (str.indexOf("top") > -1) y = 0; if (str.indexOf("left") > -1) x = 0; else if (str.indexOf("right") > -1) x = 1; return [x, y]; } //needs to return something at some point private _parseShapeDescription(str: string, w: number, h: number, center: go.Spot) { var x = center.x; var y = center.y; str = str.trim(); var split = str.split(" "); if (split === null) return [w / 2, h / 2]; if (split.length === 1) { //distance from center to farthest side horizontally and vertically var a = Math.abs(w / 2 - x * w) + w / 2; var b = Math.abs(h / 2 - y * h) + h / 2; if (str.indexOf("ellipse") > -1) { return [a * Math.sqrt(2), b * Math.sqrt(2)]; } else if (str.indexOf("circle") > -1) { var r = Math.sqrt(a * a + b * b); return [r, r]; } else { //must not contain explicit shape paramenters, only an extent, so parse that return this._parseExtentKeyword(str, w, h, center); } } else if (split.length === 2) { var digits = str.match(/\d+/g); if (digits === null) { //must be shape and extent return this._parseExtentKeyword(str, w, h, center); } else if (digits.length === 1) { //only valid description would be "circle" and a radius specified as a length, NOT a percentage if (split[0].indexOf("circle") > -1 && split[1].indexOf("%") < 0) { var r = this._parseLengthToPX(split[1]); return [r, r]; } else throw new Error("Invalid CSS shape description"); } else if (digits.length === 2) { //must both be ellipse radii return [this._parseLengthToPX(split[0]), this._parseLengthToPX(split[1])]; } else { throw new Error("Invalid CSS shape description"); } } else if (split.length === 3) { if (split[0] !== "ellipse") throw new Error("invalid CSS shape description"); return [this._parseLengthToPercent(split[1], w) * w, this._parseLengthToPercent(split[2], h) * h] } else { throw new Error("invalid CSS shape description"); } } private _parseExtentKeyword(str: string, w: number, h: number, center: go.Spot) { if (!str) return [w / 2, h / 2]; var x = center.x; var y = center.y; //distance from center to farthest side horizontally and vertically var a = Math.abs(w / 2 - x * w) + w / 2; var b = Math.abs(h / 2 - y * h) + h / 2; var split = str.split(" "); var extent; //stores the extent keyword var arr; //stores the radii to be returned if (split === null) throw new Error("invalid extent keyword"); else extent = split[split.length - 1]; //either a circle or an ellipse, nothing specified defaults to ellipse if (str.indexOf("circle") > -1) { switch (extent) { case ("closest-corner"): var r = Math.sqrt((w - a) * (w - a) + (h - b) * (h - b)); break; case ("farthest-corner"): var r = Math.sqrt(a * a + b * b); break; case ("closest-side"): var r = Math.min(w - a, h - b); break; case ("farthest-side"): var r = Math.max(a, b); break; default: throw new Error("invalid extent keyword: " + extent); } return [r, r] } else { //must be an ellipse switch (extent) { case ("closest-corner"): return [(w - a) * Math.sqrt(2), (h - b) * Math.sqrt(2)]; case ("farthest-corner"): return [a * Math.sqrt(2), b * Math.sqrt(2)]; case ("closest-side"): return [w - a, h - b]; case ("farthest-side"): return [a, b]; default: throw new Error("invalid extent keyword: " + extent); } } } private _makePaletteFromOneColor(color: string, number: number): any[] { var colorArr = this._RGB_to_Lab(this.CSSStringToRGB(color)); var arr = []; var inc = 100 / (number + 2); var numBelow = Math.floor(colorArr[0] / inc) - 1; for (var i = 1; i <= number; i++) { arr[i - 1] = go.Brush.lightenBy(color, inc * (i - numBelow) / 100); } return arr; }; private _makePaletteFromTwoColors(color1: string, color2: string, number: number): any[] { var color1Arr = this._RGB_to_Lab(this.CSSStringToRGB(color1)); var color2Arr = this._RGB_to_Lab(this.CSSStringToRGB(color2)); var arr = []; var deltaA = this._MAX_Lab_A - this._MIN_Lab_A; var deltaB = this._MAX_Lab_B - this._MIN_Lab_B; var btm = number - 1; var diffA = (color1Arr[1] - color2Arr[1]) / btm; var diffB = (color1Arr[2] - color2Arr[2]) / btm; var diffL = (color1Arr[0] - color2Arr[0]) / btm; for (var i = 0; i < number; i++) { var rgb = this._Lab_to_RGB([color2Arr[0] + i * diffL, color2Arr[1] + i * diffA, color2Arr[2] + i * diffB]); var css = this._RGBArrayToCSS(rgb); arr[i] = css; } return arr; } /** * Creates an array of valid equidistant colors. * @name ExtendedBrush#makeColorPalette * @param {string} color1 a valid color to be used as the basis for the color palette * @param {string=} color2 an additional color that will be used in conjunction with color1 * @param {number=} number the amount of colors to be generated, the default is 3 * @return {Array} */ /** @type {Array} */ public makeColorPalette(color1: any[], color2: string, number: number) { // make sure we have 1-3 parameters if (arguments.length < 1) { throw new Error('Please provide at least one color, and at most two color and a number'); } else if (arguments.length > 3) { throw new Error('Please provide no more than two colors, and an optional number argument'); } // we have 1-3 parameters, proceed // if no palette length is provided we give them a palette of length 3 var defaultPaletteLength = 3; // make sure that the first parameter is a string if (typeof color1 !== "string") throw new Error(color1 + " is not a string"); /* check to see if the last parameter is undefined. This is used later to see if the second parameter should be handled as a color string or as a number for the length of the palette */ var numundefined = number === undefined; /* This helper function will throw an error if the number passed into it is not real, and if it's not at least 1 */ var checkForNumberError = (number: number) => { if (typeof number !== "number" || isNaN(number) || number === Infinity || number < 1) throw new Error('Please provide a number greater than or equal to one, not: ' + number); } if (arguments.length === 1) { // we only have a legal color string, so return a palette with the defaultPaletteLength return this._makePaletteFromOneColor(color1, defaultPaletteLength); } // by now we have a color, and any something else, be it another color, a number, or both if (typeof color2 === "string") { if (numundefined) { // we only have 2 colors, so make a palette of them with the defaultPaletteLenght return this._makePaletteFromTwoColors(color1, color2, defaultPaletteLength); } else { checkForNumberError(number); // we have two strings and a valid number, make a palette with those return this._makePaletteFromTwoColors(color1, color2, number); } } else { if (typeof color2 === "number") { if (numundefined) { number = color2; checkForNumberError(number); // make a palette with one color and the specified length if (number === 1) { color1 = this.CSSStringToRGB(color1); color1.splice(3, 1); var x = [this._RGBArrayToCSS(color1)]; return x; } return this._makePaletteFromOneColor(color1, number); } else { throw new Error("Please provide only only one number"); } } else { throw new Error('Please provide either a color string or a number'); } } } private _sharedTempCtx: CanvasRenderingContext2D | null = null; public CSSStringToRGB(CSSColorString: string): any[] { if (!go.Brush.isValidColor(CSSColorString)) throw new Error("Invalid CSS Color String: " + CSSColorString); var canvas = this._sharedTempCtx; if (canvas === null) canvas = this._sharedTempCtx = document.createElement('canvas').getContext('2d') as CanvasRenderingContext2D; canvas.clearRect(0, 0, 1, 1); canvas.fillStyle = CSSColorString; canvas.fillRect(0, 0, 1, 1); var data = canvas.getImageData(0, 0, 1, 1).data; var arr = []; for (var i = 0; i < data.length; i++) arr.push(data[i]); return arr; }; private _RGBArrayToCSS(RGB_Array: Array<number>): string { if (RGB_Array.length === 3) var str = "rgb("; else if (RGB_Array.length === 4) var str = "rgba("; else throw new Error("invalid RGB or RGBa array: " + RGB_Array); for (var i = 0; i < RGB_Array.length; i++) { str += RGB_Array[i] + (i !== RGB_Array.length - 1 ? ", " : ""); } return str + ")"; }; private _MIN_Lab_A: number = -93; private _MAX_Lab_A: number = 92; private _MIN_Lab_B: number = -114; private _MAX_Lab_B: number = 92; private _RGB_to_Lab(rgb: string[]) { return this._XYZtoLab((this._RGBtoXYZ(rgb))); }; private _Lab_to_RGB(Lab: number[]) { return this._XYZtoRGB(this._LabtoXYZ(Lab)); }; private _sRGBtoXYZMatrix = [ [0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041] ]; private _XYZtosRGBMatrix = [ [3.2404542, -1.5371385, -0.4985314], [-0.9692660, 1.8760108, 0.0415560], [0.0556434, -0.2040259, 1.0572252] ]; private _rowMultiplication(row: number[], colorArray: string[]) { var sum = 0; for (var i = 0; i < colorArray.length; i++) { sum += row[i] * parseFloat(colorArray[i]); } return sum; }; private _RGB_XYZ_Inverse_Companding(RGB_value: number): number { RGB_value /= 255; if (RGB_value <= .04045) { return RGB_value / 12.92; } return Math.pow(((RGB_value + .055) / 1.055), 2.4); }; private _XYZ_RGB_Companding(XYZ_value: number): number { if (XYZ_value * 12.92 <= .04045) return XYZ_value * 12.92; return 1.055 * Math.pow(XYZ_value, .416667) - .055; }; private _RGBtoXYZ(rgb: string[]): string[] { rgb.splice(3, 1); // remove alpha value the Canvas gives us var applied = []; var i; for (i = 0; i < rgb.length; i++) rgb[i] = this._RGB_XYZ_Inverse_Companding(parseFloat(rgb[i])).toString(); for (i = 0; i < rgb.length; i++) applied[i] = this._rowMultiplication(this._sRGBtoXYZMatrix[i], rgb).toString(); return applied; }; private _XYZtoRGB(xyz: string[]) { var applied = []; var i; for (i = 0; i < xyz.length; i++) applied[i] = this._rowMultiplication(this._XYZtosRGBMatrix[i], xyz); for (i = 0; i < xyz.length; i++) { applied[i] = this._XYZ_RGB_Companding(applied[i]) * 255; if (applied[i] < 0) applied[i] = 0; applied[i] *= 100; applied[i] = Math.round(applied[i]); applied[i] /= 100; applied[i] = Math.floor(applied[i]); if (applied[i] > 255) applied[i] = 255; if (applied[i] < 0) applied[i] = 0; } return applied; }; private _Lab_EPSILON: number = 216 / 24389; private _Lab_KAPPA: number = 24389 / 27; private _XYZ_Lab_HelperFunction(inputXYZ: number): number { if (inputXYZ > this._Lab_EPSILON) { return Math.pow(inputXYZ, 1 / 3); } return (this._Lab_KAPPA * inputXYZ + 16) / 116; }; private _XYZtoLab(xyz: string[]): number[] { var Lab = []; var y = this._XYZ_Lab_HelperFunction(parseFloat(xyz[1])); Lab[0] = 116 * y - 16; Lab[1] = 500 * (this._XYZ_Lab_HelperFunction(parseFloat(xyz[0])) - y); Lab[2] = 200 * (y - this._XYZ_Lab_HelperFunction(parseFloat(xyz[2]))); return Lab; }; private _Lab_XYZ_HelperFunction(inputLab: number): number { var inputCbd = inputLab * inputLab * inputLab; if (inputCbd > this._Lab_EPSILON) return inputCbd; return (116 * inputLab - 16) / this._Lab_KAPPA; }; private _LabtoXYZ(Lab: Array<number>): Array<string> { var working_arr = []; working_arr[1] = (Lab[0] + 16) / 116; working_arr[0] = (Lab[1] / 500) + working_arr[1]; working_arr[2] = (-Lab[2] / 200) + working_arr[1]; var XYZ = []; XYZ[1] = this._Lab_XYZ_HelperFunction(working_arr[1]).toString(); XYZ[0] = this._Lab_XYZ_HelperFunction(working_arr[0]).toString(); XYZ[2] = this._Lab_XYZ_HelperFunction(working_arr[2]).toString(); return XYZ; }; }
the_stack
import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import './shared_style.js'; import './strings.m.js'; import './item.js'; import {CrA11yAnnouncerElement} from 'chrome://resources/cr_elements/cr_a11y_announcer/cr_a11y_announcer.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {isMac} from 'chrome://resources/js/cr.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {ListPropertyUpdateMixin, ListPropertyUpdateMixinInterface} from 'chrome://resources/js/list_property_update_mixin.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js'; import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import {afterNextRender, html, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {deselectItems, selectAll, selectItem, updateAnchor} from './actions.js'; import {BookmarksCommandManagerElement} from './command_manager.js'; import {MenuSource} from './constants.js'; import {BookmarksItemElement} from './item.js'; import {StoreClientMixin} from './store_client_mixin.js'; import {OpenCommandMenuDetail} from './types.js'; import {canReorderChildren, getDisplayedList} from './util.js'; const BookmarksListElementBase = StoreClientMixin(ListPropertyUpdateMixin(PolymerElement)); export interface BookmarksListElement { $: { list: IronListElement, message: HTMLDivElement, } } export class BookmarksListElement extends BookmarksListElementBase { static get is() { return 'bookmarks-list'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * A list of item ids wrapped in an Object. This is necessary because * iron-list is unable to distinguish focusing index 6 from focusing id * '6' so the item we supply to iron-list needs to be non-index-like. */ displayedList_: { type: Array, value() { // Use an empty list during initialization so that the databinding to // hide #list takes effect. return []; }, }, displayedIds_: { type: Array, observer: 'onDisplayedIdsChanged_', }, searchTerm_: { type: String, observer: 'onDisplayedListSourceChange_', }, selectedFolder_: { type: String, observer: 'onDisplayedListSourceChange_', }, selectedItems_: Object, }; } private displayedList_: {id: string}[]; private displayedIds_: string[]; private eventTracker_: EventTracker = new EventTracker(); private searchTerm_: string; private selectedFolder_: string; private selectedItems_: Set<string>; private boundOnHighlightItems_: (p1: CustomEvent) => void; ready() { super.ready(); this.addEventListener('click', () => this.deselectItems_()); this.addEventListener('contextmenu', e => this.onContextMenu_(e)); this.addEventListener( 'open-command-menu', e => this.onOpenCommandMenu_(e as CustomEvent<OpenCommandMenuDetail>)); } connectedCallback() { super.connectedCallback(); const list = this.$.list; list.scrollTarget = this; this.watch('displayedIds_', function(state) { return getDisplayedList(state); }); this.watch('searchTerm_', state => state.search.term); this.watch('selectedFolder_', state => state.selectedFolder); this.watch('selectedItems_', state => state.selection.items); this.updateFromStore(); this.$.list.addEventListener( 'keydown', this.onItemKeydown_.bind(this), true); this.eventTracker_.add( document, 'highlight-items', e => this.onHighlightItems_(e as CustomEvent<string[]>)); this.eventTracker_.add( document, 'import-began', () => this.onImportBegan_()); this.eventTracker_.add( document, 'import-ended', () => this.onImportEnded_()); } disconnectedCallback() { super.disconnectedCallback(); this.eventTracker_.remove(document, 'highlight-items'); } getDropTarget(): HTMLElement { return this.$.message; } /** * Updates `displayedList_` using splices to be equivalent to `newValue`. This * allows the iron-list to delete sublists of items which preserves scroll and * focus on incremental update. */ private async onDisplayedIdsChanged_(newValue: string[], oldValue: string[]) { const updatedList = newValue.map(id => ({id: id})); let skipFocus = false; let selectIndex = -1; if (this.matches(':focus-within')) { if (this.selectedItems_.size > 0) { const selectedId = Array.from(this.selectedItems_)[0]; skipFocus = newValue.some(id => id === selectedId); selectIndex = this.displayedList_.findIndex(({id}) => selectedId === id); } if (selectIndex === -1 && updatedList.length > 0) { selectIndex = 0; } else { selectIndex = Math.min(selectIndex, updatedList.length - 1); } } this.updateList( 'displayedList_', item => (item as {id: string}).id, updatedList); // Trigger a layout of the iron list. Otherwise some elements may render // as blank entries. See https://crbug.com/848683 this.$.list.dispatchEvent( new CustomEvent('iron-resize', {bubbles: true, composed: true})); const label = await PluralStringProxyImpl.getInstance().getPluralString( 'listChanged', this.displayedList_.length); CrA11yAnnouncerElement.getInstance().announce(label); if (!skipFocus && selectIndex > -1) { setTimeout(() => { this.$.list.focusItem(selectIndex); // Focus menu button so 'Undo' is only one tab stop away on delete. const item = getDeepActiveElement(); if (item) { (item as BookmarksItemElement).focusMenuButton(); } }); } } private onDisplayedListSourceChange_() { this.scrollTop = 0; } /** * Scroll the list so that |itemId| is visible, if it is not already. */ private scrollToId_(itemId: string) { const index = this.displayedIds_.indexOf(itemId); const list = this.$.list; if (index >= 0 && index < list.firstVisibleIndex || index > list.lastVisibleIndex) { list.scrollToIndex(index); } } private emptyListMessage_(): string { let emptyListMessage = 'noSearchResults'; if (!this.searchTerm_) { emptyListMessage = canReorderChildren(this.getState(), this.getState().selectedFolder) ? 'emptyList' : 'emptyUnmodifiableList'; } return loadTimeData.getString(emptyListMessage); } private isEmptyList_(): boolean { return this.displayedList_.length === 0; } private deselectItems_() { this.dispatch(deselectItems()); } private getIndexForItemElement_(el: HTMLElement): number { return (this.$.list.modelForElement(el) as unknown as {index: number}) .index; } private onOpenCommandMenu_(e: CustomEvent<{source: MenuSource}>) { // If the item is not visible, scroll to it before rendering the menu. if (e.detail.source === MenuSource.ITEM) { this.scrollToId_((e.composedPath()[0] as BookmarksItemElement).itemId); } } /** * Highlight a list of items by selecting them, scrolling them into view and * focusing the first item. */ private onHighlightItems_(e: CustomEvent<string[]>) { // Ensure that we only select items which are actually being displayed. // This should only matter if an unrelated update to the bookmark model // happens with the perfect timing to end up in a tracked batch update. const toHighlight = e.detail.filter((item) => this.displayedIds_.indexOf(item) !== -1); if (toHighlight.length <= 0) { return; } const leadId = toHighlight[0]!; this.dispatch(selectAll(toHighlight, this.getState(), leadId)); // Allow iron-list time to render additions to the list. microTask.run(() => { this.scrollToId_(leadId); const leadIndex = this.displayedIds_.indexOf(leadId); assert(leadIndex !== -1); this.$.list.focusItem(leadIndex); }); } private onImportBegan_() { CrA11yAnnouncerElement.getInstance().announce( loadTimeData.getString('importBegan')); } private onImportEnded_() { CrA11yAnnouncerElement.getInstance().announce( loadTimeData.getString('importEnded')); } private onItemKeydown_(e: KeyboardEvent) { let handled = true; const list = this.$.list; let focusMoved = false; let focusedIndex = this.getIndexForItemElement_(e.target as HTMLElement); const oldFocusedIndex = focusedIndex; const cursorModifier = isMac ? e.metaKey : e.ctrlKey; if (e.key === 'ArrowUp') { focusedIndex--; focusMoved = true; } else if (e.key === 'ArrowDown') { focusedIndex++; focusMoved = true; e.preventDefault(); } else if (e.key === 'Home') { focusedIndex = 0; focusMoved = true; } else if (e.key === 'End') { focusedIndex = list.items!.length - 1; focusMoved = true; } else if (e.key === ' ' && cursorModifier) { this.dispatch( selectItem(this.displayedIds_[focusedIndex]!, this.getState(), { clear: false, range: false, toggle: true, })); } else { handled = false; } if (focusMoved) { focusedIndex = Math.min(list.items!.length - 1, Math.max(0, focusedIndex)); list.focusItem(focusedIndex); if (cursorModifier && !e.shiftKey) { this.dispatch(updateAnchor(this.displayedIds_[focusedIndex]!)); } else { // If shift-selecting with no anchor, use the old focus index. if (e.shiftKey && this.getState().selection.anchor === null) { this.dispatch(updateAnchor(this.displayedIds_[oldFocusedIndex]!)); } // If the focus moved from something other than a Ctrl + move event, // update the selection. const config = { clear: !cursorModifier, range: e.shiftKey, toggle: false, }; this.dispatch(selectItem( this.displayedIds_[focusedIndex]!, this.getState(), config)); } } // Prevent the iron-list from changing focus on enter. if (e.key === 'Enter') { if ((e.composedPath()[0] as HTMLElement).tagName === 'CR-ICON-BUTTON') { return; } if (e.composedPath()[0] instanceof HTMLButtonElement) { handled = true; } } if (!handled) { handled = BookmarksCommandManagerElement.getInstance().handleKeyEvent( e, this.getState().selection.items); } if (handled) { e.stopPropagation(); } } private onContextMenu_(e: MouseEvent) { e.preventDefault(); this.deselectItems_(); this.dispatchEvent(new CustomEvent('open-command-menu', { bubbles: true, composed: true, detail: { x: e.clientX, y: e.clientY, source: MenuSource.LIST, } })); } private getAriaRowindex_(index: number): number { return index + 1; } private getAriaSelected_(id: string): boolean { return this.selectedItems_.has(id); } } customElements.define(BookmarksListElement.is, BookmarksListElement);
the_stack
import { XMLBuilderCreateOptions, ExpandObject, XMLBuilder, WriterOptions, XMLBuilderOptions, DefaultBuilderOptions, DocumentWithSettings, XMLBuilderOptionKeys, XMLWriterOptions, JSONWriterOptions, ObjectWriterOptions, XMLSerializedAsObject, XMLSerializedAsObjectArray, MapWriterOptions, XMLSerializedAsMap, XMLSerializedAsMapArray, XMLSerializedValue, YAMLWriterOptions } from '../interfaces' import { isPlainObject, applyDefaults, isArray } from '@oozcitak/util' import { Node, Document } from '@oozcitak/dom/lib/dom/interfaces' import { Guard } from '@oozcitak/dom/lib/util' import { XMLBuilderImpl } from '.' import { createDocument } from '../builder/dom' /** * Wraps a DOM node for use with XML builder with default options. * * @param node - DOM node * * @returns an XML builder */ export function builder(node: Node): XMLBuilder /** * Wraps an array of DOM nodes for use with XML builder with default options. * * @param nodes - an array of DOM nodes * * @returns an array of XML builders */ export function builder(nodes: Node[]): XMLBuilder[] /** * Wraps a DOM node for use with XML builder with the given options. * * @param options - builder options * @param node - DOM node * * @returns an XML builder */ export function builder(options: XMLBuilderCreateOptions, node: Node): XMLBuilder /** * Wraps an array of DOM nodes for use with XML builder with the given options. * * @param options - builder options * @param nodes - an array of DOM nodes * * @returns an array of XML builders */ export function builder(options: XMLBuilderCreateOptions, nodes: Node[]): XMLBuilder[] /** @inheritdoc */ export function builder(p1: XMLBuilderCreateOptions | Node | Node[], p2?: Node | Node[]): XMLBuilder | XMLBuilder[] { const options = formatBuilderOptions(isXMLBuilderCreateOptions(p1) ? p1 : DefaultBuilderOptions) const nodes = Guard.isNode(p1) || isArray(p1) ? p1 : p2 if (nodes === undefined) { throw new Error("Invalid arguments.") } if (isArray(nodes)) { const builders: XMLBuilder[] = [] for (let i = 0; i < nodes.length; i++) { const builder = new XMLBuilderImpl(nodes[i]) builder.set(options) builders.push(builder) } return builders } else { const builder = new XMLBuilderImpl(nodes) builder.set(options) return builder } } /** * Creates an XML document without any child nodes. * * @returns document node */ export function create(): XMLBuilder /** * Creates an XML document without any child nodes with the given options. * * @param options - builder options * * @returns document node */ export function create(options: XMLBuilderCreateOptions): XMLBuilder /** * Creates an XML document by parsing the given `contents`. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * * @returns document node */ export function create(contents: string | ExpandObject): XMLBuilder /** * Creates an XML document. * * @param options - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * * @returns document node */ export function create(options: XMLBuilderCreateOptions, contents: string | ExpandObject): XMLBuilder /** @inheritdoc */ export function create(p1?: XMLBuilderCreateOptions | string | ExpandObject, p2?: string | ExpandObject): XMLBuilder { const options = formatBuilderOptions(p1 === undefined || isXMLBuilderCreateOptions(p1) ? p1 : DefaultBuilderOptions) const contents: string | ExpandObject | undefined = isXMLBuilderCreateOptions(p1) ? p2 : p1 const doc = createDocument() setOptions(doc, options) const builder = new XMLBuilderImpl(doc) if (contents !== undefined) { // parse contents builder.ele(contents as any) } return builder } /** * Creates a new document fragment without any child nodes. * * @returns document fragment node */ export function fragment(): XMLBuilder /** * Creates a new document fragment with the given options. * * @param options - builder options * * @returns document fragment node */ export function fragment(options: XMLBuilderCreateOptions): XMLBuilder /** * Creates a new document fragment by parsing the given `contents`. * * @param contents - a string containing an XML fragment in either XML or JSON * format or a JS object representing nodes to insert * * @returns document fragment node */ export function fragment(contents: string | ExpandObject): XMLBuilder /** * Creates a new document fragment. * * @param options - builder options * @param contents - a string containing an XML fragment in either XML or JSON * format or a JS object representing nodes to insert * * @returns document fragment node */ export function fragment(options: XMLBuilderCreateOptions, contents: string | ExpandObject): XMLBuilder /** @inheritdoc */ export function fragment(p1?: XMLBuilderCreateOptions | string | ExpandObject, p2?: string | ExpandObject): XMLBuilder { const options = formatBuilderOptions(p1 === undefined || isXMLBuilderCreateOptions(p1) ? p1 : DefaultBuilderOptions) const contents: string | ExpandObject | undefined = isXMLBuilderCreateOptions(p1) ? p2 : p1 const doc = createDocument() setOptions(doc, options, true) const builder = new XMLBuilderImpl(doc.createDocumentFragment()) if (contents !== undefined) { // parse contents builder.ele(contents as any) } return builder } /** * Parses an XML document with the default options and converts it to an XML * document string with the default writer options. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * * @returns document node */ export function convert(contents: string | ExpandObject): string /** * Parses an XML document with the given options and converts it to an XML * document string with the default writer options. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject): string /** * Parses an XML document with the default options and converts it an XML * document string. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(contents: string | ExpandObject, convertOptions: XMLWriterOptions): string /** * Parses an XML document with the default options and converts it a JSON string. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(contents: string | ExpandObject, convertOptions: JSONWriterOptions): string /** * Parses an XML document with the default options and converts it a YAML string. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(contents: string | ExpandObject, convertOptions: YAMLWriterOptions): string /** * Parses an XML document with the default options and converts it to its object * representation. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(contents: string | ExpandObject, convertOptions: ObjectWriterOptions): XMLSerializedAsObject | XMLSerializedAsObjectArray /** * Parses an XML document with the default options and converts it to its object * representation using ES6 maps. * * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(contents: string | ExpandObject, convertOptions: MapWriterOptions): XMLSerializedAsMap | XMLSerializedAsMapArray /** * Parses an XML document with the given options and converts it to an XML * document string. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: XMLWriterOptions): string /** * Parses an XML document with the given options and converts it to a JSON * string. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: JSONWriterOptions): string /** * Parses an XML document with the given options and converts it to a YAML * string. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: YAMLWriterOptions): string /** * Parses an XML document with the given options and converts it to its object * representation. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: ObjectWriterOptions): XMLSerializedAsObject | XMLSerializedAsObjectArray /** * Parses an XML document with the given options and converts it to its object * representation using ES6 maps. * * @param builderOptions - builder options * @param contents - a string containing an XML document in either XML or JSON * format or a JS object representing nodes to insert * @param convertOptions - convert options * * @returns document node */ export function convert(builderOptions: XMLBuilderCreateOptions, contents: string | ExpandObject, convertOptions: MapWriterOptions): XMLSerializedAsMap | XMLSerializedAsMapArray /** @inheritdoc */ export function convert(p1: XMLBuilderCreateOptions | string | ExpandObject, p2?: string | ExpandObject | WriterOptions, p3?: WriterOptions): XMLSerializedValue { let builderOptions: XMLBuilderCreateOptions let contents: string | ExpandObject let convertOptions: WriterOptions | undefined if (isXMLBuilderCreateOptions(p1) && p2 !== undefined) { builderOptions = p1 contents = p2 convertOptions = p3 } else { builderOptions = DefaultBuilderOptions contents = p1 convertOptions = p2 as WriterOptions || undefined } return create(builderOptions, contents).end(convertOptions as any) } function isXMLBuilderCreateOptions(obj: any): obj is XMLBuilderCreateOptions { if (!isPlainObject(obj)) return false for (const key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(key)) { if (!XMLBuilderOptionKeys.has(key)) return false } } return true } function formatBuilderOptions(createOptions: XMLBuilderCreateOptions = {}) { const options = applyDefaults(createOptions, DefaultBuilderOptions) as XMLBuilderOptions if (options.convert.att.length === 0 || options.convert.ins.length === 0 || options.convert.text.length === 0 || options.convert.cdata.length === 0 || options.convert.comment.length === 0) { throw new Error("JS object converter strings cannot be zero length.") } return options } function setOptions(doc: Document, options: XMLBuilderOptions, isFragment?: boolean): void { const docWithSettings = doc as DocumentWithSettings docWithSettings._xmlBuilderOptions = options docWithSettings._isFragment = isFragment }
the_stack
import { CodeListing } from "code_listing/code_listing"; let codeListing; beforeEach(() => { // Mock MathJax window.MathJax = {} as MathJaxObject; // Mock typeset function of MathJax window.MathJax.typeset = () => ""; document.body.innerHTML = ` <a href="#" data-bs-toggle="tab">Code <span class="badge" id="badge_code"></span></a> <div class="code-table" data-submission-id="54"> <div id="feedback-table-options" class="feedback-table-options"> <button class="btn btn-text" id="add_global_annotation">Annotatie toevoegen</button> <span class="flex-spacer"></span> <span class="diff-switch-buttons switch-buttons hide" id="annotations_toggles"> <span id="diff-switch-prefix">Annotaties</span> <div class="btn-group btn-toggle" role="group" aria-label="Annotaties" data-bs-toggle="buttons"> <button class="annotation-toggle active" id="show_all_annotations"></button> <button class="annotation-toggle" id="show_only_errors"></button> <button class="annotation-toggle" id="hide_all_annotations"></button> </div> </span> </div> <div id="feedback-table-global-annotations"> <div id="feedback-table-global-annotations-list"></div> </div> <div class="code-listing-container"> <table class="code-listing highlighter-rouge"> <tbody> <tr id="line-1" class="lineno"> <td class="rouge-gutter gl"><pre>1</pre></td> <td class="rouge-code"><pre>print(5 + 6)</pre></td> </tr> <tr id="line-2" class="lineno"> <td class="rouge-gutter gl"><pre>2</pre></td> <td class="rouge-code"><pre>print(6 + 3)</pre></td> </tr> <tr id="line-3" class="lineno"> <td class="rouge-gutter gl"><pre>1</pre></td> <td class="rouge-code"><pre>print(9 + 15)</pre></td> </tr> </tbody> </table> </div> </div>`; codeListing = new CodeListing(54, "print(5 + 6)\nprint(6 + 3)\nprint(9 + 15)\n", 3); }); test("create feedback table with default settings", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "warning" }, { "text": "Value could be assigned", "row": 1, "type": "warning" }, { "text": "Value could be assigned", "row": 2, "type": "warning" }, ]); expect(document.querySelectorAll(".annotation").length).toBe(3); }); test("html in annotations should be escaped", () => { codeListing.addMachineAnnotations([{ "text": "<b>test</b>", "row": 0, "type": "warning" }]); expect(document.querySelector(".annotation .annotation-text").textContent).toBe("<b>test</b>"); }); test("feedback table should support more than 1 annotation per row (first and last row)", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "warning" }, { "text": "Value could be assigned", "row": 0, "type": "warning" }, { "text": "Value could be assigned", "row": 1, "type": "warning" }, { "text": "Value could be assigned", "row": 1, "type": "warning" }, { "text": "Value could be assigned", "row": 2, "type": "warning" }, { "text": "Value could be assigned", "row": 2, "type": "warning" }, ]); expect(document.querySelectorAll(".annotation").length).toBe(6); }); test("annotation types should be transmitted into the view", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 1, "type": "warning" }, { "text": "Division by zero", "row": 2, "type": "error" }, ]); expect(document.querySelectorAll(".annotation.info").length).toBe(1); expect(document.querySelectorAll(".annotation.warning").length).toBe(1); expect(document.querySelectorAll(".annotation.error").length).toBe(1); }); test("line highlighting", () => { codeListing.highlightLine(1); expect(document.querySelectorAll(".lineno.marked").length).toBe(1); codeListing.highlightLine(2); expect(document.querySelectorAll(".lineno.marked").length).toBe(2); codeListing.highlightLine(2); expect(document.querySelectorAll(".lineno.marked").length).toBe(2); codeListing.clearHighlights(); expect(document.querySelectorAll(".lineno.marked").length).toBe(0); }); test("dots only for non-shown messages and only the worst", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 0, "type": "warning" }, { "text": "Division by zero", "row": 0, "type": "error" }, ]); codeListing.hideAnnotations(); // Dot on line 1 should be shown. expect(document.querySelectorAll(".dot").length).toBe(1); expect(document.querySelectorAll(".dot.hide").length).toBe(0); // Type of the dot should be error. expect(document.querySelectorAll(".dot.dot-error").length).toBe(1); }); test("dots not visible when all annotations are shown", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 0, "type": "warning" }, { "text": "Division by zero", "row": 0, "type": "error" }, ]); codeListing.showAnnotations(); // 1 dot that should not be visible. expect(document.querySelectorAll(".dot").length).toBe(1); expect(document.querySelectorAll(".dot.hide").length).toBe(1); }); test("only warning dot visible when in compressed error mode", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 0, "type": "warning" }, { "text": "Division by zero", "row": 0, "type": "error" }, ]); codeListing.hideAnnotations(true); expect(document.querySelectorAll(".dot").length).toBe(1); expect(document.querySelectorAll(".dot.dot-error").length).toBe(0); expect(document.querySelectorAll(".dot.dot-warning").length).toBe(1); // Simulating user switching codeListing.showAnnotations(); codeListing.hideAnnotations(); expect(document.querySelectorAll(".dot").length).toBe(1); expect(document.querySelectorAll(".dot.dot-error").length).toBe(1); }); test("no double dots", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 0, "type": "info" }, { "text": "Division by zero", "row": 0, "type": "info" }, ]); expect(document.querySelectorAll(".dot").length).toBe(1); codeListing.showAnnotations(); expect(document.querySelectorAll(".dot.dot-info:not(.hide)").length).toBe(0); expect(document.querySelectorAll(".dot.dot-warning:not(.hide)").length).toBe(0); expect(document.querySelectorAll(".dot.dot-error:not(.hide)").length).toBe(0); codeListing.hideAnnotations(true); expect(document.querySelectorAll(".dot.dot-info:not(.hide)").length).toBe(1); expect(document.querySelectorAll(".dot.dot-warning:not(.hide)").length).toBe(0); expect(document.querySelectorAll(".dot.dot-error:not(.hide)").length).toBe(0); codeListing.hideAnnotations(); expect(document.querySelectorAll(".dot.dot-info:not(.hide)").length).toBe(1); expect(document.querySelectorAll(".dot.dot-warning:not(.hide)").length).toBe(0); expect(document.querySelectorAll(".dot.dot-error:not(.hide)").length).toBe(0); }); test("correct buttons & elements are hidden and unhidden", () => { codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "info" }, { "text": "Float transformed into int", "row": 0, "type": "info" }, { "text": "Division by zero", "row": 0, "type": "info" }, ]); expect(document.querySelectorAll("#feedback-table-options.hide").length).toBe(0); expect(document.querySelectorAll("#feedback-table-options:not(.hide)").length).toBe(1); expect(document.querySelectorAll("#show_only_errors.hide").length).toBe(1); expect(document.querySelectorAll("#show_only_errors:not(.hide)").length).toBe(0); codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "error" }, { "text": "Float transformed into int", "row": 0, "type": "error" }, { "text": "Division by zero", "row": 0, "type": "error" }, ]); expect(document.querySelectorAll("#feedback-table-options.hide").length).toBe(0); expect(document.querySelectorAll("#feedback-table-options:not(.hide)").length).toBe(1); expect(document.querySelectorAll("#show_only_errors.hide").length).toBe(0); expect(document.querySelectorAll("#show_only_errors:not(.hide)").length).toBe(1); }); test("annotations should be transmitted into view", () => { codeListing.addUserAnnotation({ "id": 1, "line_nr": 1, "annotation_text": "This could be shorter", "markdown_text": "<p>This could be shorter</p>", "released": true, "permission": { update: false, destroy: false, }, "user": { name: "Jan Klaassen", } }); codeListing.addUserAnnotation({ "id": 2, "line_nr": 2, "annotation_text": "This should be faster", "markdown_text": "<p>This should be faster</p>", "released": true, "permission": { update: true, destroy: true, }, "user": { name: "Piet Hein", } }); expect(document.querySelectorAll(".annotation").length).toBe(2); }); test("feedback table should support more than 1 annotation per row", () => { codeListing.addUserAnnotation({ "id": 1, "line_nr": 1, "annotation_text": "This could be shorter", "markdown_text": "<p>This could be shorter</p>", "permission": { update: false, destroy: false, }, "released": true, "user": { name: "Jan Klaassen", } }); codeListing.addUserAnnotation({ "id": 2, "line_nr": 1, "annotation_text": "This should be faster", "markdown_text": "<p>This should be faster</p>", "released": true, "permission": { update: true, destroy: true, }, "user": { name: "Piet Hein", } }); expect(document.querySelectorAll(".annotation").length).toBe(2); }); test("feedback table should be able to contain both machine annotations and user annotations", () => { codeListing.addUserAnnotation({ "id": 1, "line_nr": 1, "annotation_text": "This could be shorter", "markdown_text": "<p>This could be shorter</p>", "released": true, "permission": { update: false, destroy: false, }, "user": { name: "Jan Klaassen", } }); codeListing.addUserAnnotation({ "id": 2, "line_nr": 2, "annotation_text": "This should be faster", "markdown_text": "<p>This should be faster</p>", "released": true, "permission": { update: true, destroy: true, }, "user": { name: "Piet Hein", } }); codeListing.addMachineAnnotations([ { "text": "Value could be assigned", "row": 0, "type": "warning" }, { "text": "Value could be assigned", "row": 0, "type": "warning" }, { "text": "Value could be assigned", "row": 1, "type": "warning" }, { "text": "Value could be assigned", "row": 1, "type": "error" }, { "text": "Value could be assigned", "row": 2, "type": "warning" }, { "text": "Value could be assigned", "row": 2, "type": "info" }, ]); expect(document.querySelectorAll(".annotation").length).toBe(2 + 6); }); test("ensure that all buttons are created", () => { codeListing.initAnnotateButtons(); expect(document.querySelectorAll(".annotation-button").length).toBe(3); }); test("click on comment button", () => { codeListing.initAnnotateButtons(); const annotationButton: HTMLButtonElement = document.querySelector(".annotation-button"); annotationButton.click(); expect(document.querySelectorAll("form.annotation-submission").length).toBe(1); annotationButton.click(); expect(document.querySelectorAll("form.annotation-submission").length).toBe(1); });
the_stack
declare namespace samsam{ // samsam.isArguments.!0 /** * */ interface IsArguments0 { } } declare namespace samsam{ // samsam.keys.!ret type KeysRet = Array<any>; } declare namespace formatio{ // formatio.configure.!0 /** * */ interface Configure0 { /** * */ quoteStrings : boolean; /** * */ limitChildrenCount : number; } } declare namespace formatio{ // formatio.configure.!ret /** * */ interface ConfigureRet { /** * */ quoteStrings : boolean; /** * */ limitChildrenCount : number; } } declare namespace sinon{ // sinon.wrapMethod.!0 /** * */ interface WrapMethod0 { } } declare namespace sinon{ // sinon.create.!0 /** * */ interface Create0 { /** * */ xhr : { /** * */ useFilters : boolean; /** * */ parseXML : /*no type*/{}; /** * */ statusCodes : { } /** * */ prototype : { /** * */ async : boolean; /** * */ errorFlag : boolean; /** * */ sendFlag : boolean; /** * */ responseText : string; /** * */ response : string; /** * */ aborted : boolean; /** * */ requestHeaders : { /** * */ "Content-Type" : string; } /** * */ progress : number; /** * */ status : number; /** * */ statusText : string; /** * */ uploadProgress : /*no type*/{}; /** * */ toString : /* !proto.toString */ any; /** * */ open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ eventListeners : { } /** * */ setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; /** * */ readyStateChange : /* sinon.FakeXMLHttpRequest.prototype.readyStateChange */ any; } /** * */ UNSENT : number; /** * */ OPENED : number; /** * */ HEADERS_RECEIVED : number; /** * */ LOADING : number; /** * */ DONE : number; /** * */ toString : /* !proto.toString */ any; /** * */ restore : /* sinon.FakeXMLHttpRequest.restore */ any; /** * */ filters : /* sinon.FakeXMLHttpRequest.filters */ any; /** * */ addFilter : /* sinon.FakeXMLHttpRequest.addFilter */ any; /** * */ defake : /*no type*/{}; /** * */ onCreate : /* sinon.FakeXDomainRequest.onCreate */ any; } /** * */ responding : boolean; /** * */ create : /*no type*/{}; /** * */ getHTTPMethod : /*no type*/{}; /** * */ configure : /* sinon.fakeServer.configure */ any; /** * */ addRequest : /* sinon.fakeServer.addRequest */ any; /** * */ queue : { } /** * */ handleRequest : /* sinon.fakeServer.handleRequest */ any; /** * */ log : /* sinon.fakeServer.log */ any; /** * */ responses : { } /** * */ respondWith : /* sinon.fakeServer.respondWith */ any; /** * */ response : /* sinon.fakeServer.response */ any; /** * */ respond : /* sinon.fakeServer.respond */ any; /** * */ processRequest : /* sinon.fakeServer.processRequest */ any; /** * */ restore : /* sinon.fakeServer.restore */ any; } } declare namespace sinon.Create0.xhr{ // sinon.create.!0.xhr.parseXML.!ret /** * */ interface ParseXMLRet { /** * */ async : string; } } declare namespace sinon.Create0.xhr.prototype{ // sinon.create.!0.xhr.prototype.uploadProgress.!0 /** * */ interface UploadProgress0 { /** * */ loaded : number; /** * */ total : number; } } declare namespace sinon{ // sinon.objectKeys.!ret type ObjectKeysRet = Array<any>; } declare namespace sinon{ // sinon.getPropertyDescriptor.!ret /** * */ interface GetPropertyDescriptorRet { /** * */ restore : { /** * */ sinon : boolean; } } } declare namespace sinon{ // sinon.getConfig.!ret /** * */ interface GetConfigRet { } } declare namespace sinon{ // sinon.calledInOrder.!0 type CalledInOrder0 = Array<any>; } declare namespace sinon{ // sinon.extend.!ret /** * */ interface ExtendRet { /** * */ isSinonProxy : boolean; /** * */ displayName : string; /** * */ instantiateFake : /*no type*/{}; /** * */ id : string; /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ create : /*no type*/{}; /** * */ invoking : boolean; /** * */ named : /*no type*/{}; /** * */ withArgs : /*no type*/{}; /** * */ fakes : { } /** * */ callsArg : /*no type*/{}; /** * */ callArgAt : number; /** * */ callbackAsync : boolean; /** * */ returnValueDefined : boolean; /** * */ returnThis : boolean; /** * */ behaviors : Array<any>; /** * */ enumerable : boolean; /** * */ configurable : boolean; /** * */ writable : boolean; /** * */ expectations : { } /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ responseText : string; /** * */ sendFlag : boolean; /** * */ readyState : number; /** * */ errorFlag : boolean; /** * */ aborted : boolean; /** * */ status : number; /** * */ isTimeout : boolean; /** * */ UNSENT : number; /** * */ OPENED : number; /** * */ LOADING : number; /** * */ DONE : number; /** * */ async : boolean; /** * */ response : string; /** * */ requestHeaders : { /** * */ "Content-Type" : string; } /** * */ progress : number; /** * */ statusText : string; /** * */ uploadProgress : /*no type*/{}; /** * */ HEADERS_RECEIVED : number; /** * */ useFilters : boolean; /** * */ parseXML : /*no type*/{}; /** * */ statusCodes : { } /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ getCalls : /*no type*/{}; /** * */ throwsException : /* sinon.behavior.throws */ any; /** * */ get : /* sinon.collection.fakes.<i>.get */ any; /** * */ set : /* sinon.collection.fakes.<i>.set */ any; /** * */ spyCall : { /** * */ toString : /* sinon.spyCall.toString */ any; } /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ reset : /* sinon.spy.reset */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : { /** * */ c : /* sinon.spy.formatters.c */ any; /** * */ n : /* sinon.spy.formatters.n */ any; /** * */ C : /* sinon.spy.formatters.C */ any; /** * */ t : /* sinon.spy.formatters.t */ any; /** * */ "*" : /* sinon.spy.formatters.* */ any; } /** * */ isPresent : /* sinon.behavior.isPresent */ any; /** * */ onCall : /* sinon.behavior.onCall */ any; /** * */ onFirstCall : /* sinon.behavior.onFirstCall */ any; /** * */ onSecondCall : /* sinon.behavior.onSecondCall */ any; /** * */ onThirdCall : /* sinon.behavior.onThirdCall */ any; /** * */ callbackArguments : /* sinon.behavior.callbackArguments */ any; /** * */ callsArgOn : /* sinon.behavior.callsArgOn */ any; /** * */ callsArgWith : /* sinon.behavior.callsArgWith */ any; /** * */ callsArgOnWith : /* sinon.behavior.callsArgOnWith */ any; /** * */ yields : /* sinon.behavior.yields */ any; /** * */ yieldsRight : /* sinon.behavior.yieldsRight */ any; /** * */ yieldsOn : /* sinon.behavior.yieldsOn */ any; /** * */ yieldsTo : /* sinon.behavior.yieldsTo */ any; /** * */ yieldsToOn : /* sinon.behavior.yieldsToOn */ any; /** * */ throws : /* sinon.behavior.throws */ any; /** * */ returns : /* sinon.behavior.returns */ any; /** * */ returnsArg : /* sinon.behavior.returnsArg */ any; /** * */ returnsThis : /* sinon.behavior.returnsThis */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ atLeast : /* sinon.expectation.atLeast */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; /** * */ expects : /* sinon.mock.expects */ any; /** * */ proxies : /* sinon.mock.proxies */ any; /** * */ invokeMethod : /* sinon.mock.invokeMethod */ any; /** * */ open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; /** * */ addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ eventListeners : { } /** * */ readyStateChange : /* sinon.FakeXDomainRequest.prototype.readyStateChange */ any; /** * */ simulatetimeout : /* sinon.FakeXDomainRequest.prototype.simulatetimeout */ any; /** * */ onCreate : /* sinon.FakeXDomainRequest.onCreate */ any; /** * */ filters : /* sinon.FakeXMLHttpRequest.filters */ any; /** * */ addFilter : /* sinon.FakeXMLHttpRequest.addFilter */ any; /** * */ defake : /*no type*/{}; /** * */ restore : /* sinon.FakeXMLHttpRequest.restore */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.instantiateFake.!ret /** * */ interface InstantiateFakeRet { /** * */ isSinonProxy : boolean; /** * */ displayName : string; /** * */ id : string; /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ named : /*no type*/{}; /** * */ withArgs : /*no type*/{}; /** * */ fakes : { } /** * */ enumerable : boolean; /** * */ configurable : boolean; /** * */ writable : boolean; /** * */ toString : /* !proto.toString */ any; /** * */ instantiateFake : /* sinon.spy.create */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ create : /* sinon.spy.create */ any; /** * */ getCalls : /*no type*/{}; /** * */ restore : /* sinon.collection.fakes.<i>.restore */ any; /** * */ get : /* sinon.collection.fakes.<i>.get */ any; /** * */ set : /* sinon.collection.fakes.<i>.set */ any; /** * */ spyCall : { /** * */ toString : /* sinon.spyCall.toString */ any; } /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ reset : /* sinon.spy.reset */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ invoke : /* sinon.spy.invoke */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : { /** * */ c : /* sinon.spy.formatters.c */ any; /** * */ n : /* sinon.spy.formatters.n */ any; /** * */ C : /* sinon.spy.formatters.C */ any; /** * */ t : /* sinon.spy.formatters.t */ any; /** * */ "*" : /* sinon.spy.formatters.* */ any; } /** * */ behaviors : /* sinon.extend.!ret.behaviors */ any; } } declare namespace sinon.ExtendRet.InstantiateFakeRet{ // sinon.extend.!ret.instantiateFake.!ret.named.!ret /** * */ interface NamedRet { /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ withArgs : /*no type*/{}; /** * */ fakes : { } /** * */ reset : /* sinon.spy.reset */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ create : /* sinon.spy.create */ any; /** * */ invoke : /* sinon.spy.invoke */ any; /** * */ named : /* sinon.spy.named */ any; /** * */ getCalls : /*no type*/{}; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : { /** * */ c : /* sinon.spy.formatters.c */ any; /** * */ n : /* sinon.spy.formatters.n */ any; /** * */ C : /* sinon.spy.formatters.C */ any; /** * */ t : /* sinon.spy.formatters.t */ any; /** * */ "*" : /* sinon.spy.formatters.* */ any; } } } declare namespace sinon.ExtendRet.InstantiateFakeRet.NamedRet{ // sinon.extend.!ret.instantiateFake.!ret.named.!ret.withArgs.!ret /** * */ interface WithArgsRet { /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ matchingAguments : /* sinon.spy.fakes.<i>.matchingAguments */ any; /** * */ parent : /* sinon.spy.fakes.<i>.parent */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ withArgs : /* sinon.spy.fakes.<i>.withArgs */ any; } } declare namespace sinon.ExtendRet.InstantiateFakeRet{ // sinon.extend.!ret.instantiateFake.!ret.withArgs.!ret /** * */ interface WithArgsRet { /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ matchingAguments : /* sinon.spy.fakes.<i>.matchingAguments */ any; /** * */ parent : /* sinon.spy.fakes.<i>.parent */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ withArgs : /* sinon.spy.fakes.<i>.withArgs */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.create.!ret /** * */ interface CreateRet { /** * */ method : string; /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ atLeast : /*no type*/{}; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ invoking : boolean; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ create : /* sinon.expectation.create */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ withArgs : /* sinon.expectation.withArgs */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; } } declare namespace sinon.ExtendRet.CreateRet{ // sinon.extend.!ret.create.!ret.atLeast.!ret /** * */ interface AtLeastRet { /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ invoking : boolean; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ create : /* sinon.expectation.create */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ atLeast : /* sinon.expectation.atLeast */ any; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ withArgs : /* sinon.expectation.withArgs */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.named.!ret /** * */ interface NamedRet { /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ reset : /* sinon.spy.reset */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ create : /* sinon.spy.create */ any; /** * */ invoke : /* sinon.spy.invoke */ any; /** * */ named : /* sinon.spy.named */ any; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ getCalls : /* sinon.spy.getCalls */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ withArgs : /* sinon.spy.withArgs */ any; /** * */ fakes : /* sinon.spy.fakes */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : /* sinon.spy.formatters */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.withArgs.!ret /** * */ interface WithArgsRet { /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ invoking : boolean; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ create : /* sinon.expectation.create */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ atLeast : /* sinon.expectation.atLeast */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ withArgs : /* sinon.expectation.withArgs */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.callsArg.!ret /** * */ interface CallsArgRet { /** * */ create : /*no type*/{}; /** * */ callArgAt : number; /** * */ callbackAsync : boolean; /** * */ returnValueDefined : boolean; /** * */ returnThis : boolean; /** * */ isPresent : /* sinon.behavior.isPresent */ any; /** * */ onCall : /* sinon.behavior.onCall */ any; /** * */ onFirstCall : /* sinon.behavior.onFirstCall */ any; /** * */ onSecondCall : /* sinon.behavior.onSecondCall */ any; /** * */ onThirdCall : /* sinon.behavior.onThirdCall */ any; /** * */ callsArg : /* sinon.behavior.callsArg */ any; /** * */ throwsException : /* sinon.behavior.throws */ any; /** * */ callbackArguments : /* sinon.behavior.callbackArguments */ any; /** * */ callsArgOn : /* sinon.behavior.callsArgOn */ any; /** * */ callsArgWith : /* sinon.behavior.callsArgWith */ any; /** * */ callsArgOnWith : /* sinon.behavior.callsArgOnWith */ any; /** * */ yields : /* sinon.behavior.yields */ any; /** * */ yieldsRight : /* sinon.behavior.yieldsRight */ any; /** * */ yieldsOn : /* sinon.behavior.yieldsOn */ any; /** * */ yieldsTo : /* sinon.behavior.yieldsTo */ any; /** * */ yieldsToOn : /* sinon.behavior.yieldsToOn */ any; /** * */ throws : /* sinon.behavior.throws */ any; /** * */ returns : /* sinon.behavior.returns */ any; /** * */ returnsArg : /* sinon.behavior.returnsArg */ any; /** * */ returnsThis : /* sinon.behavior.returnsThis */ any; /** * */ invoke : /* sinon.behavior.invoke */ any; /** * */ withArgs : /* sinon.behavior.withArgs */ any; } } declare namespace sinon.ExtendRet.CallsArgRet{ // sinon.extend.!ret.callsArg.!ret.create.!ret /** * */ interface CreateRet { /** * */ callArgAt : number; /** * */ callbackAsync : boolean; /** * */ returnValueDefined : boolean; /** * */ returnThis : boolean; /** * */ toString : /* !proto.toString */ any; /** * */ create : /* sinon.behavior.create */ any; /** * */ isPresent : /* sinon.behavior.isPresent */ any; /** * */ onCall : /* sinon.behavior.onCall */ any; /** * */ onFirstCall : /* sinon.behavior.onFirstCall */ any; /** * */ onSecondCall : /* sinon.behavior.onSecondCall */ any; /** * */ onThirdCall : /* sinon.behavior.onThirdCall */ any; /** * */ callsArg : /* sinon.behavior.callsArg */ any; /** * */ throwsException : /* sinon.behavior.throws */ any; /** * */ invoke : /* sinon.behavior.invoke */ any; /** * */ withArgs : /* sinon.behavior.withArgs */ any; /** * */ callbackArguments : /* sinon.behavior.callbackArguments */ any; /** * */ callsArgOn : /* sinon.behavior.callsArgOn */ any; /** * */ callsArgWith : /* sinon.behavior.callsArgWith */ any; /** * */ callsArgOnWith : /* sinon.behavior.callsArgOnWith */ any; /** * */ yields : /* sinon.behavior.yields */ any; /** * */ yieldsRight : /* sinon.behavior.yieldsRight */ any; /** * */ yieldsOn : /* sinon.behavior.yieldsOn */ any; /** * */ yieldsTo : /* sinon.behavior.yieldsTo */ any; /** * */ yieldsToOn : /* sinon.behavior.yieldsToOn */ any; /** * */ throws : /* sinon.behavior.throws */ any; /** * */ returns : /* sinon.behavior.returns */ any; /** * */ returnsArg : /* sinon.behavior.returnsArg */ any; /** * */ returnsThis : /* sinon.behavior.returnsThis */ any; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.uploadProgress.!0 /** * */ interface UploadProgress0 { /** * */ loaded : number; /** * */ total : number; } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.parseXML.!ret /** * */ interface ParseXMLRet { /** * */ async : string; } } declare namespace sinon.spy{ // sinon.spy.reset.!ret /** * Retain the function length: */ interface ResetRet { /** * */ isSinonProxy : boolean; /** * */ displayName : string; /** * */ id : string; /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ enumerable : boolean; /** * */ configurable : boolean; /** * */ writable : boolean; /** * */ (): void; } } declare namespace sinon.spy{ // sinon.spy.named.!ret /** * */ interface NamedRet { /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ reset : /* sinon.spy.reset */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ create : /* sinon.spy.create */ any; /** * */ invoke : /* sinon.spy.invoke */ any; /** * */ named : /* sinon.spy.named */ any; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ getCalls : /* sinon.spy.getCalls */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ withArgs : /* sinon.spy.withArgs */ any; /** * */ fakes : /* sinon.spy.fakes */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : /* sinon.spy.formatters */ any; } } declare namespace sinon.spy{ // sinon.spy.getCalls.!ret type GetCallsRet = Array</* sinon.spy.firstCall */ any>; } declare namespace sinon.spy{ // sinon.spy.withArgs.!ret /** * */ interface WithArgsRet { /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ matchingAguments : /* sinon.spy.fakes.<i>.matchingAguments */ any; /** * */ parent : /* sinon.spy.fakes.<i>.parent */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ withArgs : /* sinon.spy.fakes.<i>.withArgs */ any; } } declare namespace sinon.spy{ // sinon.spy.fakes.<i> /** * */ interface FakesI { /** * */ matchingAguments : Array<any>; /** * Public API */ parent : { /** * */ called : boolean; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ callCount : number; /** * */ invoking : boolean; /** * */ reset : /* sinon.spy.reset */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; /** * */ args : /* sinon.spy.args */ any; /** * */ returnValues : /* sinon.spy.returnValues */ any; /** * */ thisValues : /* sinon.spy.thisValues */ any; /** * */ exceptions : /* sinon.spy.exceptions */ any; /** * */ callIds : /* sinon.spy.callIds */ any; /** * */ stacks : /* sinon.spy.stacks */ any; /** * */ create : /* sinon.spy.create */ any; /** * */ invoke : /* sinon.spy.invoke */ any; /** * */ named : /* sinon.spy.named */ any; /** * */ getCall : /* sinon.spy.getCall */ any; /** * */ getCalls : /* sinon.spy.getCalls */ any; /** * */ calledBefore : /* sinon.spy.calledBefore */ any; /** * */ calledAfter : /* sinon.spy.calledAfter */ any; /** * */ withArgs : /* sinon.spy.withArgs */ any; /** * */ fakes : /* sinon.spy.fakes */ any; /** * */ matches : /* sinon.spy.matches */ any; /** * */ printf : /* sinon.spy.printf */ any; /** * */ formatters : { /** * */ c : /* sinon.spy.formatters.c */ any; /** * */ n : /* sinon.spy.formatters.n */ any; /** * */ C : /* sinon.spy.formatters.C */ any; /** * */ t : /* sinon.spy.formatters.t */ any; /** * */ "*" : /* sinon.spy.formatters.* */ any; } } /** * * @return */ withArgs(): /* sinon.spy.fakes.<i> */ any; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; } } declare namespace sinon{ // sinon.spy.!0 type Spy0 = (() => void); } declare namespace sinon.behavior{ // sinon.behavior.create.!ret /** * */ interface CreateRet { /** * */ callArgAt : number; /** * */ callbackAsync : boolean; /** * */ returnValueDefined : boolean; /** * */ returnThis : boolean; /** * */ toString : /* !proto.toString */ any; /** * */ create : /* sinon.behavior.create */ any; /** * */ isPresent : /* sinon.behavior.isPresent */ any; /** * */ onCall : /* sinon.behavior.onCall */ any; /** * */ onFirstCall : /* sinon.behavior.onFirstCall */ any; /** * */ onSecondCall : /* sinon.behavior.onSecondCall */ any; /** * */ onThirdCall : /* sinon.behavior.onThirdCall */ any; /** * */ callsArg : /* sinon.behavior.callsArg */ any; /** * */ callbackArguments : /* sinon.behavior.callbackArguments */ any; /** * */ callsArgOn : /* sinon.behavior.callsArgOn */ any; /** * */ callsArgWith : /* sinon.behavior.callsArgWith */ any; /** * */ callsArgOnWith : /* sinon.behavior.callsArgOnWith */ any; /** * */ yields : /* sinon.behavior.yields */ any; /** * */ yieldsRight : /* sinon.behavior.yieldsRight */ any; /** * */ yieldsOn : /* sinon.behavior.yieldsOn */ any; /** * */ yieldsTo : /* sinon.behavior.yieldsTo */ any; /** * */ yieldsToOn : /* sinon.behavior.yieldsToOn */ any; /** * */ throws : /* sinon.behavior.throws */ any; /** * */ throwsException : /* sinon.behavior.throws */ any; /** * */ returns : /* sinon.behavior.returns */ any; /** * */ returnsArg : /* sinon.behavior.returnsArg */ any; /** * */ returnsThis : /* sinon.behavior.returnsThis */ any; /** * */ invoke : /* sinon.behavior.invoke */ any; /** * */ withArgs : /* sinon.behavior.withArgs */ any; } } declare namespace sinon.expectation{ // sinon.expectation.create.!ret /** * */ interface CreateRet { /** * */ method : string; /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ invoking : boolean; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ create : /* sinon.expectation.create */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ atLeast : /* sinon.expectation.atLeast */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ withArgs : /* sinon.expectation.withArgs */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; } } declare namespace sinon.expectation{ // sinon.expectation.allowsCall.!1 type AllowsCall1 = Array<any>; } declare namespace sinon.mock{ // sinon.mock.create.!ret /** * */ interface CreateRet { /** * */ create : /* sinon.mock.create */ any; /** * */ expects : /* sinon.mock.expects */ any; /** * */ expectations : /* sinon.mock.expectations */ any; /** * */ proxies : /* sinon.mock.proxies */ any; /** * */ invokeMethod : /* sinon.mock.invokeMethod */ any; /** * */ restore : /* sinon.mock.restore */ any; /** * */ verify : /* sinon.mock.verify */ any; } } declare namespace sinon.mock.expectations{ // sinon.mock.expectations.<i>.<i> /** * */ interface ExpectationsII { /** * */ method : string; /** * */ minCalls : number; /** * */ maxCalls : number; /** * */ limitsSet : boolean; /** * */ failed : boolean; /** * */ expectsExactArgCount : boolean; /** * */ invoking : boolean; /** * */ called : boolean; /** * */ callCount : number; /** * */ notCalled : boolean; /** * */ calledOnce : boolean; /** * */ calledTwice : boolean; /** * */ calledThrice : boolean; /** * */ toString : /* sinon.expectation.toString */ any; /** * */ create : /* sinon.expectation.create */ any; /** * */ invoke : /* sinon.expectation.invoke */ any; /** * */ atLeast : /* sinon.expectation.atLeast */ any; /** * */ atMost : /* sinon.expectation.atMost */ any; /** * */ never : /* sinon.expectation.never */ any; /** * */ once : /* sinon.expectation.once */ any; /** * */ twice : /* sinon.expectation.twice */ any; /** * */ thrice : /* sinon.expectation.thrice */ any; /** * */ exactly : /* sinon.expectation.exactly */ any; /** * */ met : /* sinon.expectation.met */ any; /** * */ verifyCallAllowed : /* sinon.expectation.verifyCallAllowed */ any; /** * */ allowsCall : /* sinon.expectation.allowsCall */ any; /** * */ withArgs : /* sinon.expectation.withArgs */ any; /** * */ expectedArguments : /* sinon.expectation.expectedArguments */ any; /** * */ withExactArgs : /* sinon.expectation.withExactArgs */ any; /** * */ on : /* sinon.expectation.on */ any; /** * */ verify : /* sinon.expectation.verify */ any; /** * */ pass : /* sinon.expectation.pass */ any; /** * */ fail : /* sinon.expectation.fail */ any; /** * */ firstCall : /* sinon.spy.firstCall */ any; /** * */ secondCall : /* sinon.spy.firstCall */ any; /** * */ thirdCall : /* sinon.spy.firstCall */ any; /** * */ lastCall : /* sinon.spy.firstCall */ any; } } declare namespace sinon.mock{ // sinon.mock.invokeMethod.!2 type InvokeMethod2 = Array<any>; } declare namespace sinon.collection{ // sinon.collection.stub.!0 /** * */ interface Stub0 { } } declare namespace sinon.collection{ // sinon.collection.stub.!ret /** * */ interface StubRet { /** * */ restore(): void; } } declare namespace sinon.collection{ // sinon.collection.inject.!0 /** * */ interface Inject0 { /** * */ clock : { /** * */ duringTick : boolean; /** * */ restore : /* sinon.fakeServerWithClock.clock.uninstall */ any; /** * */ setTimeout : /* sinon.fakeServerWithClock.clock.setTimeout */ any; /** * */ clearTimeout : /* sinon.fakeServerWithClock.clock.clearTimeout */ any; /** * */ setInterval : /* sinon.fakeServerWithClock.clock.setInterval */ any; /** * */ clearInterval : /* sinon.fakeServerWithClock.clock.clearInterval */ any; /** * */ setImmediate : /* sinon.fakeServerWithClock.clock.setImmediate */ any; /** * */ clearImmediate : /* sinon.fakeServerWithClock.clock.clearImmediate */ any; /** * */ tick : /* sinon.fakeServerWithClock.clock.tick */ any; /** * */ reset : /* sinon.fakeServerWithClock.clock.reset */ any; /** * */ setSystemTime : /* sinon.fakeServerWithClock.clock.setSystemTime */ any; /** * */ uninstall : /* sinon.fakeServerWithClock.clock.uninstall */ any; } /** * */ requests : Array<any>; /** * * @return */ spy(): any; /** * * @return */ stub(): /* sinon.collection.stub.!ret */ any; /** * * @return */ mock(): any; /** * */ mock(); /** * */ server : { /** * */ requests : { } } /** * */ match : /* sinon.match */ any; } } declare namespace sinon{ // sinon.useFakeTimers.!ret /** * */ interface UseFakeTimersRet { /** * */ duringTick : boolean; /** * */ restore : /* sinon.fakeServerWithClock.clock.uninstall */ any; /** * */ setTimeout : /* sinon.fakeServerWithClock.clock.setTimeout */ any; /** * */ clearTimeout : /* sinon.fakeServerWithClock.clock.clearTimeout */ any; /** * */ setInterval : /* sinon.fakeServerWithClock.clock.setInterval */ any; /** * */ clearInterval : /* sinon.fakeServerWithClock.clock.clearInterval */ any; /** * */ setImmediate : /* sinon.fakeServerWithClock.clock.setImmediate */ any; /** * */ clearImmediate : /* sinon.fakeServerWithClock.clock.clearImmediate */ any; /** * */ tick : /* sinon.fakeServerWithClock.clock.tick */ any; /** * */ reset : /* sinon.fakeServerWithClock.clock.reset */ any; /** * */ setSystemTime : /* sinon.fakeServerWithClock.clock.setSystemTime */ any; /** * */ uninstall : /* sinon.fakeServerWithClock.clock.uninstall */ any; } } declare namespace sinon.Event.prototype{ // sinon.Event.prototype.initEvent.!3 /** * */ interface InitEvent3 { /** * */ async : boolean; /** * */ errorFlag : boolean; /** * */ sendFlag : boolean; /** * */ responseText : string; /** * */ response : string; /** * */ aborted : boolean; /** * */ progress : number; /** * */ status : number; /** * */ statusText : string; /** * */ open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ readyStateChange : /* sinon.FakeXMLHttpRequest.prototype.readyStateChange */ any; /** * */ setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ requestHeaders : /* sinon.FakeXMLHttpRequest.prototype.requestHeaders */ any; /** * */ responseHeaders : any; /** * */ error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ uploadProgress : /* sinon.FakeXMLHttpRequest.prototype.uploadProgress */ any; /** * */ downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; } } declare namespace sinon.Event.prototype.target{ // sinon.Event.prototype.target.uploadProgress.!0 /** * */ interface UploadProgress0 { /** * */ loaded : number; /** * */ total : number; } } declare namespace sinon{ // sinon.ProgressEvent.!1 /** * ensure loaded and total are numbers */ interface ProgressEvent1 { /** * */ loaded : number; /** * */ total : number; } } declare namespace sinon{ // sinon.CustomEvent.!1 /** * */ interface CustomEvent1 { } } declare namespace sinon.logError{ // sinon.logError.setTimeout.!0 type SetTimeout0 = (() => void); } declare namespace sinon{ // sinon.logError.!1 /** * */ interface LogError1 { /** * */ message : string; } } declare namespace sinon.xhr.XMLHttpRequest{ // sinon.xhr.XMLHttpRequest.parseXML.!ret /** * */ interface ParseXMLRet { /** * */ async : string; } } declare namespace sinon.FakeXMLHttpRequest{ // sinon.FakeXMLHttpRequest.defake.!0 /** * */ interface Defake0 { } } declare namespace sinon.FakeXMLHttpRequest{ // sinon.FakeXMLHttpRequest.defake.!1 type Defake1 = Array<any>; } declare namespace sinon.FakeXMLHttpRequest{ // sinon.FakeXMLHttpRequest.parseXML.!ret /** * */ interface ParseXMLRet { /** * */ async : string; } } declare namespace sinon.fakeServer{ // sinon.fakeServer.create.!ret /** * */ interface CreateRet { /** * */ requests : /* sinon.collection.inject.!0.requests */ any; } } declare namespace sinon.fakeServer{ // sinon.fakeServer.queue.<i> /** * */ interface QueueI { /** * */ onSend : /* sinon.FakeXMLHttpRequest.onSend */ any; } } declare namespace sinon.fakeServer{ // sinon.fakeServer.log.!0 type Log0 = Array</* number,?,string */ any>; } declare namespace sinon.fakeServer{ // sinon.fakeServer.responses.<i> /** * */ interface ResponsesI { /** * */ response : Array<any>; } } declare namespace sinon.assert{ // sinon.assert.expose.!0 /** * */ interface Expose0 { } } declare namespace sinon.Create0{ // sinon.create.!0.create.!ret /** * */ interface CreateRet { /** * */ requests : { } } } declare namespace sinon.Create0{ // sinon.create.!0.getHTTPMethod.!0 /** * */ interface GetHTTPMethod0 { /** * */ onSend : /* sinon.FakeXMLHttpRequest.onSend */ any; } } declare namespace sinon.ExtendRet.InstantiateFakeRet.NamedRet{ // sinon.extend.!ret.instantiateFake.!ret.named.!ret.getCalls.!ret /** * */ interface GetCallsRet { } } declare namespace sinon.ExtendRet.InstantiateFakeRet{ // sinon.extend.!ret.instantiateFake.!ret.getCalls.!ret /** * */ interface GetCallsRet { } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.getCalls.!ret /** * */ interface GetCallsRet { } } declare namespace sinon.Create0.xhr{ // sinon.create.!0.xhr.defake.!0 /** * */ interface Defake0 { } } declare namespace sinon.ExtendRet{ // sinon.extend.!ret.defake.!0 /** * */ interface Defake0 { } } declare namespace sinon.xhr.XMLHttpRequest{ // sinon.xhr.XMLHttpRequest.defake.!0 /** * */ interface Defake0 { } } declare namespace sinon.fakeServer{ // sinon.fakeServer.getHTTPMethod.!0 /** * */ interface GetHTTPMethod0 { /** * */ onSend : /* sinon.FakeXMLHttpRequest.onSend */ any; } } /** * */ declare namespace samsam{ /** * @name samsam.isArguments * @param Object object * * Returns ``true`` if ``object`` is an ``arguments`` object, * ``false`` otherwise. * @param object * @return */ function isArguments(object : samsam.IsArguments0): boolean; /** * @name samsam.isElement * @param Object object * * Returns ``true`` if ``object`` is a DOM element node. Unlike * Underscore.js/lodash, this function will return ``false`` if ``object`` * is an *element-like* object, i.e. a regular object with a ``nodeType`` * property that holds the value ``1``. * @param object * @return */ function isElement(object : any): boolean; /** * @name samsam.isDate * @param Object value * * Returns true if the object is a ``Date``, or *date-like*. Duck typing * of date objects work by checking that the object has a ``getTime`` * function whose return value equals the return value from the object's * ``valueOf``. * @param value * @return */ function isDate(value : any): boolean; /** * @name samsam.isNegZero * @param Object value * * Returns ``true`` if ``value`` is ``-0``. * @param value * @return */ function isNegZero(value : any): boolean; /** * @name samsam.equal * @param Object obj1 * @param Object obj2 * * Returns ``true`` if two objects are strictly equal. Compared to * ``===`` there are two exceptions: * * - NaN is considered equal to NaN * - -0 and +0 are not considered equal * @param obj1 * @param obj2 * @return */ function identical(obj1 : any, obj2 : any): boolean; /** * @name samsam.deepEqual * @param Object obj1 * @param Object obj2 * * Deep equal comparison. Two values are "deep equal" if: * * - They are equal, according to samsam.identical * - They are both date objects representing the same time * - They are both arrays containing elements that are all deepEqual * - They are objects with the same set of properties, and each property * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` * * Supports cyclic objects. * @param obj1 * @param obj2 * @return */ function deepEqual(obj1 : any, obj2 : any): boolean; /** * @name samsam.match * @param Object object * @param Object matcher * * Compare arbitrary value ``object`` with matcher. * @param object * @param matcher * @return */ function match(object : any, matcher : any): boolean; /** * * @param object * @return */ function keys(object : any): samsam.KeysRet; } /** * */ declare namespace formatio{ /** * * @param func * @return */ function functionName(func : any): /* error */ any; /** * * @param options * @return */ function configure(options : formatio.Configure0): formatio.ConfigureRet; /** * * @param object * @return */ function constructorName(object : any): /* error */ any; /** * * @param object * @param processed * @param indent * @return */ function ascii(object : Array<any> | /* sinon.fakeServer.queue.<i> */ any, processed : Array<any> | /* sinon.fakeServer.queue.<i> */ any, indent : Array<any> | /* sinon.fakeServer.queue.<i> */ any): Array<any> | /* sinon.fakeServer.queue.<i> */ any; } /** * eslint-disable-line no-unused-vars */ declare namespace sinon{ /** * * @param object * @param property * @param method * @return */ function wrapMethod(object : sinon.WrapMethod0, property : any, method : {} | (() => void)): {} | (() => void); /** * * @param proto */ function create(proto : sinon.Create0): void; /** * * @param a * @param b * @return */ function deepEqual(a : any, b : any): boolean; /** * * @param func * @return */ function functionName(func : any): /* error */ any; /** * * @return */ function functionToString(): /* !this.displayName */ any; /** * * @param obj * @return */ function objectKeys(obj : {} | (() => void)): sinon.ObjectKeysRet; /** * * @param object * @param property * @return */ function getPropertyDescriptor(object : /* sinon.wrapMethod.!0 */ any, property : any): sinon.GetPropertyDescriptorRet; /** * * @param custom * @return */ function getConfig(custom : any): sinon.GetConfigRet; /** * */ namespace defaultConfig{ /** * */ export var injectIntoThis : boolean; /** * */ export var properties : Array<string>; /** * */ export var useFakeTimers : boolean; /** * */ export var useFakeServer : boolean; } /** * * @param count * @return */ function timesInWords(count : number): boolean; /** * */ function timesInWords(); /** * * @param spies * @return */ function calledInOrder(spies : sinon.CalledInOrder0): boolean; /** * * @param spies */ function orderByFirstCall(spies : Array<any>): void; /** * * @param constructor */ function createStubInstance(constructor : any): void; /** * * @param object */ function restore(object : any): void; /** * * @param target * @return */ function extend(target : any): sinon.ExtendRet; /** * * @param expectation * @param message * @return */ function match(expectation : any, message : string): /* sinon.match.any */ any; /** * */ namespace match{ /** * * @param object * @return */ function isMatcher(object : any): boolean; /** * */ var any : { /** * */ message : string; } /** * * @param expectation * @return */ function same(expectation : any): /* sinon.match.any */ any; /** * * @param type * @return */ function typeOf(type : string): /* sinon.match.any */ any; /** * * @param type * @return */ function instanceOf(type : any): /* sinon.match.any */ any; /** * * @param property * @param value * @return */ function has(property : any, value : any): /* sinon.match.any */ any; } /** * * @param value * @return */ function format(value : Array<any> | /* sinon.fakeServer.queue.<i> */ any): string; /** * * @param spy * @param thisValue * @param args * @param returnValue * @param exception * @param id * @param stack * @return */ function spyCall(spy : /* sinon.spy.fakes.<i>.parent */ any | (() => void), thisValue : any, args : any, returnValue : any, exception : any, id : any, stack : any): /* sinon.spy.firstCall */ any; /** * */ namespace spyCall{ /** * * @return */ function toString(): string; } /** * * @param object * @param property * @param types * @return */ function spy(object : sinon.Spy0, property : any, types : any): any; /** * */ namespace spy{ /** * * @return */ function reset(): sinon.spy.ResetRet; /** * */ export var called : boolean; /** * */ export var notCalled : boolean; /** * */ export var calledOnce : boolean; /** * */ export var calledTwice : boolean; /** * */ export var calledThrice : boolean; /** * */ export var callCount : number; /** * */ export var firstCall : /*no type*/{}; /** * */ export var args : Array<any>; /** * */ export var returnValues : Array<any>; /** * */ export var thisValues : Array<any>; /** * */ export var exceptions : Array<any>; /** * */ export var callIds : Array<any>; /** * */ export var stacks : Array<any>; /** * * @param func * @param spyLength * @return */ function create(func : (() => void) | {}, spyLength : any): () => void; /** * * @param func * @param thisValue * @param args * @return */ function invoke(func : any, thisValue : any, args : any): any; /** * */ export var invoking : boolean; /** * * @param name * @return */ function named(name : any): sinon.spy.NamedRet; /** * * @param i * @return */ function getCall(i : number): /* sinon.spy.firstCall */ any; /** * * @return */ function getCalls(): sinon.spy.GetCallsRet; /** * * @param spyFn * @return */ function calledBefore(spyFn : any): boolean; /** * * @param spyFn * @return */ function calledAfter(spyFn : any): boolean; /** * * @return */ function withArgs(): sinon.spy.WithArgsRet; /** * */ export var fakes : Array<sinon.spy.FakesI>; /** * * @param args * @param strict * @return */ function matches(args : any, strict : any): boolean; /** * * @param format * @return */ function printf(format : any): string; /** * */ namespace formatters{ /** * * @param spyInstance * @return */ function c(spyInstance : any): boolean; /** * */ function c(); /** * * @param spyInstance */ function n(spyInstance : any): void; /** * */ interface C { /** * * @param spyInstance * @return */ new (spyInstance : any): string; } /** * * @param spyInstance * @return */ function t(spyInstance : any): string; } /** * */ interface formatters { /** * * @param spyInstance * @param args * @return */ "*"(spyInstance : any, args : any): string; } } /** * */ namespace behavior{ /** * * @param stub * @return */ function create(stub : any): sinon.behavior.CreateRet; /** * */ function create(); /** * * @return */ function isPresent(): /* !this.exception */ any; /** * * @param context * @param args * @return */ function invoke(context : any, args : any): /* !this.returnValue */ any; /** * * @param index */ function onCall(index : any): void; /** * */ function onFirstCall(): void; /** * */ function onSecondCall(): void; /** * */ function onThirdCall(): void; /** * */ function withArgs(): void; /** * * @param pos * @return */ function callsArg(pos : any): /* !this */ any; /** * */ export var callArgAt : number; /** * */ export var callbackArguments : Array<any>; /** * */ export var callbackAsync : boolean; /** * * @param pos * @param context * @return */ function callsArgOn(pos : any, context : any): /* !this */ any; /** * * @param pos * @return */ function callsArgWith(pos : any): /* !this */ any; /** * * @param pos * @param context * @return */ function callsArgOnWith(pos : any, context : any): /* !this */ any; /** * * @return */ function yields(): /* !this */ any; /** * * @return */ function yieldsRight(): /* !this */ any; /** * * @param context * @return */ function yieldsOn(context : any): /* !this */ any; /** * * @param prop * @return */ function yieldsTo(prop : any): /* !this */ any; /** * * @param prop * @param context * @return */ function yieldsToOn(prop : any, context : any): /* !this */ any; /** * * @param error * @param message * @return */ function throws(error : any, message : any): /* !this */ any; /** * * @param value * @return */ function returns(value : any): /* !this */ any; /** * */ export var returnValueDefined : boolean; /** * * @param pos * @return */ function returnsArg(pos : any): /* !this */ any; /** * * @return */ function returnsThis(): /* !this */ any; /** * */ export var returnThis : boolean; /** * */ export var throwsException : /* sinon.behavior.throws */ any; } /** * */ namespace expectation{ /** * */ export var minCalls : number; /** * */ export var maxCalls : number; /** * * @param methodName * @return */ function create(methodName : string): sinon.expectation.CreateRet; /** * */ function create(); /** * * @param func * @param thisValue * @param args */ function invoke(func : any, thisValue : any, args : any): void; /** * * @param num * @return */ function atLeast(num : number): /* !this */ any; /** * */ export var limitsSet : boolean; /** * * @param num * @return */ function atMost(num : number): /* !this */ any; /** * * @return */ function never(): /* sinon.expectation */ any; /** * * @return */ function once(): /* sinon.expectation */ any; /** * * @return */ function twice(): /* sinon.expectation */ any; /** * * @return */ function thrice(): /* sinon.expectation */ any; /** * * @param num * @return */ function exactly(num : number): /* sinon.expectation */ any; /** * * @return */ function met(): boolean; /** * * @param thisValue * @param args */ function verifyCallAllowed(thisValue : any, args : any): void; /** * */ export var failed : boolean; /** * * @param thisValue * @param args * @return */ function allowsCall(thisValue : any, args : sinon.expectation.AllowsCall1): boolean; /** * * @return */ function withArgs(): /* !this */ any; /** * */ export var expectedArguments : Array<any>; /** * * @return */ function withExactArgs(): /* !this */ any; /** * */ export var expectsExactArgCount : boolean; /** * * @param thisValue * @return */ function on(thisValue : any): /* !this */ any; /** * * @return */ function toString(): string; /** * * @return */ function verify(): boolean; /** * * @param message */ function pass(message : string): void; /** * * @param message */ function fail(message : string): void; /** * */ export var invoking : boolean; /** * */ export var called : boolean; /** * */ export var callCount : number; /** * */ export var notCalled : boolean; /** * */ export var calledOnce : boolean; /** * */ export var calledTwice : boolean; /** * */ export var calledThrice : boolean; /** * */ export var firstCall : /* sinon.spy.firstCall */ any; /** * */ export var secondCall : /* sinon.spy.firstCall */ any; /** * */ export var thirdCall : /* sinon.spy.firstCall */ any; /** * */ export var lastCall : /* sinon.spy.firstCall */ any; } /** * * @param object * @return */ function mock(object : any): any; /** * */ function mock(); /** * */ namespace mock{ /** * * @param object * @return */ function create(object : any): sinon.mock.CreateRet; /** * */ function create(); /** * * @param method * @return */ function expects(method : any): any; /** * */ function expects(); /** * */ namespace expectations{ } /** * */ export var proxies : Array<any>; /** * */ function restore(): void; /** * * @return */ function verify(): boolean; /** * * @param method * @param thisValue * @param args */ function invokeMethod(method : any, thisValue : any, args : sinon.mock.InvokeMethod2): void; } /** * */ namespace collection{ /** * */ function verify(): void; /** * */ export var fakes : Array<any>; /** * */ namespace fakes{ } /** * */ function restore(): void; /** * */ function reset(): void; /** * */ function verifyAndRestore(): void; /** * * @param fake * @return */ function add(fake : any): any; /** * * @return */ function spy(): any; /** * * @param object * @param property * @param value * @return */ function stub(object : sinon.collection.Stub0, property : any, value : any): sinon.collection.StubRet; /** * * @return */ function mock(): any; /** * */ function mock(); /** * * @param obj * @return */ function inject(obj : sinon.collection.Inject0): sinon.collection.Inject0; } /** * * @return */ function useFakeTimers(): sinon.UseFakeTimersRet; /** * */ namespace clock{ /** * * @param now * @return */ function create(now : any): /* sinon.fakeServerWithClock.clock */ any; } /** * */ var timers : { /** * */ Date : Date; } /** * */ interface Event { /** * * @param type * @param bubbles * @param cancelable * @param target */ new (type : string, bubbles : boolean, cancelable : boolean, target : /* sinon.ProgressEvent.target */ any); /** * * @param type * @param bubbles * @param cancelable * @param target */ initEvent(type : string, bubbles : boolean, cancelable : boolean, target : sinon.Event.prototype.InitEvent3): void; /** * */ stopPropagation(): void; /** * */ preventDefault(): void; /** * */ type : string; /** * */ bubbles : boolean; /** * */ cancelable : boolean; /** * */ target : { /** * */ async : boolean; /** * */ errorFlag : boolean; /** * */ sendFlag : boolean; /** * */ responseText : string; /** * */ response : string; /** * */ aborted : boolean; /** * */ requestHeaders : { /** * */ "Content-Type" : string; } /** * */ progress : number; /** * */ status : number; /** * */ statusText : string; /** * */ uploadProgress : /*no type*/{}; /** * */ open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ readyStateChange : /* sinon.FakeXMLHttpRequest.prototype.readyStateChange */ any; /** * */ setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; } /** * */ defaultPrevented : boolean; } /** * */ interface ProgressEvent extends sinon.Event { /** * * @param type * @param progressEventRaw * @param target */ new (type : string, progressEventRaw : /* sinon.ProgressEvent.!1 */ any, target : /* sinon.ProgressEvent.target */ any); /** * */ type : string; /** * */ bubbles : boolean; /** * */ cancelable : boolean; /** * */ defaultPrevented : boolean; /** * */ target : { /** * */ async : boolean; /** * */ errorFlag : boolean; /** * */ sendFlag : boolean; /** * */ responseText : string; /** * */ response : string; /** * */ aborted : boolean; /** * */ progress : number; /** * */ status : number; /** * */ statusText : string; /** * */ open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ readyStateChange : /* sinon.FakeXMLHttpRequest.prototype.readyStateChange */ any; /** * */ setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ requestHeaders : /* sinon.FakeXMLHttpRequest.prototype.requestHeaders */ any; /** * */ responseHeaders : any; /** * */ error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ uploadProgress : /* sinon.FakeXMLHttpRequest.prototype.uploadProgress */ any; /** * */ downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; } /** * */ loaded : number; /** * */ total : number; /** * */ lengthComputable : boolean; } /** * */ interface CustomEvent { /** * * @param type * @param customData * @param target * @return */ new (type : string, customData : sinon.CustomEvent1, target : any): CustomEvent; } /** * */ namespace EventTarget{ /** * * @param event * @param listener */ function addEventListener(event : any, listener : any): void; /** * * @param event * @param listener * @return */ function removeEventListener(event : any, listener : any): Array<any>; /** * * @param event * @return */ function dispatchEvent(event : /* sinon.EventTarget.ProgressEvent */ any): boolean; /** * */ namespace eventListeners{ } } /** * */ export var loaded : number; /** * */ export var total : number; /** * */ export var lengthComputable : boolean; /** * */ function log(): void; /** * * @param label * @param err */ function logError(label : string, err : sinon.LogError1): void; /** * */ namespace logError{ /** * When set to true, any errors logged will be thrown immediately; * If set to false, the errors will be thrown in separate execution frame. */ export var useImmediateExceptions : boolean; /** * wrap realSetTimeout with something we can stub in tests * @param func * @param timeout */ function setTimeout(func : sinon.logError.SetTimeout0, timeout : number): void; } /** * */ namespace xdr{ /** * */ namespace XDomainRequest{ /** * */ namespace prototype{ /** * */ export var responseText : string; /** * */ export var sendFlag : boolean; /** * */ export var readyState : number; /** * */ export var errorFlag : boolean; /** * */ export var aborted : boolean; /** * */ export var status : number; /** * */ export var isTimeout : boolean; /** * */ export var toString : /* !proto.toString */ any; /** * */ export var addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ export var removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ export var dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ export var eventListeners : /* sinon.EventTarget.eventListeners */ any; /** * */ export var open : /* sinon.FakeXDomainRequest.prototype.open */ any; /** * */ export var readyStateChange : /* sinon.FakeXDomainRequest.prototype.readyStateChange */ any; /** * */ export var send : /* sinon.FakeXDomainRequest.prototype.send */ any; /** * */ export var abort : /* sinon.FakeXDomainRequest.prototype.abort */ any; /** * */ export var setResponseBody : /* sinon.FakeXDomainRequest.prototype.setResponseBody */ any; /** * */ export var respond : /* sinon.FakeXDomainRequest.prototype.respond */ any; /** * */ export var simulatetimeout : /* sinon.FakeXDomainRequest.prototype.simulatetimeout */ any; } /** * */ export var UNSENT : number; /** * */ export var OPENED : number; /** * */ export var LOADING : number; /** * */ export var DONE : number; /** * */ export var toString : /* !proto.toString */ any; /** * */ export var restore : /* sinon.FakeXDomainRequest.restore */ any; /** * */ export var onCreate : /* sinon.FakeXDomainRequest.onCreate */ any; } /** * */ export var supportsXDR : boolean; /** * */ export var workingXDR : boolean; /** * */ export var GlobalXDomainRequest : /* sinon.FakeXDomainRequest */ any; } /** * * @return */ function useFakeXDomainRequest(): () => void; /** * */ interface FakeXDomainRequest { /** * */ new (); /** * * @param method * @param url */ open(method : any, url : any): void; /** * */ responseText : string; /** * */ sendFlag : boolean; /** * * @param state */ readyStateChange(state : number): void; /** * */ readyState : number; /** * * @param data */ send(data : any): void; /** * */ errorFlag : boolean; /** * */ abort(): void; /** * */ aborted : boolean; /** * * @param body */ setResponseBody(body : string): void; /** * * @param status * @param contentType * @param body */ respond(status : any, contentType : any, body : any): void; /** * */ status : number; /** * */ simulatetimeout(): void; /** * */ isTimeout : boolean; /** * */ addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ eventListeners : /* sinon.EventTarget.eventListeners */ any; /** * * @param keepOnCreate */ restore(keepOnCreate : any): void; /** * */ UNSENT : number; /** * */ OPENED : number; /** * */ LOADING : number; /** * */ DONE : number; /** * * @param xhrObj */ onCreate(xhrObj : /* sinon.FakeXDomainRequest.FakeXMLHttpRequest */ any): void; } /** * */ namespace xhr{ /** * */ namespace XMLHttpRequest{ /** * */ export var useFilters : boolean; /** * */ export var parseXML : /*no type*/{}; /** * */ var statusCodes : { } /** * */ namespace prototype{ /** * */ export var async : boolean; /** * */ export var errorFlag : boolean; /** * */ export var sendFlag : boolean; /** * */ export var responseText : string; /** * */ export var response : string; /** * */ export var aborted : boolean; /** * */ export var progress : number; /** * */ export var status : number; /** * */ export var statusText : string; /** * */ export var toString : /* !proto.toString */ any; /** * */ export var open : /* sinon.FakeXMLHttpRequest.prototype.open */ any; /** * */ export var readyStateChange : /* sinon.FakeXMLHttpRequest.prototype.readyStateChange */ any; /** * */ export var setRequestHeader : /* sinon.FakeXMLHttpRequest.prototype.setRequestHeader */ any; /** * */ export var setResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.setResponseHeaders */ any; /** * */ export var send : /* sinon.FakeXMLHttpRequest.prototype.send */ any; /** * */ export var abort : /* sinon.FakeXMLHttpRequest.prototype.abort */ any; /** * */ export var requestHeaders : /* sinon.FakeXMLHttpRequest.prototype.requestHeaders */ any; /** * */ export var responseHeaders : any; /** * */ export var error : /* sinon.FakeXMLHttpRequest.prototype.error */ any; /** * */ export var getResponseHeader : /* sinon.FakeXMLHttpRequest.prototype.getResponseHeader */ any; /** * */ export var getAllResponseHeaders : /* sinon.FakeXMLHttpRequest.prototype.getAllResponseHeaders */ any; /** * */ export var setResponseBody : /* sinon.FakeXMLHttpRequest.prototype.setResponseBody */ any; /** * */ export var respond : /* sinon.FakeXMLHttpRequest.prototype.respond */ any; /** * */ export var uploadProgress : /* sinon.FakeXMLHttpRequest.prototype.uploadProgress */ any; /** * */ export var downloadProgress : /* sinon.FakeXMLHttpRequest.prototype.downloadProgress */ any; /** * */ export var uploadError : /* sinon.FakeXMLHttpRequest.prototype.uploadError */ any; /** * */ export var addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ export var removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ export var dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ export var eventListeners : /* sinon.EventTarget.eventListeners */ any; } /** * */ export var UNSENT : number; /** * */ export var OPENED : number; /** * */ export var HEADERS_RECEIVED : number; /** * */ export var LOADING : number; /** * */ export var DONE : number; /** * */ export var toString : /* !proto.toString */ any; /** * */ export var onCreate : /* sinon.FakeXDomainRequest.onCreate */ any; /** * */ export var filters : /* sinon.FakeXMLHttpRequest.filters */ any; /** * */ export var addFilter : /* sinon.FakeXMLHttpRequest.addFilter */ any; /** * */ export var defake : /*no type*/{}; /** * */ export var restore : /* sinon.FakeXMLHttpRequest.restore */ any; } /** * */ interface GlobalActiveXObject { /** * * @param objId * @return */ new (objId : string): /* sinon.xhr.GlobalActiveXObject */ any; } /** * */ export var supportsActiveX : boolean; /** * */ export var supportsXHR : boolean; /** * */ export var supportsCORS : boolean; /** * */ export var GlobalXMLHttpRequest : /* sinon.FakeXMLHttpRequest */ any; /** * */ export var workingXHR : /* sinon.FakeXMLHttpRequest */ any; } /** * * @return */ function useFakeXMLHttpRequest(): () => void; /** * Note that for FakeXMLHttpRequest to work pre ES5 * we lose some of the alignment with the spec. * To ensure as close a match as possible, * set responseType before calling open, send or respond; */ interface FakeXMLHttpRequest { /** * */ new (); /** * */ async : boolean; /** * * @param method * @param url * @param async * @param username * @param password */ open(method : any, url : any, async : any, username : any, password : any): void; /** * * @param state */ readyStateChange(state : any): void; /** * * @param header * @param value */ setRequestHeader(header : any, value : any): void; /** * Helps testing * @param headers */ setResponseHeaders(headers : any): void; /** * Currently treats ALL data as a DOMString (i.e. no Document) * @param data */ send(data : any): void; /** * */ errorFlag : boolean; /** * */ sendFlag : boolean; /** * */ responseText : string; /** * */ response : string; /** * */ abort(): void; /** * */ aborted : boolean; /** * */ requestHeaders : { /** * */ "Content-Type" : string; } /** * */ error(): void; /** * * @param header * @return */ getResponseHeader(header : string): /* !this.responseHeaders.<i> */ any; /** * * @return */ getAllResponseHeaders(): string; /** * * @param body */ setResponseBody(body : string): void; /** * */ progress : number; /** * * @param status * @param headers * @param body */ respond(status : any, headers : any, body : any): void; /** * */ status : number; /** * */ statusText : string; /** * * @param progressEventRaw */ uploadProgress(progressEventRaw : any): void; /** * * @param progressEventRaw */ downloadProgress(progressEventRaw : any): void; /** * * @param error */ uploadError(error : any): void; /** * */ addEventListener : /* sinon.EventTarget.addEventListener */ any; /** * */ removeEventListener : /* sinon.EventTarget.removeEventListener */ any; /** * */ dispatchEvent : /* sinon.EventTarget.dispatchEvent */ any; /** * */ eventListeners : /* sinon.EventTarget.eventListeners */ any; /** * */ filters : Array<any>; /** * * @param fn */ addFilter(fn : any): void; /** * * @param fakeXhr * @param xhrArgs */ defake(fakeXhr : sinon.FakeXMLHttpRequest.Defake0, xhrArgs : sinon.FakeXMLHttpRequest.Defake1): void; /** * */ useFilters : boolean; /** * * @param text * @return */ parseXML(text : string): sinon.FakeXMLHttpRequest.ParseXMLRet; /** * */ statusCodes : { } /** * * @param keepOnCreate */ restore(keepOnCreate : any): void; /** * */ UNSENT : number; /** * */ OPENED : number; /** * */ HEADERS_RECEIVED : number; /** * */ LOADING : number; /** * */ DONE : number; /** * */ upload : { /** * */ eventListeners : { /** * */ abort : Array<any>; /** * */ error : Array<any>; /** * */ load : Array<any>; /** * */ loadend : Array<any>; /** * */ progress : Array<any>; } } /** * */ responseType : string; /** * */ withCredentials : boolean; /** * */ onreadystatechange(): void; /** * */ onSend(): void; } /** * */ namespace fakeServer{ /** * * @param config * @return */ function create(config : any): sinon.fakeServer.CreateRet; /** * * @param config */ function configure(config : any): void; /** * * @param xhrObj */ function addRequest(xhrObj : any): void; /** * */ export var responding : boolean; /** * * @param request * @return */ function getHTTPMethod(request : sinon.fakeServer.GetHTTPMethod0): /* error */ any; /** * * @param xhr */ function handleRequest(xhr : /* sinon.fakeServer.queue.<i> */ any): void; /** * */ export var queue : Array<sinon.fakeServer.QueueI>; /** * * @param response * @param undefined * @param undefined * @param request */ function log(response : sinon.fakeServer.Log0, param2 : any, param3 : /* string] */ any, request : /* sinon.fakeServer.queue.<i> */ any): void; /** * * @param method * @param url * @param body */ function respondWith(method : any, url : any, body : any): void; /** * */ export var response : Array<any>; /** * */ export var responses : Array<sinon.fakeServer.ResponsesI>; /** * */ function respond(): void; /** * * @param request */ function processRequest(request : /* sinon.fakeServer.queue.<i> */ any): void; /** * * @return */ function restore(): /* !this.xhr.restore */ any; /** * */ export var xhr : /* sinon.FakeXMLHttpRequest */ any; } /** * */ interface fakeServerWithClock { /** * * @param xhr */ addRequest(xhr : any): void; /** * */ respond(): void; /** * * @return */ restore(): (keepOnCreate : any) => void; /** * */ clock : { /** * * @param func * @param timeout * @return */ setTimeout(func : any, timeout : any): number; /** * * @param timerId */ clearTimeout(timerId : any): void; /** * * @param func * @param timeout * @return */ setInterval(func : any, timeout : any): number; /** * * @param timerId */ clearInterval(timerId : any): void; /** * * @param func * @return */ setImmediate(func : any): number; /** * * @param timerId */ clearImmediate(timerId : any): void; /** * */ duringTick : boolean; /** * * @param ms * @return */ tick(ms : number): any; /** * */ reset(): void; /** * * @param now */ setSystemTime(now : any): void; /** * */ uninstall(): void; /** * */ restore : /* sinon.fakeServerWithClock.clock.uninstall */ any; } /** * */ resetClock : boolean; /** * */ longestTimeout : number; } /** * */ namespace assert{ /** * */ export var failException : string; /** * * @param message */ function fail(message : string): void; /** * */ function pass(): void; /** * */ function callOrder(): void; /** * * @param method * @param count */ function callCount(method : any, count : any): void; /** * * @param target * @param options * @return */ function expose(target : sinon.assert.Expose0, options : any): sinon.assert.Expose0; /** * * @param actual * @param expectation */ function match(actual : any, expectation : any): void; } /** * */ interface Float32Array { } } declare module 'sinon' { export = sinon; //legacy ts module export }
the_stack
import type { InjectedOptionsParam, InjectedDependenciesParam, PineTypedResult, } from '..'; import type { Device } from '../types/models'; import { isNotFoundResponse, treatAsMissingDevice, withSupervisorLockedError, } from '../util'; import { ensureVersionCompatibility } from '../util/device-os-version'; import { toWritable } from '../util/types'; // The min version where /apps API endpoints are implemented is 1.8.0 but we'll // be accepting >= 1.8.0-alpha.0 instead. This is a workaround for a published 1.8.0-p1 // prerelease supervisor version, which precedes 1.8.0 but comes after 1.8.0-alpha.0 // according to semver. export const MIN_SUPERVISOR_APPS_API = '1.8.0-alpha.0'; export const MIN_SUPERVISOR_MC_API = '7.0.0'; // Degraded network, slow devices, compressed docker binaries and any combination of these factors // can cause proxied device requests to surpass the default timeout (currently 30s). This was // noticed during tests and the endpoints that resulted in container management actions were // affected in particular. export const CONTAINER_ACTION_ENDPOINT_TIMEOUT = 50000; export interface SupervisorStatus { api_port: string; ip_address: string; os_version: string; supervisor_version: string; update_pending: boolean; update_failed: boolean; update_downloaded: boolean; status?: string | null; commit?: string | null; download_progress?: string | null; } export const getSupervisorApiHelper = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { request, // Do not destructure sub-modules, to allow lazy loading only when needed. sdkInstance, } = deps; const { apiUrl } = opts; const getId = (uuidOrId: string | number) => sdkInstance.models.device._getId(uuidOrId); const exports = { /** * @summary Ping a device * @name ping * @public * @function * @memberof balena.models.device * * @description * This is useful to signal that the supervisor is alive and responding. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.ping('7cf02a6'); * * @example * balena.models.device.ping(123); * * @example * balena.models.device.ping('7cf02a6', function(error) { * if (error) throw error; * }); */ ping: async (uuidOrId: string | number): Promise<void> => { const deviceOptions = { $select: 'id', $expand: { belongs_to__application: { $select: 'id' } }, } as const; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; await request.send({ method: 'POST', url: '/supervisor/ping', baseUrl: apiUrl, body: { method: 'GET', deviceId: device.id, appId: device.belongs_to__application[0].id, }, }); }, /** * @summary Get application container information * @name getApplicationInfo * @public * @function * @memberof balena.models.device * * @deprecated * @description * This is not supported on multicontainer devices, and will be removed in a future major release * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Object} - application info * @returns {Promise} * * @example * balena.models.device.getApplicationInfo('7cf02a6').then(function(appInfo) { * console.log(appInfo); * }); * * @example * balena.models.device.getApplicationInfo(123).then(function(appInfo) { * console.log(appInfo); * }); * * @example * balena.models.device.getApplicationInfo('7cf02a6', function(error, appInfo) { * if (error) throw error; * console.log(appInfo); * }); */ getApplicationInfo: async ( uuidOrId: string | number, ): Promise<{ appId: string; commit: string; containerId: string; env: { [key: string]: string | number }; imageId: string; }> => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' } }, } as const; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_APPS_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; const { body } = await request.send({ method: 'POST', url: `/supervisor/v1/apps/${appId}`, baseUrl: apiUrl, body: { deviceId: device.id, appId, method: 'GET', }, }); return body; }, /** * @summary Identify device * @name identify * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.identify('7cf02a6'); * * @example * balena.models.device.identify(123); * * @example * balena.models.device.identify('7cf02a6', function(error) { * if (error) throw error; * }); */ identify: async (uuidOrId: string | number): Promise<void> => { const device = await sdkInstance.models.device.get(uuidOrId, { $select: 'uuid', }); await request.send({ method: 'POST', url: '/supervisor/v1/blink', baseUrl: apiUrl, body: { uuid: device.uuid, }, }); }, /** * @summary Start application on device * @name startApplication * @public * @function * @memberof balena.models.device * * @deprecated * @description * This is not supported on multicontainer devices, and will be removed in a future major release * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - application container id * @returns {Promise} * * @example * balena.models.device.startApplication('7cf02a6').then(function(containerId) { * console.log(containerId); * }); * * @example * balena.models.device.startApplication(123).then(function(containerId) { * console.log(containerId); * }); * * @example * balena.models.device.startApplication('7cf02a6', function(error, containerId) { * if (error) throw error; * console.log(containerId); * }); */ startApplication: async (uuidOrId: string | number): Promise<void> => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' as const } }, }; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_APPS_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; const { body } = await request.send({ method: 'POST', url: `/supervisor/v1/apps/${appId}/start`, baseUrl: apiUrl, body: { deviceId: device.id, appId, }, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); return body.containerId; }, /** * @summary Stop application on device * @name stopApplication * @public * @function * @memberof balena.models.device * * @deprecated * @description * This is not supported on multicontainer devices, and will be removed in a future major release * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - application container id * @returns {Promise} * * @example * balena.models.device.stopApplication('7cf02a6').then(function(containerId) { * console.log(containerId); * }); * * @example * balena.models.device.stopApplication(123).then(function(containerId) { * console.log(containerId); * }); * * @example * balena.models.device.stopApplication('7cf02a6', function(error, containerId) { * if (error) throw error; * console.log(containerId); * }); */ stopApplication: (uuidOrId: string | number): Promise<void> => withSupervisorLockedError(async () => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' as const } }, }; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_APPS_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; const { body } = await request.send({ method: 'POST', url: `/supervisor/v1/apps/${appId}/stop`, baseUrl: apiUrl, body: { deviceId: device.id, appId, }, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); return body.containerId; }), /** * @summary Reboot device * @name reboot * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options] - options * @param {Boolean} [options.force=false] - override update lock * @returns {Promise} * * @example * balena.models.device.reboot('7cf02a6'); * * @example * balena.models.device.reboot(123); * * @example * balena.models.device.reboot('7cf02a6', function(error) { * if (error) throw error; * }); */ reboot: ( uuidOrId: string | number, options: { force?: boolean }, ): Promise<void> => withSupervisorLockedError(async () => { if (options == null) { options = {}; } try { const deviceId = await getId(uuidOrId); const { body } = await request.send({ method: 'POST', url: '/supervisor/v1/reboot', baseUrl: apiUrl, body: { deviceId, data: { force: Boolean(options?.force), }, }, }); return body; } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingDevice(uuidOrId, err); } throw err; } }), /** * @summary Shutdown device * @name shutdown * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options] - options * @param {Boolean} [options.force=false] - override update lock * @returns {Promise} * * @example * balena.models.device.shutdown('7cf02a6'); * * @example * balena.models.device.shutdown(123); * * @example * balena.models.device.shutdown('7cf02a6', function(error) { * if (error) throw error; * }); */ shutdown: ( uuidOrId: string | number, options: { force?: boolean }, ): Promise<void> => withSupervisorLockedError(async () => { if (options == null) { options = {}; } const deviceOptions = { $select: 'id', $expand: { belongs_to__application: { $select: 'id' } }, } as const; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; await request.send({ method: 'POST', url: '/supervisor/v1/shutdown', baseUrl: apiUrl, body: { deviceId: device.id, appId: device.belongs_to__application[0].id, data: { force: Boolean(options?.force), }, }, }); }), /** * @summary Purge device * @name purge * @public * @function * @memberof balena.models.device * * @description * This function clears the user application's `/data` directory. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.purge('7cf02a6'); * * @example * balena.models.device.purge(123); * * @example * balena.models.device.purge('7cf02a6', function(error) { * if (error) throw error; * }); */ purge: (uuidOrId: string | number): Promise<void> => withSupervisorLockedError(async () => { const deviceOptions = { $select: 'id', $expand: { belongs_to__application: { $select: 'id' } }, } as const; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; await request.send({ method: 'POST', url: '/supervisor/v1/purge', baseUrl: apiUrl, body: { deviceId: device.id, appId: device.belongs_to__application[0].id, data: { appId: device.belongs_to__application[0].id, }, }, }); }), /** * @summary Trigger an update check on the supervisor * @name update * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options] - options * @param {Boolean} [options.force=false] - override update lock * @returns {Promise} * * @example * balena.models.device.update('7cf02a6', { * force: true * }); * * @example * balena.models.device.update(123, { * force: true * }); * * @example * balena.models.device.update('7cf02a6', { * force: true * }, function(error) { * if (error) throw error; * }); */ async update( uuidOrId: string | number, options: { force?: boolean }, ): Promise<void> { if (options == null) { options = {}; } const deviceOptions = { $select: 'id', $expand: { belongs_to__application: { $select: 'id' } }, } as const; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; await request.send({ method: 'POST', url: '/supervisor/v1/update', baseUrl: apiUrl, body: { deviceId: device.id, appId: device.belongs_to__application[0].id, data: { force: Boolean(options?.force), }, }, }); }, /** * @summary Get the supervisor state on a device * @name getSupervisorState * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.getSupervisorState('7cf02a6').then(function(state) { * console.log(state); * }); * * @example * balena.models.device.getSupervisorState(123).then(function(state) { * console.log(state); * }); * * @example * balena.models.device.getSupervisorState('7cf02a6', function(error, state) { * if (error) throw error; * console.log(state); * }); */ getSupervisorState: async ( uuidOrId: string | number, ): Promise<SupervisorStatus> => { const { uuid } = await sdkInstance.models.device.get(uuidOrId, { $select: 'uuid', }); const { body } = await request.send({ method: 'POST', url: '/supervisor/v1/device', baseUrl: apiUrl, body: { uuid, method: 'GET', }, }); return body; }, /** * @summary Start a service on a device * @name startService * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} imageId - id of the image to start * @returns {Promise} * * @example * balena.models.device.startService('7cf02a6', 123).then(function() { * ... * }); * * @example * balena.models.device.startService(1, 123).then(function() { * ... * }); * * @example * balena.models.device.startService('7cf02a6', 123, function(error) { * if (error) throw error; * ... * }); */ startService: async ( uuidOrId: string | number, imageId: number, ): Promise<void> => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' as const } }, }; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_MC_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; await request.send({ method: 'POST', url: `/supervisor/v2/applications/${appId}/start-service`, baseUrl: apiUrl, body: { deviceId: device.id, appId, data: { appId, imageId, }, }, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); }, /** * @summary Stop a service on a device * @name stopService * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} imageId - id of the image to stop * @returns {Promise} * * @example * balena.models.device.stopService('7cf02a6', 123).then(function() { * ... * }); * * @example * balena.models.device.stopService(1, 123).then(function() { * ... * }); * * @example * balena.models.device.stopService('7cf02a6', 123, function(error) { * if (error) throw error; * ... * }); */ stopService: (uuidOrId: string | number, imageId: number): Promise<void> => withSupervisorLockedError(async () => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' as const } }, }; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_MC_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; await request.send({ method: 'POST', url: `/supervisor/v2/applications/${appId}/stop-service`, baseUrl: apiUrl, body: { deviceId: device.id, appId, data: { appId, imageId, }, }, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); }), /** * @summary Restart a service on a device * @name restartService * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} imageId - id of the image to restart * @returns {Promise} * * @example * balena.models.device.restartService('7cf02a6', 123).then(function() { * ... * }); * * @example * balena.models.device.restartService(1, 123).then(function() { * ... * }); * * @example * balena.models.device.restartService('7cf02a6', 123, function(error) { * if (error) throw error; * ... * }); */ restartService: ( uuidOrId: string | number, imageId: number, ): Promise<void> => withSupervisorLockedError(async () => { const deviceOptions = { $select: toWritable(['id', 'supervisor_version'] as const), $expand: { belongs_to__application: { $select: 'id' as const } }, }; const device = (await sdkInstance.models.device.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_MC_API, 'supervisor', ); const appId = device.belongs_to__application[0].id; await request.send({ method: 'POST', url: `/supervisor/v2/applications/${appId}/restart-service`, baseUrl: apiUrl, body: { deviceId: device.id, appId, data: { appId, imageId, }, }, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); }), }; return exports; };
the_stack
import { Directive, NgModule, Input, QueryList, Output, EventEmitter, AfterContentInit, ContentChildren, OnDestroy, HostBinding } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { IgxRadioComponent, RadioLabelPosition, IChangeRadioEventArgs } from '../../radio/radio.component'; import { IgxRippleModule } from '../ripple/ripple.directive'; import { takeUntil } from 'rxjs/operators'; import { noop, Subject } from 'rxjs'; import { mkenum } from '../../core/utils'; import { DeprecateProperty } from '../../core/deprecateDecorators'; /** * Determines the Radio Group alignment */ export const RadioGroupAlignment = mkenum({ horizontal: 'horizontal', vertical: 'vertical' }); export type RadioGroupAlignment = typeof RadioGroupAlignment[keyof typeof RadioGroupAlignment]; let nextId = 0; /** * Radio group directive renders set of radio buttons. * * @igxModule IgxRadioModule * * @igxTheme igx-radio-theme * * @igxKeywords radiogroup, radio, button, input * * @igxGroup Data Entry & Display * * @remarks * The Ignite UI Radio Group allows the user to select a single option from an available set of options that are listed side by side. * * @example: * ```html * <igx-radio-group name="radioGroup"> * <igx-radio *ngFor="let item of ['Foo', 'Bar', 'Baz']" value="{{item}}"> * {{item}} * </igx-radio> * </igx-radio-group> * ``` */ @Directive({ exportAs: 'igxRadioGroup', selector: 'igx-radio-group, [igxRadioGroup]', providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: IgxRadioGroupDirective, multi: true }] }) export class IgxRadioGroupDirective implements AfterContentInit, ControlValueAccessor, OnDestroy { private static ngAcceptInputType_required: boolean | ''; private static ngAcceptInputType_disabled: boolean | ''; /** * Returns reference to the child radio buttons. * * @example * ```typescript * let radioButtons = this.radioGroup.radioButtons; * ``` */ @ContentChildren(IgxRadioComponent, { descendants: true }) public radioButtons: QueryList<IgxRadioComponent>; /** * Sets/gets the `value` attribute. * * @example * ```html * <igx-radio-group [value] = "'radioButtonValue'"></igx-radio-group> * ``` */ @Input() public get value(): any { return this._value; } public set value(newValue: any) { if (this._value !== newValue) { this._value = newValue; this._selectRadioButton(); } } /** * Sets/gets the `name` attribute of the radio group component. All child radio buttons inherits this name. * * @example * ```html * <igx-radio-group name = "Radio1"></igx-radio-group> * ``` */ @Input() public get name(): string { return this._name; } public set name(newValue: string) { if (this._name !== newValue) { this._name = newValue; this._setRadioButtonNames(); } } /** * Sets/gets whether the radio group is required. * * @remarks * If not set, `required` will have value `false`. * * @example * ```html * <igx-radio-group [required] = "true"></igx-radio-group> * ``` */ @Input() public get required(): boolean { return this._required; } public set required(value: boolean) { this._required = (value as any) === '' || value; this._setRadioButtonsRequired(); } /** * An @Input property that allows you to disable the radio group. By default it's false. * * @deprecated in version 12.2.0 * * @example * ```html * <igx-radio-group disabled></igx-radio-group> * ``` */ @DeprecateProperty('`disabled` is deprecated.') @Input() public get disabled(): boolean { return this._disabled; } public set disabled(value: boolean) { this._disabled = (value as any) === '' || value; this.setDisabledState(value); } /** * Sets/gets the position of the `label` in the child radio buttons. * * @deprecated in version 12.2.0 * * @remarks * If not set, `labelPosition` will have value `"after"`. * * @example * ```html * <igx-radio-group labelPosition = "before"></igx-radio-group> * ``` */ @DeprecateProperty('`labelPosition` is deprecated.') @Input() public get labelPosition(): RadioLabelPosition | string { return this._labelPosition; } public set labelPosition(newValue: RadioLabelPosition | string) { if (this._labelPosition !== newValue) { this._labelPosition = newValue === RadioLabelPosition.BEFORE ? RadioLabelPosition.BEFORE : RadioLabelPosition.AFTER; this._setRadioButtonLabelPosition(); } } /** * Sets/gets the selected child radio button. * * @example * ```typescript * let selectedButton = this.radioGroup.selected; * this.radioGroup.selected = selectedButton; * ``` */ @Input() public get selected() { return this._selected; } public set selected(selected: IgxRadioComponent | null) { if (this._selected !== selected) { this._selected = selected; this.value = selected ? selected.value : null; } } /** * An event that is emitted after the radio group `value` is changed. * * @remarks * Provides references to the selected `IgxRadioComponent` and the `value` property as event arguments. * * @example * ```html * <igx-radio-group (change)="handler($event)"></igx-radio-group> * ``` */ // eslint-disable-next-line @angular-eslint/no-output-native @Output() public readonly change: EventEmitter<IChangeRadioEventArgs> = new EventEmitter<IChangeRadioEventArgs>(); /** * The css class applied to the component. * * @hidden * @internal */ @HostBinding('class.igx-radio-group') public cssClass = 'igx-radio-group'; /** * Sets vertical alignment to the radio group, if `alignment` is set to `vertical`. * By default the alignment is horizontal. * * @example * ```html * <igx-radio-group alignment="vertical"></igx-radio-group> * ``` */ @HostBinding('class.igx-radio-group--vertical') private vertical = false; /** * Returns the alignment of the `igx-radio-group`. * ```typescript * @ViewChild("MyRadioGroup") * public radioGroup: IgxRadioGroupDirective; * ngAfterViewInit(){ * let radioAlignment = this.radioGroup.alignment; * } * ``` */ @Input() public get alignment(): RadioGroupAlignment { return this.vertical ? RadioGroupAlignment.vertical : RadioGroupAlignment.horizontal; } /** * Allows you to set the radio group alignment. * Available options are `RadioGroupAlignment.horizontal` (default) and `RadioGroupAlignment.vertical`. * ```typescript * public alignment = RadioGroupAlignment.vertical; * //.. * ``` * ```html * <igx-radio-group [alignment]="alignment"></igx-radio-group> * ``` */ public set alignment(value: RadioGroupAlignment) { this.vertical = value === RadioGroupAlignment.vertical; } /** * @hidden * @internal */ private _onChangeCallback: (_: any) => void = noop; /** * @hidden * @internal */ private _name = `igx-radio-group-${nextId++}`; /** * @hidden * @internal */ private _value: any = null; /** * @hidden * @internal */ private _selected: IgxRadioComponent | null = null; /** * @hidden * @internal */ private _isInitialized = false; /** * @hidden * @internal */ private _labelPosition: RadioLabelPosition | string = 'after'; /** * @hidden * @internal */ private _disabled = false; /** * @hidden * @internal */ private _required = false; /** * @hidden * @internal */ private destroy$ = new Subject<boolean>(); /** * @hidden * @internal */ public ngAfterContentInit() { // The initial value can possibly be set by NgModel and it is possible that // the OnInit of the NgModel occurs after the OnInit of this class. this._isInitialized = true; setTimeout(() => { this._initRadioButtons(); }); } /** * Sets the "checked" property value on the radio input element. * * @remarks * Checks whether the provided value is consistent to the current radio button. * If it is, the checked attribute will have value `true` and selected property will contain the selected `IgxRadioComponent`. * * @example * ```typescript * this.radioGroup.writeValue('radioButtonValue'); * ``` */ public writeValue(value: any) { this.value = value; } /** * Registers a function called when the control value changes. * * @hidden * @internal */ public registerOnChange(fn: (_: any) => void) { this._onChangeCallback = fn; } /** * @hidden * @internal */ public setDisabledState(isDisabled: boolean) { if (this.radioButtons) { this.radioButtons.forEach((button) => { button.setDisabledState(isDisabled); }); } } /** * Registers a function called when the control is touched. * * @hidden * @internal */ public registerOnTouched(fn: () => void) { if (this.radioButtons) { this.radioButtons.forEach((button) => { button.registerOnTouched(fn); }); } } /** * @hidden * @internal */ public ngOnDestroy(): void { this.destroy$.next(true); this.destroy$.complete(); } /** * @hidden * @internal */ private _initRadioButtons() { if (this.radioButtons) { const props = { name: this._name, labelPosition: this._labelPosition, disabled: this._disabled, required: this._required }; this.radioButtons.forEach((button) => { Object.assign(button, props); if (button.value === this._value) { button.checked = true; this._selected = button; } button.change.pipe(takeUntil(this.destroy$)).subscribe((ev) => this._selectedRadioButtonChanged(ev)); }); } } /** * @hidden * @internal */ private _selectedRadioButtonChanged(args: IChangeRadioEventArgs) { this.radioButtons.forEach((button) => { button.checked = button.id === args.radio.id; }); this._selected = args.radio; this._value = args.value; if (this._isInitialized) { this.change.emit(args); this._onChangeCallback(this.value); } } /** * @hidden * @internal */ private _setRadioButtonNames() { if (this.radioButtons) { this.radioButtons.forEach((button) => { button.name = this._name; }); } } /** * @hidden * @internal */ private _selectRadioButton() { if (this.radioButtons) { this.radioButtons.forEach((button) => { if (this._value === null) { // no value - uncheck all radio buttons if (button.checked) { button.checked = false; } } else { if (this._value === button.value) { // selected button if (this._selected !== button) { this._selected = button; } if (!button.checked) { button.select(); } } else { // non-selected button if (button.checked) { button.checked = false; } } } }); } } /** * @hidden * @internal */ private _setRadioButtonLabelPosition() { if (this.radioButtons) { this.radioButtons.forEach((button) => { button.labelPosition = this._labelPosition; }); } } /** * @hidden * @internal */ private _setRadioButtonsRequired() { if (this.radioButtons) { this.radioButtons.forEach((button) => { button.required = this._required; }); } } } /** * @hidden */ @NgModule({ declarations: [IgxRadioGroupDirective, IgxRadioComponent], exports: [IgxRadioGroupDirective, IgxRadioComponent], imports: [IgxRippleModule] }) export class IgxRadioModule {}
the_stack
import { Component, h, RenderableProps } from 'preact'; import * as accountApi from '../../api/account'; import { Input } from '../../components/forms'; import { translate, TranslateProps } from '../../decorators/translate'; import A from '../anchor/anchor'; import { Dialog } from '../dialog/dialog'; import { CopyableInput } from '../copy/Copy'; import { ExpandIcon } from '../icon/icon'; import { ProgressRing } from '../progressRing/progressRing'; import { FiatConversion } from '../rates/rates'; import { ArrowIn, ArrowOut, ArrowSelf, Edit, Save } from './components/icons'; import * as style from './transaction.css'; import * as parentStyle from './transactions.css'; interface State { transactionDialog: boolean; newNote: string; editMode: boolean; } interface TransactionProps extends accountApi.ITransaction { accountCode: string; index: number; explorerURL: string; } type Props = TransactionProps & TranslateProps; class Transaction extends Component<Props, State> { private input!: HTMLInputElement; private editButton!: HTMLButtonElement; public readonly state: State = { transactionDialog: false, newNote: this.props.note, editMode: !this.props.note, }; private parseTimeShort = time => { const options = { year: 'numeric', month: 'numeric', day: 'numeric', }; return new Date(Date.parse(time)).toLocaleString(this.context.i18n.language, options); } private showDetails = () => { this.setState({ transactionDialog: true, newNote: this.props.note, editMode: !this.props.note, }); } private hideDetails = () => { this.setState({ transactionDialog: false }); } private handleNoteInput = (e: Event) => { const target = e.target as HTMLInputElement; this.setState({ newNote: target.value }); } private handleEdit = (e: Event) => { e.preventDefault(); if (this.state.editMode && this.props.note !== this.state.newNote) { accountApi.postNotesTx(this.props.accountCode, { internalTxID: this.props.internalID, note: this.state.newNote, }) .catch(console.error); } this.focusEdit(); this.setState( ({ editMode }) => ({ editMode: !editMode }), this.focusEdit, ); } private focusEdit = () => { if (this.editButton) { this.editButton.blur(); } if (this.state.editMode && this.input) { this.input.scrollLeft = this.input.scrollWidth; this.input.focus(); } } private setInputRef = input => { this.input = input; } private setEditButtonRef = button => { this.editButton = button; } public render({ t, index, explorerURL, type, txID, amount, fee, feeRatePerKb, gas, nonce, vsize, size, weight, numConfirmations, numConfirmationsComplete, time, addresses, status, note = '', }: RenderableProps<Props>, { transactionDialog, newNote, editMode, }: State) { const arrow = type === 'receive' ? ( <ArrowIn /> ) : type === 'send' ? ( <ArrowOut /> ) : ( <ArrowSelf /> ); const sign = ((type === 'send') && '−') || ((type === 'receive') && '+') || null; const typeClassName = (type === 'send' && style.send) || (type === 'receive' && style.receive) || ''; const sDate = time ? this.parseTimeShort(time) : '---'; const statusText = { complete: t('transaction.status.complete'), pending: t('transaction.status.pending'), failed: t('transaction.status.failed'), }[status]; const progress = numConfirmations < numConfirmationsComplete ? (numConfirmations / numConfirmationsComplete) * 100 : 100; return ( <div className={[style.container, index === 0 ? style.first : ''].join(' ')}> <div className={[parentStyle.columns, style.row].join(' ')}> <div className={parentStyle.columnGroup}> <div className={parentStyle.type}>{arrow}</div> <div className={parentStyle.date}> <span className={style.columnLabel}> {t('transaction.details.date')}: </span> <span className={style.date}>{sDate}</span> </div> { note ? ( <div className={parentStyle.activity}> <span className={style.address}> {note} </span> </div> ) : ( <div className={parentStyle.activity}> <span className={style.label}> {t(type === 'receive' ? 'transaction.tx.received' : 'transaction.tx.sent')} </span> <span className={style.address}> {addresses[0]} {addresses.length > 1 && ( <span className={style.badge}> (+{addresses.length - 1}) </span> )} </span> </div> )} <div className={[parentStyle.action, parentStyle.hideOnMedium].join(' ')}> <button type="button" className={style.action} onClick={this.showDetails}> <ExpandIcon expand={!transactionDialog} /> </button> </div> </div> <div className={parentStyle.columnGroup}> <div className={parentStyle.status}> <span className={style.columnLabel}> {t('transaction.details.status')}: </span> <ProgressRing className="m-right-quarter" width={14} value={progress} isComplete={numConfirmations >= numConfirmationsComplete} /> <span className={style.status}>{statusText}</span> </div> <div className={parentStyle.fiat}> <span className={`${style.fiat} ${typeClassName}`}> <FiatConversion amount={amount} noAction>{sign}</FiatConversion> </span> </div> <div className={parentStyle.currency}> <span className={`${style.currency} ${typeClassName}`}> {sign}{amount.amount} {' '} <span className={style.currencyUnit}>{amount.unit}</span> </span> </div> <div className={[parentStyle.action, parentStyle.showOnMedium].join(' ')}> <button type="button" className={style.action} onClick={this.showDetails}> <ExpandIcon expand={!transactionDialog} /> </button> </div> </div> </div> { transactionDialog && ( <Dialog title="Transaction Details" onClose={this.hideDetails} slim medium> <form onSubmit={this.handleEdit} className={style.detailInput}> <label for="note">{t('note.title')}</label> <Input align="right" autoFocus={!editMode ? 'false' : 'true'} className={style.textOnlyInput} readOnly={!editMode} type="text" id="note" transparent placeholder={t('note.input.placeholder')} value={newNote} maxLength={256} onInput={this.handleNoteInput} getRef={this.setInputRef}/> <button className={style.editButton} onClick={this.handleEdit} title={t(`transaction.note.${editMode ? 'save' : 'edit'}`)} type="button" ref={this.setEditButtonRef}> {editMode ? <Save /> : <Edit />} </button> </form> <div className={style.detail}> <label>{t('transaction.details.type')}</label> <p>{arrow}</p> </div> <div className={style.detail}> <label>{t('transaction.confirmation')}</label> <p>{numConfirmations}</p> </div> <div className={style.detail}> <label>{t('transaction.details.status')}</label> <p className="flex flex-items-center"> <ProgressRing className="m-right-quarter" width={14} value={progress} isComplete={numConfirmations >= numConfirmationsComplete} /> <span className={style.status}> {statusText} { status === 'pending' && ( <span>({numConfirmations}/{numConfirmationsComplete})</span> ) } </span> </p> </div> <div className={style.detail}> <label>{t('transaction.details.date')}</label> <p>{sDate}</p> </div> <div className={style.detail}> <label>{t('transaction.details.fiat')}</label> <p> <span className={`${style.fiat} ${typeClassName}`}> <FiatConversion amount={amount} noAction>{sign}</FiatConversion> </span> </p> </div> <div className={style.detail}> <label>{t('transaction.details.amount')}</label> <p> <span className={`${style.currency} ${typeClassName}`}> {sign}{amount.amount} {' '} <span className={style.currencyUnit}>{amount.unit}</span> </span> </p> </div> <div className={style.detail}> <label>{t('transaction.fee')}</label> { fee && fee.amount ? ( <p title={feeRatePerKb.amount ? feeRatePerKb.amount + ' ' + feeRatePerKb.unit + '/Kb' : ''}> {fee.amount} {' '} <span className={style.currencyUnit}>{fee.unit}</span> </p> ) : ( <p>---</p> ) } </div> <div className={[style.detail, style.addresses].join(' ')}> <label>{t('transaction.details.address')}</label> <div className={style.detailAddresses}> { addresses.map((address) => ( <CopyableInput key={address} alignRight borderLess flexibleHeight className={style.detailAddress} value={address} /> )) } </div> </div> { gas ? ( <div className={style.detail}> <label>{t('transaction.gas')}</label> <p>{gas}</p> </div> ) : null } { nonce !== null ? ( <div className={style.detail}> <label>Nonce</label> <p>{nonce}</p> </div> ) : null } { weight ? ( <div className={style.detail}> <label>{t('transaction.weight')}</label> <p> {weight} {' '} <span className={style.currencyUnit}>WU</span> </p> </div> ) : null } { vsize ? ( <div className={style.detail}> <label>{t('transaction.vsize')}</label> <p> {vsize} {' '} <span className={style.currencyUnit}>b</span> </p> </div> ) : null } { size ? ( <div className={style.detail}> <label>{t('transaction.size')}</label> <p> {size} {' '} <span className={style.currencyUnit}>b</span> </p> </div> ) : null } <div className={style.detail}> <label>{t('transaction.explorer')}</label> <p className="text-break"> <A className={style.externalLink} href={ explorerURL + txID } title={t('transaction.explorerTitle')}>{txID}</A> </p> </div> </Dialog> ) } </div> ); } } const HOC = translate<TransactionProps>()(Transaction); export { HOC as Transaction };
the_stack
import { GM_addStyle, GM_xmlhttpRequest } from '../@types/tm_f' const W = typeof unsafeWindow === 'undefined' ? window : unsafeWindow let gInputUSDCNY: HTMLInputElement let gDivLastChecked: HTMLDivElement let gInputAddCent: HTMLInputElement let gSpanQuickSurplus: HTMLSpanElement let gSpanQuickError: HTMLSpanElement const gDivItems: HTMLDivElement[] = [] const gQuickSells: ItemInfo[] = [] // 执行程序 addCSS() addUI() doLoop() const elmDivActiveInventoryPage = <HTMLDivElement>document.querySelector('#inventories') // 创建观察者对象 const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { // 有点丑的复选框 const rt = <HTMLDivElement>mutation.target if (rt.classList.contains('inventory_page')) { const itemHolders = <NodeListOf<HTMLDivElement>>rt.querySelectorAll('.itemHolder') itemHolders.forEach(itemHolder => { const rgItem = itemHolder.rgItem if (rgItem !== undefined && !gDivItems.includes(rgItem.element) && rgItem.description.marketable === 1) { gDivItems.push(rgItem.element) // 复选框 const elmDiv = document.createElement('div') elmDiv.classList.add('scmpItemCheckbox') rgItem.element.appendChild(elmDiv) } }) } }) }) // 传入目标节点和观察选项 observer.observe(elmDivActiveInventoryPage, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] }) /** * 添加复选框和汇率输入框 * */ async function addUI() { // 插入快速出售按钮 const elmDivInventoryPageRight = <HTMLDivElement>document.querySelector('.inventory_page_right') const elmDiv = document.createElement('div') elmDiv.innerHTML = ` <div class="scmpQuickSell">快速以此价格出售: <span class="btn_green_white_innerfade" id="scmpQuickSellItem">null</span> <span> 加价: $ <input class="filter_search_box" id="scmpAddCent" type="number" value="0.00" step="0.01"> </span> </div> <div> 汇率: <input class="filter_search_box" id="scmpExch" type="number" value="6.50"> <span class="btn_green_white_innerfade" id="scmpQuickAllItem">快速出售</span> 剩余: <span id="scmpQuickSurplus">0</span> 失败: <span id="scmpQuickError">0</span> </div>` elmDivInventoryPageRight.appendChild(elmDiv) // 获取快速出售按钮 const elmSpanQuickSellItem = <HTMLSpanElement>elmDiv.querySelector('#scmpQuickSellItem') const elmSpanQuickAllItem = <HTMLSpanElement>document.querySelector('#scmpQuickAllItem') gInputAddCent = <HTMLInputElement>elmDiv.querySelector('#scmpAddCent') gSpanQuickSurplus = <HTMLSpanElement>elmDiv.querySelector('#scmpQuickSurplus') gSpanQuickError = <HTMLSpanElement>elmDiv.querySelector('#scmpQuickError') // 监听全局点击事件 document.addEventListener('click', async (ev: MouseEvent) => { const evt = <HTMLElement>ev.target // 点击物品 if (evt.className === 'inventory_item_link') { elmSpanQuickSellItem.innerText = 'null' const rgItem = (<HTMLDivElement>evt.parentNode).rgItem const itemInfo = new ItemInfo(rgItem) const priceOverview = await getPriceOverview(itemInfo) if (priceOverview !== 'error') elmSpanQuickSellItem.innerText = <string>priceOverview.formatPrice } // 选择逻辑 else if (evt.classList.contains('scmpItemCheckbox')) { const rgItem = (<HTMLDivElement>evt.parentNode).rgItem const select = evt.classList.contains('scmpItemSelect') // 改变背景 const changeClass = (elmDiv: HTMLDivElement) => { const elmCheckbox = <HTMLDivElement>elmDiv.querySelector('.scmpItemCheckbox') if ((<HTMLDivElement>elmDiv.parentNode).style.display !== 'none' && !elmCheckbox.classList.contains('scmpItemSuccess')) { elmCheckbox.classList.remove('scmpItemError') elmCheckbox.classList.toggle('scmpItemSelect', !select) } } // shift多选 if (gDivLastChecked !== undefined && ev.shiftKey) { const start = gDivItems.indexOf(gDivLastChecked) const end = gDivItems.indexOf(rgItem.element) const someDivItems = gDivItems.slice(Math.min(start, end), Math.max(start, end) + 1) for (const y of someDivItems) changeClass(y) } else changeClass(rgItem.element) gDivLastChecked = rgItem.element } }) // 点击快速出售 elmSpanQuickSellItem.addEventListener('click', (ev: Event) => { const evt = <HTMLSpanElement>ev.target const elmDivActiveInfo = <HTMLDivElement>document.querySelector('.activeInfo') const rgItem = elmDivActiveInfo.rgItem const elmDivitemCheck = <HTMLDivElement>rgItem.element.querySelector('.scmpItemCheckbox') if (!elmDivitemCheck.classList.contains('scmpItemSuccess') && evt.innerText !== 'null') { const price = W.GetPriceValueAsInt(evt.innerText) const itemInfo = new ItemInfo(rgItem, price) quickSellItem(itemInfo) } }) // 点击全部出售 elmSpanQuickAllItem.addEventListener('click', () => { const elmDivItemInfos = document.querySelectorAll('.scmpItemSelect') elmDivItemInfos.forEach(elmDivItemInfo => { const rgItem = (<HTMLDivElement>elmDivItemInfo.parentNode).rgItem const itemInfo = new ItemInfo(rgItem) if (rgItem.description.marketable === 1) gQuickSells.push(itemInfo) }) }) // 点击加价 gInputAddCent.addEventListener('input', () => { const activeInfo = <HTMLLinkElement>document.querySelector('.activeInfo > .inventory_item_link') activeInfo.click() }) // 改变汇率 gInputUSDCNY = <HTMLInputElement>elmDiv.querySelector('#scmpExch') // 在线获取实时汇率 const baiduExch = await XHR<baiduExch>({ GM: true, method: 'GET', url: `https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=1%E7%BE%8E%E5%85%83%E7%AD%89%E4%BA%8E%E5%A4%9A%E5%B0%91%E4%BA%BA%E6%B0%91%E5%B8%81&resource_id=6017&t=${Date.now()}&ie=utf8&oe=utf8&format=json&tn=baidu`, responseType: 'json', }) if (baiduExch !== undefined && baiduExch.response.status === 200) gInputUSDCNY.value = baiduExch.body.data[0].number2 } /** * 获取美元区价格 * * @param {ItemInfo} itemInfo * @returns {(Promise<'error' | ItemInfo>)} */ async function getPriceOverview(itemInfo: ItemInfo): Promise<'error' | ItemInfo> { const priceoverview = await XHR<priceoverview>({ method: 'GET', url: `/market/priceoverview/?country=US&currency=1&appid=${itemInfo.rgItem.description.appid}\ &market_hash_name=${encodeURIComponent(W.GetMarketHashName(itemInfo.rgItem.description))}`, responseType: 'json' }) const stop = (): 'error' => itemInfo.status = 'error' if (priceoverview !== undefined && priceoverview.response.status === 200 && priceoverview.body.success && priceoverview.body.lowest_price) { // 对$进行处理, 否则会报错 itemInfo.lowestPrice = priceoverview.body.lowest_price.replace('$', '') return calculatePrice(itemInfo) } else { const marketListings = await XHR<string>({ method: 'GET', url: `/market/listings/${itemInfo.rgItem.description.appid}\ /${encodeURIComponent(W.GetMarketHashName(itemInfo.rgItem.description))}` }) if (marketListings === undefined || marketListings.response.status !== 200) return stop() const marketLoadOrderSpread = marketListings.body.match(/Market_LoadOrderSpread\( (\d+)/) if (marketLoadOrderSpread === null) return stop() const itemordershistogram = await XHR<itemordershistogram>({ method: 'GET', url: `/market/itemordershistogram/?country=US&language=english&currency=1&item_nameid=${marketLoadOrderSpread[1]}&two_factor=0`, responseType: 'json' }) if (itemordershistogram === undefined || itemordershistogram.response.status !== 200 || itemordershistogram.body.success !== 1) return stop() itemInfo.lowestPrice = ' ' + itemordershistogram.body.sell_order_graph[0][0] return calculatePrice(itemInfo) } } /** * 计算价格 * * @param {ItemInfo} itemInfo * @returns {ItemInfo} */ function calculatePrice(itemInfo: ItemInfo): ItemInfo { // 格式化取整 let price = W.GetPriceValueAsInt(<string>itemInfo.lowestPrice) const addCent = parseFloat(gInputAddCent.value) * 100 // 汇率 const exchangeRate = parseFloat(gInputUSDCNY.value) // 手续费 const publisherFee = itemInfo.rgItem.description.market_fee || W.g_rgWalletInfo.wallet_publisher_fee_percent_default const feeInfo = W.CalculateFeeAmount(price, publisherFee) price = price - feeInfo.fees // 换算成人民币 itemInfo.price = Math.floor((price + addCent) * exchangeRate) // 格式化 itemInfo.formatPrice = W.v_currencyformat(itemInfo.price, W.GetCurrencyCode(W.g_rgWalletInfo.wallet_currency)) return itemInfo } /** * 快速出售 * * @param {ItemInfo} itemInfo * @returns {Promise < void>} */ async function quickSellItem(itemInfo: ItemInfo): Promise<void> { itemInfo.status = 'run' const sellitem = await XHR<sellitem>({ method: 'POST', url: 'https://steamcommunity.com/market/sellitem/', data: `sessionid=${W.g_sessionID}&appid=${itemInfo.rgItem.description.appid}\ &contextid=${itemInfo.rgItem.contextid}&assetid=${itemInfo.rgItem.assetid}&amount=1&price=${itemInfo.price}`, responseType: 'json', withCredentials: true }) if (sellitem === undefined || sellitem.response.status !== 200 || !sellitem.body.success) itemInfo.status = 'error' else itemInfo.status = 'success' } /** * 批量出售采用轮询 * */ async function doLoop() { const itemInfo = gQuickSells.shift() const loop = () => { setTimeout(() => { doLoop() }, 500) } if (itemInfo !== undefined) { const priceOverview = await getPriceOverview(itemInfo) if (priceOverview !== 'error') { await quickSellItem(priceOverview) doLoop() } else loop() } else loop() } /** * 添加CSS * */ function addCSS() { GM_addStyle(` .scmpItemSelect { background: yellow; } .scmpItemRun { background: blue; } .scmpItemSuccess { background: green; } .scmpItemError { background: red; } .scmpItemCheckbox { position: absolute; z-index: 100; top: 0; left: 0; width: 20px; height: 20px; border: 2px solid yellow; opacity: 0.7; cursor: default; } .scmpItemCheckbox:hover { opacity: 1; } #scmpExch { width: 3.3em; -moz-appearance: textfield; } #scmpExch::-webkit-inner-spin-button { -webkit-appearance: none; } #scmpAddCent { width: 3.9em; }`) } /** * 使用Promise封装xhr * 因为上下文问题, GM_xmlhttpRequest为单独一项 * fetch和GM_xmlhttpRequest兼容过于复杂, 所以使用XMLHttpRequest * * @template T * @param {XHROptions} XHROptions * @returns {(Promise<response<T> | undefined>)} */ function XHR<T>(XHROptions: XHROptions): Promise<response<T> | undefined> { return new Promise(resolve => { const onerror = (error: any) => { console.error(error) resolve(undefined) } if (XHROptions.GM) { if (XHROptions.method === 'POST') { if (XHROptions.headers === undefined) XHROptions.headers = {} if (XHROptions.headers['Content-Type'] === undefined) XHROptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' } XHROptions.timeout = 30 * 1000 XHROptions.onload = res => resolve({ response: res, body: res.response }) XHROptions.onerror = onerror XHROptions.ontimeout = onerror GM_xmlhttpRequest(XHROptions) } else { const xhr = new XMLHttpRequest() xhr.open(XHROptions.method, XHROptions.url) if (XHROptions.method === 'POST' && xhr.getResponseHeader('Content-Type') === null) xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8') if (XHROptions.withCredentials) xhr.withCredentials = true if (XHROptions.responseType !== undefined) xhr.responseType = XHROptions.responseType xhr.timeout = 30 * 1000 xhr.onload = ev => { const res = <XMLHttpRequest>ev.target resolve({ response: res, body: res.response }) } xhr.onerror = onerror xhr.ontimeout = onerror xhr.send(XHROptions.data) } }) } /** * 物品信息 * * @class ItemInfo */ class ItemInfo { constructor(rgItem: rgItem, price?: number) { this.rgItem = rgItem if (price !== undefined) this.price = price } /** * rgItem * * @type {rgItem} * @memberof ItemInfo */ public rgItem: rgItem /** * 价格, 整数 * * @type {number} * @memberof ItemInfo */ public price?: number /** * 价格, 格式化带单位 * * @type {string} * @memberof ItemInfo */ public formatPrice?: string /** * 当前状态, 选择, 出售, 失败 * * @private * @type {string} * @memberof ItemInfo */ private _status: string = '' public get status(): string { return this._status } public set status(valve: string) { this._status = valve const elmCheckbox = <HTMLDivElement | null>this.rgItem.element.querySelector('.scmpItemCheckbox') if (elmCheckbox === null) return switch (valve) { case 'run': elmCheckbox.classList.remove('scmpItemError') elmCheckbox.classList.remove('scmpItemSelect') elmCheckbox.classList.add('scmpItemRun') break case 'success': gSpanQuickSurplus.innerText = gQuickSells.length.toString() elmCheckbox.classList.remove('scmpItemError') elmCheckbox.classList.remove('scmpItemRun') elmCheckbox.classList.add('scmpItemSuccess') break case 'error': gSpanQuickSurplus.innerText = gQuickSells.length.toString() gSpanQuickError.innerText = (parseInt(gSpanQuickError.innerText) + 1).toString() elmCheckbox.classList.remove('scmpItemRun') elmCheckbox.classList.add('scmpItemError') elmCheckbox.classList.add('scmpItemSelect') break default: break } } /** * 最低价, 整数 * * @type {string} * @memberof ItemInfo */ public lowestPrice?: string }
the_stack
import { b64string, generichash, ready as cryptoReady, utils } from '@tanker/crypto'; import { InvalidArgument } from '@tanker/errors'; import { expect } from '@tanker/test-utils'; import { obfuscateUserId, createIdentity, createProvisionalIdentity, getPublicIdentity, } from '@tanker/identity'; import { _deserializePermanentIdentity, _deserializeProvisionalIdentity, _deserializePublicIdentity, _splitProvisionalAndPermanentPublicIdentities, _serializeIdentity, assertTrustchainId, } from '../identity'; import type { SecretPermanentIdentity, PublicIdentity, SecretProvisionalIdentity, } from '../identity'; describe('Identity', () => { const trustchain = { id: 'tpoxyNzh0hU9G2i9agMvHyyd+pO6zGCjO9BfhrCLjd4=', sk: 'cTMoGGUKhwN47ypq4xAXAtVkNWeyUtMltQnYwJhxWYSvqjPVGmXd2wwa7y17QtPTZhn8bxb015CZC/e4ZI7+MQ==', pk: 'r6oz1Rpl3dsMGu8te0LT02YZ/G8W9NeQmQv3uGSO/jE=', }; const userId = 'b_eich'; const userEmail = 'brendan.eich@tanker.io'; let hashedUserEmail: b64string; let obfuscatedUserId: b64string; before(async () => { await cryptoReady; obfuscatedUserId = utils.toBase64(obfuscateUserId(utils.fromBase64(trustchain.id), userId)); hashedUserEmail = utils.toBase64(generichash(utils.fromString(userEmail))); }); describe('deserialize', () => { const goodPermanentIdentity = 'eyJ0cnVzdGNoYWluX2lkIjoidHBveHlOemgwaFU5RzJpOWFnTXZIeXlkK3BPNnpHQ2pPOUJmaHJDTGpkND0iLCJ0YXJnZXQiOiJ1c2VyIiwidmFsdWUiOiJSRGEwZXE0WE51ajV0VjdoZGFwak94aG1oZVRoNFFCRE5weTRTdnk5WG9rPSIsImRlbGVnYXRpb25fc2lnbmF0dXJlIjoiVTlXUW9sQ3ZSeWpUOG9SMlBRbWQxV1hOQ2kwcW1MMTJoTnJ0R2FiWVJFV2lyeTUya1d4MUFnWXprTHhINmdwbzNNaUE5cisremhubW9ZZEVKMCtKQ3c9PSIsImVwaGVtZXJhbF9wdWJsaWNfc2lnbmF0dXJlX2tleSI6IlhoM2kweERUcHIzSFh0QjJRNTE3UUt2M2F6TnpYTExYTWRKRFRTSDRiZDQ9IiwiZXBoZW1lcmFsX3ByaXZhdGVfc2lnbmF0dXJlX2tleSI6ImpFRFQ0d1FDYzFERndvZFhOUEhGQ2xuZFRQbkZ1Rm1YaEJ0K2lzS1U0WnBlSGVMVEVOT212Y2RlMEhaRG5YdEFxL2RyTTNOY3N0Y3gwa05OSWZodDNnPT0iLCJ1c2VyX3NlY3JldCI6IjdGU2YvbjBlNzZRVDNzMERrdmV0UlZWSmhYWkdFak94ajVFV0FGZXh2akk9In0='; const goodProvisionalIdentity = 'eyJ0cnVzdGNoYWluX2lkIjoidHBveHlOemgwaFU5RzJpOWFnTXZIeXlkK3BPNnpHQ2pPOUJmaHJDTGpkND0iLCJ0YXJnZXQiOiJlbWFpbCIsInZhbHVlIjoiYnJlbmRhbi5laWNoQHRhbmtlci5pbyIsInB1YmxpY19lbmNyeXB0aW9uX2tleSI6Ii8yajRkSTNyOFBsdkNOM3VXNEhoQTV3QnRNS09jQUNkMzhLNk4wcSttRlU9IiwicHJpdmF0ZV9lbmNyeXB0aW9uX2tleSI6IjRRQjVUV212Y0JyZ2V5RERMaFVMSU5VNnRicUFPRVE4djlwakRrUGN5YkE9IiwicHVibGljX3NpZ25hdHVyZV9rZXkiOiJXN1FFUUJ1OUZYY1hJcE9ncTYydFB3Qml5RkFicFQxckFydUQwaC9OclRBPSIsInByaXZhdGVfc2lnbmF0dXJlX2tleSI6IlVtbll1dmRUYUxZRzBhK0phRHBZNm9qdzQvMkxsOHpzbXJhbVZDNGZ1cVJidEFSQUc3MFZkeGNpazZDcnJhMC9BR0xJVUJ1bFBXc0N1NFBTSDgydE1BPT0ifQ=='; const goodPublicIdentity = 'eyJ0cnVzdGNoYWluX2lkIjoidHBveHlOemgwaFU5RzJpOWFnTXZIeXlkK3BPNnpHQ2pPOUJmaHJDTGpkND0iLCJ0YXJnZXQiOiJ1c2VyIiwidmFsdWUiOiJSRGEwZXE0WE51ajV0VjdoZGFwak94aG1oZVRoNFFCRE5weTRTdnk5WG9rPSJ9'; const goodOldPublicProvisionalIdentity = 'eyJ0cnVzdGNoYWluX2lkIjoidHBveHlOemgwaFU5RzJpOWFnTXZIeXlkK3BPNnpHQ2pPOUJmaHJDTGpkND0iLCJ0YXJnZXQiOiJlbWFpbCIsInZhbHVlIjoiYnJlbmRhbi5laWNoQHRhbmtlci5pbyIsInB1YmxpY19lbmNyeXB0aW9uX2tleSI6Ii8yajRkSTNyOFBsdkNOM3VXNEhoQTV3QnRNS09jQUNkMzhLNk4wcSttRlU9IiwicHVibGljX3NpZ25hdHVyZV9rZXkiOiJXN1FFUUJ1OUZYY1hJcE9ncTYydFB3Qml5RkFicFQxckFydUQwaC9OclRBPSJ9'; const goodPublicProvisionalIdentity = 'eyJ0cnVzdGNoYWluX2lkIjoidHBveHlOemgwaFU5RzJpOWFnTXZIeXlkK3BPNnpHQ2pPOUJmaHJDTGpkND0iLCJ0YXJnZXQiOiJoYXNoZWRfZW1haWwiLCJ2YWx1ZSI6IjB1MmM4dzhFSVpXVDJGelJOL3l5TTVxSWJFR1lUTkRUNVNrV1ZCdTIwUW89IiwicHVibGljX2VuY3J5cHRpb25fa2V5IjoiLzJqNGRJM3I4UGx2Q04zdVc0SGhBNXdCdE1LT2NBQ2QzOEs2TjBxK21GVT0iLCJwdWJsaWNfc2lnbmF0dXJlX2tleSI6Ilc3UUVRQnU5RlhjWElwT2dxNjJ0UHdCaXlGQWJwVDFyQXJ1RDBoL05yVEE9In0='; it('can parse a valid permanent identity', () => { const identity = _deserializePermanentIdentity(goodPermanentIdentity); expect(identity.trustchain_id).to.be.equal(trustchain.id); expect(identity.target).to.be.equal('user'); expect(identity.value).to.equal(obfuscatedUserId); expect(identity.delegation_signature).to.equal('U9WQolCvRyjT8oR2PQmd1WXNCi0qmL12hNrtGabYREWiry52kWx1AgYzkLxH6gpo3MiA9r++zhnmoYdEJ0+JCw=='); expect(identity.ephemeral_public_signature_key).to.equal('Xh3i0xDTpr3HXtB2Q517QKv3azNzXLLXMdJDTSH4bd4='); expect(identity.ephemeral_private_signature_key).to.equal('jEDT4wQCc1DFwodXNPHFClndTPnFuFmXhBt+isKU4ZpeHeLTENOmvcde0HZDnXtAq/drM3Ncstcx0kNNIfht3g=='); expect(identity.user_secret).to.equal('7FSf/n0e76QT3s0DkvetRVVJhXZGEjOxj5EWAFexvjI='); // @ts-expect-error hidden property expect(identity.serializedIdentity).to.equal(goodPermanentIdentity); }); it('can parse a valid provisional identity', () => { const identity = _deserializeProvisionalIdentity(goodProvisionalIdentity) as SecretProvisionalIdentity; expect(identity.trustchain_id).to.be.equal(trustchain.id); expect(identity.target).to.be.equal('email'); expect(identity.value).to.equal(userEmail); expect(identity.public_signature_key).to.equal('W7QEQBu9FXcXIpOgq62tPwBiyFAbpT1rAruD0h/NrTA='); expect(identity.private_signature_key).to.equal('UmnYuvdTaLYG0a+JaDpY6ojw4/2Ll8zsmramVC4fuqRbtARAG70Vdxcik6Crra0/AGLIUBulPWsCu4PSH82tMA=='); expect(identity.public_encryption_key).to.equal('/2j4dI3r8PlvCN3uW4HhA5wBtMKOcACd38K6N0q+mFU='); expect(identity.private_encryption_key).to.equal('4QB5TWmvcBrgeyDDLhULINU6tbqAOEQ8v9pjDkPcybA='); // @ts-expect-error hidden property expect(identity.serializedIdentity).to.equal(goodProvisionalIdentity); }); it('can parse a valid public identity', () => { const identity = _deserializePublicIdentity(goodPublicIdentity); expect(identity.trustchain_id).to.equal(trustchain.id); expect(identity.target).to.equal('user'); expect(identity.value).to.equal(obfuscatedUserId); // @ts-expect-error hidden property expect(identity.serializedIdentity).to.equal(goodPublicIdentity); expect(_serializeIdentity(identity)).to.equal(goodPublicIdentity); }); it('can parse a valid non-hashed email public provisional identity', () => { const identity = _deserializeProvisionalIdentity(goodOldPublicProvisionalIdentity); expect(identity.trustchain_id).to.be.equal(trustchain.id); expect(identity.target).to.be.equal('email'); expect(identity.value).to.equal(userEmail); expect(identity.public_signature_key).to.equal('W7QEQBu9FXcXIpOgq62tPwBiyFAbpT1rAruD0h/NrTA='); expect(identity.public_encryption_key).to.equal('/2j4dI3r8PlvCN3uW4HhA5wBtMKOcACd38K6N0q+mFU='); // @ts-expect-error hidden property expect(identity.serializedIdentity).to.equal(goodOldPublicProvisionalIdentity); expect(_serializeIdentity(identity)).to.equal(goodOldPublicProvisionalIdentity); }); it('can parse a valid hashed email public provisional identity', () => { const identity = _deserializeProvisionalIdentity(goodPublicProvisionalIdentity); expect(identity.trustchain_id).to.be.equal(trustchain.id); expect(identity.target).to.be.equal('hashed_email'); expect(identity.value).to.equal(hashedUserEmail); expect(identity.public_signature_key).to.equal('W7QEQBu9FXcXIpOgq62tPwBiyFAbpT1rAruD0h/NrTA='); expect(identity.public_encryption_key).to.equal('/2j4dI3r8PlvCN3uW4HhA5wBtMKOcACd38K6N0q+mFU='); // @ts-expect-error hidden property expect(identity.serializedIdentity).to.equal(goodPublicProvisionalIdentity); }); }); describe('_splitProvisionalAndPermanentPublicIdentities', () => { let b64Identity: b64string; let identity: SecretPermanentIdentity; let b64PublicIdentity: b64string; let publicIdentity: PublicIdentity; let b64ProvisionalIdentity: b64string; let provisionalIdentity: SecretProvisionalIdentity; let b64PublicProvisionalIdentity: b64string; let publicProvisionalIdentity: PublicIdentity; before(async () => { b64Identity = await createIdentity(trustchain.id, trustchain.sk, userId); identity = _deserializePermanentIdentity(b64Identity); b64PublicIdentity = await getPublicIdentity(b64Identity); publicIdentity = _deserializePublicIdentity(b64PublicIdentity); b64ProvisionalIdentity = await createProvisionalIdentity(trustchain.id, 'email', userEmail); provisionalIdentity = _deserializeProvisionalIdentity(b64ProvisionalIdentity) as SecretProvisionalIdentity; b64PublicProvisionalIdentity = await getPublicIdentity(b64ProvisionalIdentity); publicProvisionalIdentity = _deserializePublicIdentity(b64PublicProvisionalIdentity); }); it('splits identities as expected', async () => { const { permanentIdentities, provisionalIdentities } = _splitProvisionalAndPermanentPublicIdentities([publicIdentity, publicProvisionalIdentity]); expect(permanentIdentities).to.deep.equal([publicIdentity]); expect(provisionalIdentities).to.deep.equal([publicProvisionalIdentity]); }); it('throws when given a secret permanent identity', async () => { expect(() => _splitProvisionalAndPermanentPublicIdentities([identity, publicProvisionalIdentity])).to.throw(InvalidArgument); }); it('throws when given a secret provisional identity', async () => { // @ts-expect-error testing edge case with permanentIdentity expect(() => _splitProvisionalAndPermanentPublicIdentities([publicIdentity, provisionalIdentity])).to.throw(InvalidArgument); }); }); describe('assertTrustchainId', () => { const trustchain2 = { id: 'gOhJDFYKK/GNScGOoaZ1vLAwxkuqZCY36IwEo4jcnDE=', sk: 'D9jiQt7nB2IlRjilNwUVVTPsYkfbCX0PelMzx5AAXIaVokZ71iUduWCvJ9Akzojca6lvV8u1rnDVEdh7yO6JAQ==', }; const trustchainIdUint8Array = utils.fromBase64(trustchain.id); let validPublicIdentity: PublicIdentity; let invalidPublicIdentity: PublicIdentity; let validPublicProvisionalIdentity: PublicIdentity; let invalidPublicProvidionalIdentity: PublicIdentity; before(async () => { let b64Identity = await createIdentity(trustchain.id, trustchain.sk, userId); let b64PublicIdentity = await getPublicIdentity(b64Identity); validPublicIdentity = _deserializePublicIdentity(b64PublicIdentity); b64Identity = await createIdentity(trustchain2.id, trustchain2.sk, userId); b64PublicIdentity = await getPublicIdentity(b64Identity); invalidPublicIdentity = _deserializePublicIdentity(b64PublicIdentity); b64Identity = await createProvisionalIdentity(trustchain.id, 'email', userEmail); b64PublicIdentity = await getPublicIdentity(b64Identity); validPublicProvisionalIdentity = _deserializePublicIdentity(b64PublicIdentity); b64Identity = await createProvisionalIdentity(trustchain2.id, 'email', userEmail); b64PublicIdentity = await getPublicIdentity(b64Identity); invalidPublicProvidionalIdentity = _deserializePublicIdentity(b64PublicIdentity); }); it('does not throw with an empty array', async () => { expect(() => assertTrustchainId([], trustchainIdUint8Array)).not.to.throw; }); it('does not throw with valid public identities', async () => { expect(() => assertTrustchainId([validPublicIdentity], trustchainIdUint8Array)).not.to.throw; }); it('does not throw with valid public provisional identities', async () => { expect(() => assertTrustchainId([validPublicProvisionalIdentity], trustchainIdUint8Array)).not.to.throw; }); it('throws with invalid identities', async () => { expect(() => assertTrustchainId([invalidPublicIdentity], trustchainIdUint8Array)).to.throw(InvalidArgument); }); it('throws with invalid provisional identities', async () => { expect(() => assertTrustchainId([invalidPublicProvidionalIdentity], trustchainIdUint8Array)).to.throw(InvalidArgument); }); it('throws with a mix of valid and invalid identities', async () => { expect(() => assertTrustchainId([validPublicIdentity, validPublicProvisionalIdentity, invalidPublicIdentity, invalidPublicProvidionalIdentity], trustchainIdUint8Array)).to.throw(InvalidArgument); }); }); });
the_stack
import { createMemoryHistory } from 'history'; import type { CreateRouterOptions, RoutesConfig, State } from '../../types'; import { createRouter } from '../createRouter'; import { locationsMatch } from '../locationsMatch'; import { matchRoutes } from '../matchRoutes'; import { prepareMatch } from '../prepareMatch'; import { routesToEntryMap } from '../routesToEntryMap'; jest.mock('../routesToEntryMap', () => ({ routesToEntryMap: jest.fn(() => 'routesEntryMap'), })); const componentLoadMock = jest.fn(); jest.mock('../matchRoutes', () => ({ matchRoutes: jest.fn(() => ({ location: 'matchedLocation', route: { component: { load: componentLoadMock } }, })), })); jest.mock('../prepareMatch', () => ({ prepareMatch: jest.fn(() => ({ component: { load: componentLoadMock }, location: 'preparedLocation', })), })); jest.mock('../locationsMatch', () => ({ locationsMatch: jest.fn(() => true), })); const mockLocationsMatch = locationsMatch as unknown as jest.Mock<boolean>; const mockPrepareMatch = prepareMatch as unknown as jest.Mock<{ component: { load: () => void }; location: string; }>; describe('createRouter()', () => { const defaultRouterOptions: CreateRouterOptions<RoutesConfig> = { assistPreload: true, awaitComponent: true, awaitPreload: false, history: { action: 'PUSH', block: jest.fn(), createHref: jest.fn(), go: jest.fn(), goBack: jest.fn(), goForward: jest.fn(), length: 0, listen: jest.fn(), location: { hash: '', key: 'historyKey', pathname: 'historyLocation', search: '', state: undefined, }, push: jest.fn(), replace: jest.fn(), }, routes: [ { component: jest.fn(), path: 'foo', }, { component: jest.fn(), path: '*', }, ], }; afterEach(() => { jest.clearAllMocks(); }); it('should run the expected functions when called', () => { createRouter(defaultRouterOptions); expect(routesToEntryMap).toHaveBeenCalledTimes(1); expect(routesToEntryMap).toHaveBeenCalledWith(defaultRouterOptions.routes); expect(matchRoutes).toHaveBeenCalledTimes(1); expect(matchRoutes).toHaveBeenCalledWith( 'routesEntryMap', defaultRouterOptions.history.location ); expect(prepareMatch).toHaveBeenCalledTimes(1); expect(prepareMatch).toHaveBeenCalledWith( { location: 'matchedLocation', route: { component: { load: expect.any(Function) } }, }, defaultRouterOptions.assistPreload, defaultRouterOptions.awaitPreload ); expect(locationsMatch).toHaveBeenCalledTimes(1); expect(locationsMatch).toHaveBeenCalledWith( 'matchedLocation', defaultRouterOptions.history.location, true ); expect(defaultRouterOptions.history.replace).not.toHaveBeenCalled(); expect(defaultRouterOptions.history.listen).toHaveBeenCalledTimes(1); expect(defaultRouterOptions.history.listen).toHaveBeenCalledWith( expect.any(Function) ); }); it('should call history.replace when locationsMatch returns false', () => { mockLocationsMatch.mockReturnValueOnce(false); createRouter(defaultRouterOptions); expect(defaultRouterOptions.history.replace).toHaveBeenCalledTimes(1); expect(defaultRouterOptions.history.replace).toHaveBeenCalledWith( 'matchedLocation' ); }); it('should return the expected router context', () => { const router = createRouter(defaultRouterOptions); expect(router).toEqual({ assistPreload: defaultRouterOptions.assistPreload, awaitComponent: defaultRouterOptions.awaitComponent, get: expect.any(Function), getCurrentRouteKey: expect.any(Function), history: { ...defaultRouterOptions.history, // These functions explicitly expect any function because of issue: // https://github.com/erictaylor/yarr/issues/4 push: expect.any(Function), replace: expect.any(Function), }, isActive: expect.any(Function), logger: expect.any(Function), preloadCode: expect.any(Function), routeTransitionCompleted: expect.any(Function), subscribe: expect.any(Function), warmRoute: expect.any(Function), }); }); it('should have expected behavior from returned `get` function', () => { const router = createRouter(defaultRouterOptions); expect(router.get()).toEqual({ component: { load: expect.any(Function) }, location: 'preparedLocation', }); }); it('should have expected behavior from returned `isActive` function', () => { const router = createRouter(defaultRouterOptions); mockLocationsMatch.mockClear(); router.isActive('foo'); expect(locationsMatch).toHaveBeenCalledTimes(1); expect(locationsMatch).toHaveBeenCalledWith( defaultRouterOptions.history.location, 'foo', undefined ); router.isActive('bar', false); expect(locationsMatch).toHaveBeenCalledTimes(2); expect(locationsMatch).toHaveBeenCalledWith( defaultRouterOptions.history.location, 'bar', false ); router.isActive('baz', true); expect(locationsMatch).toHaveBeenCalledTimes(3); expect(locationsMatch).toHaveBeenCalledWith( defaultRouterOptions.history.location, 'baz', true ); }); it('should have expected behavior from returned `preloadCode` function', () => { const router = createRouter(defaultRouterOptions); router.preloadCode('baz'); expect(matchRoutes).toHaveBeenCalledTimes(2); expect(matchRoutes).toHaveBeenCalledWith('routesEntryMap', { hash: '', pathname: 'baz', search: '', }); expect(componentLoadMock).toHaveBeenCalledTimes(1); expect(componentLoadMock).toHaveBeenCalledWith(); }); it('should have expected behavior from returned `subscribe` function', () => { const history = createMemoryHistory<State>(); const router = createRouter({ ...defaultRouterOptions, history }); const mockSubscribeHistoryFunction = jest.fn(); const mockSubscribeTransitionFunction = jest.fn(); mockLocationsMatch.mockReturnValueOnce(false); const dispose = router.subscribe({ onTransitionComplete: mockSubscribeTransitionFunction, onTransitionStart: mockSubscribeHistoryFunction, }); expect(dispose).toEqual(expect.any(Function)); history.push('/testing'); expect(mockSubscribeHistoryFunction).toHaveBeenCalledTimes(1); expect(mockSubscribeHistoryFunction).toHaveBeenCalledWith( { component: { load: expect.any(Function) }, location: 'preparedLocation', }, { action: 'PUSH', location: { hash: '', key: expect.any(String), pathname: '/testing', search: '', state: undefined, }, } ); expect(mockSubscribeTransitionFunction).not.toHaveBeenCalled(); router.routeTransitionCompleted({ action: 'PUSH', location: { hash: '', key: 'testKey', pathname: '/testing', search: '', state: undefined, }, }); expect(mockSubscribeTransitionFunction).toHaveBeenCalledTimes(1); expect(mockSubscribeTransitionFunction).toHaveBeenCalledWith({ action: 'PUSH', location: { hash: '', key: 'testKey', pathname: '/testing', search: '', state: undefined, }, }); dispose(); mockSubscribeHistoryFunction.mockClear(); mockLocationsMatch.mockReturnValueOnce(false); history.push('/testing2'); expect(mockSubscribeHistoryFunction).not.toHaveBeenCalled(); }); it('should have expected behavior from returned `warmRoute` function', () => { const router = createRouter(defaultRouterOptions); mockPrepareMatch.mockClear(); router.warmRoute('testWarmRoute'); expect(matchRoutes).toHaveBeenCalledTimes(2); expect(matchRoutes).toHaveBeenCalledWith('routesEntryMap', { hash: '', pathname: 'testWarmRoute', search: '', }); expect(prepareMatch).toHaveBeenCalledTimes(1); expect(prepareMatch).toHaveBeenCalledWith( { location: 'matchedLocation', route: { component: { load: expect.any(Function) } }, }, defaultRouterOptions.assistPreload, defaultRouterOptions.awaitPreload ); }); describe('history listener logic', () => { it('should do nothing when locationsMatch returns true', () => { const history = createMemoryHistory<State>(); jest.spyOn(history, 'replace'); const router = createRouter({ ...defaultRouterOptions, history }); const mockSubscribeFunction = jest.fn(); router.subscribe({ onTransitionStart: mockSubscribeFunction }); history.push('/firstLocation'); expect(locationsMatch).toHaveBeenCalledTimes(2); expect(locationsMatch).toHaveBeenCalledWith( 'preparedLocation', { hash: '', key: expect.any(String), pathname: '/firstLocation', search: '', state: undefined, }, true ); expect(matchRoutes).toHaveBeenCalledTimes(1); expect(prepareMatch).toHaveBeenCalledTimes(1); expect(history.replace).not.toHaveBeenCalled(); expect(mockSubscribeFunction).not.toHaveBeenCalled(); }); it('should act as expected when first locationsMatch returns false (new location)', () => { const history = createMemoryHistory<State>(); jest.spyOn(history, 'replace'); const router = createRouter({ ...defaultRouterOptions, history }); const mockSubscribeFunction = jest.fn(); router.subscribe({ onTransitionStart: mockSubscribeFunction }); mockLocationsMatch.mockReturnValueOnce(false); history.push('/newLocation'); expect(locationsMatch).toHaveBeenCalledTimes(3); expect(locationsMatch).toHaveBeenNthCalledWith( 2, 'preparedLocation', { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }, true ); expect(matchRoutes).toHaveBeenCalledTimes(2); expect(matchRoutes).toHaveBeenCalledWith('routesEntryMap', { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }); expect(prepareMatch).toHaveBeenCalledTimes(2); expect(prepareMatch).toHaveBeenCalledWith( { location: 'matchedLocation', route: { component: { load: expect.any(Function) } }, }, defaultRouterOptions.assistPreload, defaultRouterOptions.awaitPreload ); expect(history.replace).not.toHaveBeenCalled(); expect(mockSubscribeFunction).toHaveBeenCalledTimes(1); expect(mockSubscribeFunction).toHaveBeenCalledWith( { component: { load: expect.any(Function) }, location: 'preparedLocation', }, { action: 'PUSH', location: { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }, } ); }); it('should act as expected when second locationsMatch returns false (replaced location)', () => { const history = createMemoryHistory<State>(); jest.spyOn(history, 'replace'); const router = createRouter({ ...defaultRouterOptions, history }); const mockSubscribeFunction = jest.fn(); router.subscribe({ onTransitionStart: mockSubscribeFunction }); mockLocationsMatch.mockReturnValueOnce(false).mockReturnValueOnce(false); expect(locationsMatch).toHaveBeenCalledTimes(1); history.push('/newLocation'); // First time is init check pre history.listen calls (return is true) // Second time is first call in history.listen (return is false) // Third time is second call in history.listen (return is false) // This means history.replace is called, which calls history.location again // So we get our last call to locationsMatch in history.listen (return is true) expect(locationsMatch).toHaveBeenCalledTimes(4); expect(matchRoutes).toHaveBeenCalledTimes(2); expect(prepareMatch).toHaveBeenCalledTimes(2); expect(history.replace).toHaveBeenCalledTimes(1); expect(history.replace).toHaveBeenCalledWith('matchedLocation'); expect(mockSubscribeFunction).not.toHaveBeenCalled(); }); it('should update the currentEntry with a new location', () => { const history = createMemoryHistory<State>(); const router = createRouter({ ...defaultRouterOptions, history }); expect(router.get()).toEqual({ component: { load: expect.any(Function) }, location: 'preparedLocation', }); mockLocationsMatch.mockReturnValueOnce(false); mockPrepareMatch.mockReturnValueOnce({ component: { load: jest.fn() }, location: 'newLocation', }); history.push('newLocation'); expect(router.get()).toEqual({ component: { load: expect.any(Function) }, location: 'newLocation', }); }); it('should notify all subscribers of changes', () => { const history = createMemoryHistory<State>(); const router = createRouter({ ...defaultRouterOptions, history }); const firstHistorySubscriber = jest.fn(); const secondHistorySubscriber = jest.fn(); const thirdHistorySubscriber = jest.fn(); const firstTransitionSubscriber = jest.fn(); const secondTransitionSubscriber = jest.fn(); const thirdTransitionSubscriber = jest.fn(); router.subscribe({ onTransitionComplete: firstTransitionSubscriber, onTransitionStart: firstHistorySubscriber, }); router.subscribe({ onTransitionComplete: secondTransitionSubscriber, onTransitionStart: secondHistorySubscriber, }); router.subscribe({ onTransitionComplete: thirdTransitionSubscriber, onTransitionStart: thirdHistorySubscriber, }); mockLocationsMatch.mockReturnValueOnce(false); history.push('newLocation'); expect(firstHistorySubscriber).toHaveBeenCalledTimes(1); expect(firstHistorySubscriber).toHaveBeenCalledWith( { component: { load: expect.any(Function) }, location: 'preparedLocation', }, { action: 'PUSH', location: { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }, } ); expect(firstTransitionSubscriber).not.toHaveBeenCalled(); expect(secondHistorySubscriber).toHaveBeenCalledTimes(1); expect(secondHistorySubscriber).toHaveBeenCalledWith( { component: { load: expect.any(Function) }, location: 'preparedLocation', }, { action: 'PUSH', location: { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }, } ); expect(firstTransitionSubscriber).not.toHaveBeenCalled(); expect(thirdHistorySubscriber).toHaveBeenCalledTimes(1); expect(thirdHistorySubscriber).toHaveBeenCalledWith( { component: { load: expect.any(Function) }, location: 'preparedLocation', }, { action: 'PUSH', location: { hash: '', key: expect.any(String), pathname: '/newLocation', search: '', state: undefined, }, } ); expect(firstTransitionSubscriber).not.toHaveBeenCalled(); router.routeTransitionCompleted({ action: 'PUSH', location: { hash: '', key: 'newKey', pathname: 'newLocation', search: '', state: undefined, }, }); expect(firstTransitionSubscriber).toHaveBeenCalledTimes(1); expect(firstTransitionSubscriber).toHaveBeenCalledWith({ action: 'PUSH', location: { hash: '', key: 'newKey', pathname: 'newLocation', search: '', state: undefined, }, }); expect(secondTransitionSubscriber).toHaveBeenCalledTimes(1); expect(secondTransitionSubscriber).toHaveBeenCalledWith({ action: 'PUSH', location: { hash: '', key: 'newKey', pathname: 'newLocation', search: '', state: undefined, }, }); expect(thirdTransitionSubscriber).toHaveBeenCalledTimes(1); expect(thirdTransitionSubscriber).toHaveBeenCalledWith({ action: 'PUSH', location: { hash: '', key: 'newKey', pathname: 'newLocation', search: '', state: undefined, }, }); }); }); });
the_stack
import path from 'path' import { createLambda, BuildOptions, download, File, FileBlob, FileFsRef, glob, getNodeVersion, getSpawnOptions, Lambda, runNpmInstall, runPackageJsonScript } from '@vercel/build-utils' import type { Route } from '@vercel/routing-utils' import consola from 'consola' import fs from 'fs-extra' import resolveFrom from 'resolve-from' import { gte, gt } from 'semver' import { update as updaterc } from 'rc9' import { hasProtocol } from 'ufo' import { endStep, exec, getNuxtConfig, getNuxtConfigName, globAndPrefix, MutablePackageJson, prepareNodeModules, preparePkgForProd, readJSON, startStep, validateEntrypoint } from './utils' import { prepareTypescriptEnvironment, compileTypescriptBuildFiles, JsonOptions } from './typescript' interface BuilderOutput { watch?: string[]; output: Record<string, Lambda | File | FileFsRef>; routes: Route[]; } interface NuxtBuilderConfig { maxDuration?: number memory?: number tscOptions?: JsonOptions generateStaticRoutes?: boolean includeFiles?: string[] | string serverFiles?: string[] internalServer?: boolean } export async function build (opts: BuildOptions & { config: NuxtBuilderConfig }): Promise<BuilderOutput> { const { files, entrypoint, workPath, config = {}, meta = {} } = opts // ---------------- Debugging context -------------- consola.log('Running with @nuxt/vercel-builder version', require('../package.json').version) // ----------------- Prepare build ----------------- startStep('Prepare build') // Validate entrypoint validateEntrypoint(entrypoint) // Get Nuxt directory const entrypointDirname = path.dirname(entrypoint) // Get Nuxt path const entrypointPath = path.join(workPath, entrypointDirname) // Get folder where we'll store node_modules const modulesPath = path.join(entrypointPath, 'node_modules') // Create a real filesystem consola.log('Downloading files...') await download(files, workPath, meta) // Change current working directory to entrypointPath process.chdir(entrypointPath) consola.log('Working directory:', process.cwd()) // Read package.json let pkg: MutablePackageJson try { pkg = await readJSON('package.json') } catch (e) { throw new Error(`Can not read package.json from ${entrypointPath}`) } // Node version const nodeVersion = await getNodeVersion(entrypointPath, undefined, {}, meta) const spawnOpts = getSpawnOptions(meta, nodeVersion) // Prepare TypeScript environment if required. const usesTypescript = (pkg.devDependencies && Object.keys(pkg.devDependencies).includes('@nuxt/typescript-build')) || (pkg.dependencies && Object.keys(pkg.dependencies).includes('@nuxt/typescript')) const needsTypescriptBuild = getNuxtConfigName(entrypointPath) === 'nuxt.config.ts' if (usesTypescript) { await prepareTypescriptEnvironment({ pkg, spawnOpts, rootDir: entrypointPath }) } // Detect npm (prefer yarn) const isYarn = !fs.existsSync('package-lock.json') consola.log('Using', isYarn ? 'yarn' : 'npm') // Write .npmrc if (process.env.NPM_RC) { consola.log('Found NPM_RC in environment; creating .npmrc') await fs.writeFile('.npmrc', process.env.NPM_RC) } else if (process.env.NPM_AUTH_TOKEN || process.env.NPM_TOKEN) { consola.log('Found NPM_AUTH_TOKEN or NPM_TOKEN in environment; creating .npmrc') await fs.writeFile('.npmrc', `//registry.npmjs.org/:_authToken=${process.env.NPM_AUTH_TOKEN || process.env.NPM_TOKEN}`) } // Write .yarnclean if (isYarn && !fs.existsSync('../.yarnclean')) { await fs.copyFile(path.join(__dirname, '../.yarnclean'), '.yarnclean') } // Cache dir const cachePath = path.resolve(entrypointPath, '.vercel_cache') await fs.mkdirp(cachePath) const yarnCachePath = path.join(cachePath, 'yarn') await fs.mkdirp(yarnCachePath) // Detect vercel analytics if (process.env.VERCEL_ANALYTICS_ID) { consola.log('Vercel Analytics Detected. Adding @nuxtjs/web-vitals to .nuxtrc') updaterc( { 'buildModules[]': require.resolve('@nuxtjs/web-vitals') }, { dir: entrypointPath, name: '.nuxtrc' } ) } // ----------------- Install devDependencies ----------------- startStep('Install devDependencies') // Prepare node_modules await prepareNodeModules(entrypointPath, 'node_modules_dev') // Install all dependencies await runNpmInstall(entrypointPath, [ '--prefer-offline', '--frozen-lockfile', '--non-interactive', '--production=false', `--modules-folder=${modulesPath}`, `--cache-folder=${yarnCachePath}` ], { ...spawnOpts, env: { ...spawnOpts.env, NODE_ENV: 'development' } }, meta) // ----------------- Pre build ----------------- const buildSteps = ['vercel-build', 'now-build'] for (const step of buildSteps) { if (pkg.scripts && Object.keys(pkg.scripts).includes(step)) { startStep(`Pre build (${step})`) await runPackageJsonScript(entrypointPath, step, spawnOpts) break } } // ----------------- Nuxt build ----------------- startStep('Nuxt build') let compiledTypescriptFiles: { [filePath: string]: FileFsRef } = {} if (needsTypescriptBuild) { const { tscOptions } = config compiledTypescriptFiles = await compileTypescriptBuildFiles({ rootDir: entrypointPath, spawnOpts, tscOptions }) } // Read nuxt.config.js const nuxtConfigName = 'nuxt.config.js' const nuxtConfigFile = getNuxtConfig(entrypointPath, nuxtConfigName) // Read options from nuxt.config.js otherwise set sensible defaults const staticDir = (nuxtConfigFile.dir && nuxtConfigFile.dir.static) ? nuxtConfigFile.dir.static : 'static' let publicPath = ((nuxtConfigFile.build && nuxtConfigFile.build.publicPath) ? nuxtConfigFile.build.publicPath : '/_nuxt/').replace(/^\//, '') if (hasProtocol(publicPath)) { publicPath = '_nuxt/' } const buildDir = nuxtConfigFile.buildDir ? path.relative(entrypointPath, nuxtConfigFile.buildDir) : '.nuxt' const srcDir = nuxtConfigFile.srcDir ? path.relative(entrypointPath, nuxtConfigFile.srcDir) : '.' const lambdaName = nuxtConfigFile.lambdaName ? nuxtConfigFile.lambdaName : 'index' const usesServerMiddleware = config.internalServer !== undefined ? config.internalServer : !!nuxtConfigFile.serverMiddleware await exec('nuxt', [ 'build', '--standalone', '--no-lock', // #19 `--config-file "${nuxtConfigName}"`, entrypointPath ], spawnOpts) if (config.generateStaticRoutes) { await exec('nuxt', [ 'generate', '--no-build', '--no-lock', // #19 `--config-file "${nuxtConfigName}"`, entrypointPath ], spawnOpts) } // ----------------- Install dependencies ----------------- startStep('Install dependencies') // Use node_modules_prod await prepareNodeModules(entrypointPath, 'node_modules_prod') // Only keep core dependency const nuxtDep = preparePkgForProd(pkg) await fs.writeJSON('package.json', pkg) await runNpmInstall(entrypointPath, [ '--prefer-offline', '--pure-lockfile', '--non-interactive', '--production=true', `--modules-folder=${modulesPath}`, `--cache-folder=${yarnCachePath}` ], { ...spawnOpts, env: { ...spawnOpts.env, NPM_ONLY_PRODUCTION: 'true' } }, meta) // Validate nuxt version const nuxtPkg = require(resolveFrom(entrypointPath, `@nuxt/core${nuxtDep.suffix}/package.json`)) if (!gte(nuxtPkg.version, '2.4.0')) { throw new Error(`nuxt >= 2.4.0 is required, detected version ${nuxtPkg.version}`) } if (gt(nuxtPkg.version, '3.0.0')) { consola.warn('WARNING: nuxt >= 3.0.0 is not tested against this builder!') } // Cleanup .npmrc if (process.env.NPM_AUTH_TOKEN) { await fs.unlink('.npmrc') } // ----------------- Collect artifacts ----------------- startStep('Collect artifacts') // Static files const staticFiles = await glob('**', path.join(entrypointPath, srcDir, staticDir)) // Client dist files const clientDistDir = path.join(entrypointPath, buildDir, 'dist/client') const clientDistFiles = await globAndPrefix('**', clientDistDir, publicPath) // Server dist files const serverDistDir = path.join(entrypointPath, buildDir, 'dist/server') const serverDistFiles = await globAndPrefix('**', serverDistDir, path.join(buildDir, 'dist/server')) // Generated static files const generatedDir = path.join(entrypointPath, 'dist') const generatedPagesFiles = config.generateStaticRoutes ? await globAndPrefix('**/*.*', generatedDir, './') : {} // node_modules_prod const nodeModulesDir = path.join(entrypointPath, 'node_modules_prod') const nodeModules = await globAndPrefix('**', nodeModulesDir, 'node_modules') // Lambdas const lambdas: Record<string, Lambda> = {} const launcherPath = path.join(__dirname, 'launcher.js') const launcherSrc = (await fs.readFile(launcherPath, 'utf8')) .replace(/__NUXT_SUFFIX__/g, nuxtDep.suffix) .replace(/__NUXT_CONFIG__/g, './' + nuxtConfigName) .replace(/\/\* __ENABLE_INTERNAL_SERVER__ \*\/ *true/g, String(usesServerMiddleware)) const launcherFiles = { 'vercel__launcher.js': new FileBlob({ data: launcherSrc }), 'vercel__bridge.js': new FileFsRef({ fsPath: require('@vercel/node-bridge') }), [nuxtConfigName]: new FileFsRef({ fsPath: path.resolve(entrypointPath, nuxtConfigName) }), ...serverDistFiles, ...compiledTypescriptFiles, ...nodeModules } // Extra files to be included in lambda const serverFiles = [ ...(Array.isArray(config.includeFiles) ? config.includeFiles : config.includeFiles ? [config.includeFiles] : []), ...(Array.isArray(config.serverFiles) ? config.serverFiles : []), 'package.json' ] for (const pattern of serverFiles) { const files = await glob(pattern, entrypointPath) Object.assign(launcherFiles, files) } // lambdaName will be titled index, unless specified in nuxt.config.js lambdas[lambdaName] = await createLambda({ handler: 'vercel__launcher.launcher', runtime: nodeVersion.runtime, files: launcherFiles, environment: { NODE_ENV: 'production' }, // maxDuration: config.maxDuration, memory: config.memory }) // await download(launcherFiles, rootDir) endStep() return { output: { ...lambdas, ...clientDistFiles, ...staticFiles, ...generatedPagesFiles }, routes: [ { src: `/${publicPath}.+`, headers: { 'Cache-Control': 'max-age=31557600' } }, ...Object.keys(staticFiles).map(file => ({ src: `/${file}`, headers: { 'Cache-Control': 'max-age=31557600' } })), { handle: 'filesystem' }, { src: '/(.*)', dest: '/index' } ] } }
the_stack
import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import { errorMessage } from 'elements-sk/errorMessage'; import 'elements-sk/tabs-sk'; import 'elements-sk/tabs-panel-sk'; import { TabsSk } from 'elements-sk/tabs-sk/tabs-sk'; import 'elements-sk/checkbox-sk'; import { CheckOrRadio } from 'elements-sk/checkbox-sk/checkbox-sk'; import { ElementDocSk } from '../element-doc-sk/element-doc-sk'; import { DebugViewSk } from '../debug-view-sk/debug-view-sk'; import { CommandsSk } from '../commands-sk/commands-sk'; import { TimelineSk } from '../timeline-sk/timeline-sk'; import { PlaySk } from '../play-sk/play-sk'; import { ZoomSk } from '../zoom-sk/zoom-sk'; import 'elements-sk/error-toast-sk'; import { AndroidLayersSk } from '../android-layers-sk/android-layers-sk'; import { ResourcesSk } from '../resources-sk/resources-sk'; // Types for the wasm bindings import { Debugger, DebuggerInitOptions, Matrix3x3, Matrix4x4, MatrixClipInfo, SkIRect, SkpDebugPlayer, SkpJsonCommandList, SkSurface, } from '../debugger'; // other modules from this application import '../android-layers-sk'; import '../commands-sk'; import '../debug-view-sk'; import '../histogram-sk'; import '../resources-sk'; import '../timeline-sk'; import '../zoom-sk'; import { InspectLayerEventDetail, CursorEventDetail, ToggleBackgroundEventDetail, InspectLayerEvent, JumpCommandEvent, JumpCommandEventDetail, ModeChangedManuallyEvent, MoveCommandPositionEvent, MoveCommandPositionEventDetail, MoveCursorEvent, MoveFrameEvent, Point, RenderCursorEvent, SelectImageEvent, SelectImageEventDetail, ToggleBackgroundEvent, ModeChangedManuallyEventDetail, MoveFrameEventDetail, } from '../events'; // Declarations for variables defined in JS files included by main.html declare function DebuggerInit(opts: DebuggerInitOptions): Promise<Debugger>; declare const SKIA_VERSION: string; interface FileContext { player: SkpDebugPlayer; version: number; frameCount: number; } export class DebuggerPageSk extends ElementDocSk { private static template = (ele: DebuggerPageSk) => html` <header> <h2>Skia WASM Debugger</h2> <a class="version-link" href="https://skia.googlesource.com/skia/+show/${ele._skiaVersion}" title="The skia commit at which the debugger WASM module was built"> ${ele._skiaVersionShort} </a> </header> <div id=content> <div class="horizontal-flex"> <label>SKP to open:</label> <input type="file" @change=${ele._fileInputChanged} ?disabled=${ele._debugger === null} /> <a href="https://skia.org/dev/tools/debugger">User Guide</a> <p class="file-version">File version: ${ele._fileContext?.version}</p> </div> <timeline-sk></timeline-sk> <div class="horizontal-flex"> <commands-sk></commands-sk> <div id=center> <tabs-sk id='center-tabs'> <button class=selected>SKP</button> <button>Image Resources</button> </tabs-sk> <tabs-panel-sk> <div> <debug-view-sk></debug-view-sk> </div> <div> <resources-sk></resources-sk> </div> </tabs-panel> </div> <div id=right> ${DebuggerPageSk.controlsTemplate(ele)} <histogram-sk></histogram-sk> <div>Command which shaded the<br>selected pixel: ${ele._pointCommandIndex} <button @click=${() => { ele._jumpToCommand(ele._pointCommandIndex); }}>Jump</button> </div> <zoom-sk></zoom-sk> <android-layers-sk></android-layers-sk> </div> </div> </div> <error-toast-sk></error-toast-sk> `; private static controlsTemplate = (ele: DebuggerPageSk) => html` <div> <table> <tr> <td><checkbox-sk label="GPU" ?checked=${ele._gpuMode} title="Toggle between Skia making WebGL2 calls vs. using it's CPU backend and\ copying the buffer into a Canvas2D element." @change=${ele._gpuHandler}></checkbox-sk></td> <td><checkbox-sk label="Display GPU Op Bounds" ?disabled=${!ele._gpuMode} title="Show a visual representation of the GPU operations recorded in each\ command's audit trail." @change=${ele._opBoundsHandler}></checkbox-sk></td> </tr> <tr> <td><checkbox-sk label="Light/Dark" title="Show transparency backrounds as light or dark" @change=${ele._lightDarkHandler}></checkbox-sk></td> <td><checkbox-sk label="Display Overdraw Viz" title="Shades pixels redder in proportion to how many times they were written\ to in the current frame." @change=${ele._overdrawHandler}></checkbox-sk></td> </tr> </table> <details ?open=${ele._showOpBounds}> <summary><b> GPU Op Bounds Legend</b></summary> <p style="width: 200px">GPU op bounds are rectangles with a 1 pixel wide stroke. This may\ mean you can't see them unless you scale the canvas view to its original size.</p> <table class=shortcuts> <tr><td class=gpuDrawBoundColor>Bounds for the current draw.</td></tr> <tr><td class=gpuOpBoundColor>Individual bounds for other draws in the same op.</td></tr> <tr><td class=gpuTotalOpColor>Total bounds of the current op.</td></tr> </table> </details> <details open> <summary><b>Overlay Options</b></summary> <checkbox-sk label="Show Clip" title="Show a semi-transparent teal overlay on the areas within the current\ clip." id=clip @change=${ele._clipHandler}></checkbox-sk> <checkbox-sk label="Show Android Device Clip Restriction" title="Show a semi-transparent peach overlay on the areas within the current\ andorid device clip restriction. This is set at the beginning of each frame and recorded in the DrawAnnotation\ Command labeled AndroidDeviceClipRestriction" id=androidclip @change=${ele._androidClipHandler}></checkbox-sk> <checkbox-sk label="Show Origin" title="Show the origin of the coordinate space defined by the current matrix." id=origin @change=${ele._originHandler}></checkbox-sk> <div class="horizontal-flex"> <div class="matrixClipBox"> <h3 class="compact">Clip</h3> <table> <tr><td>${ele._info.ClipRect[0]}</td><td>${ele._info.ClipRect[1]}</td></tr> <tr><td>${ele._info.ClipRect[2]}</td><td>${ele._info.ClipRect[3]}</td></tr> </table> </div> <div class="matrixClipBox"> <h3 class="compact">Matrix</h3> <table> ${ele._matrixTable(ele._info.ViewMatrix)} </table> </div> </div> </div>`; // defined by version.js which is included by main.html and generated in Makefile. private _skiaVersion: string = SKIA_VERSION; private _skiaVersionShort: string = SKIA_VERSION.substring(0, 7); // null as long as no file loaded. private _fileContext: FileContext | null = null; // null until the DebuggerInit promise resolves. private _debugger: Debugger | null = null; // null until either file loaded or cpu/gpu switch toggled private _surface: SkSurface | null = null; // submodules are null until first template render private _androidLayersSk: AndroidLayersSk | null = null; private _debugViewSk: DebugViewSk | null = null; private _commandsSk: CommandsSk | null = null; private _resourcesSk: ResourcesSk | null = null; private _timelineSk: TimelineSk | null = null; private _zoom: ZoomSk | null = null // application state private _targetItem: number = 0; // current command playback index in filtered list // When turned on, always draw to the end of a frame private _drawToEnd: boolean = false; // the index of the last command to alter the pixel under the crosshair private _pointCommandIndex = 0; // The matrix and clip retrieved from the last draw private _info: MatrixClipInfo = { ClipRect: [0, 0, 0, 0], ViewMatrix: [ [1, 0, 0], [0, 1, 0], [0, 0, 1], ], }; // things toggled by the upper right checkboxes. private _gpuMode = true; // true means use gpu private _showOpBounds = false; private _darkBackgrounds = false; // true means dark private _showOverdrawViz = false; private _showClip = false; private _showAndroidClip = false; private _showOrigin = false; constructor() { super(DebuggerPageSk.template); DebuggerInit({ locateFile: (file: string) => `/dist/${file}`, }).then((loadedWasmModule) => { // Save a reference to the module somewhere we can use it later. this._debugger = loadedWasmModule; // File input element should now be enabled, so we need to render. this._render(); // It is now possible to load SKP files. this._checkUrlParams(); }); } connectedCallback() { super.connectedCallback(); this._render(); this._androidLayersSk = this.querySelector<AndroidLayersSk>('android-layers-sk')!; this._debugViewSk = this.querySelector<DebugViewSk>('debug-view-sk')!; this._commandsSk = this.querySelector<CommandsSk>('commands-sk')!; this._resourcesSk = this.querySelector<ResourcesSk>('resources-sk')!; this._timelineSk = this.querySelector<TimelineSk>('timeline-sk')!; this._zoom = this.querySelector<ZoomSk>('zoom-sk')!; this._zoom.source = this._debugViewSk.canvas; this._commandsSk.addEventListener(MoveCommandPositionEvent, (e) => { const detail = (e as CustomEvent<MoveCommandPositionEventDetail>).detail; this._targetItem = detail.position; this._updateDebuggerView(); if (detail.paused) { this._updateJumpButton(this._zoom!.point); } }); this._timelineSk.playsk.addEventListener( ModeChangedManuallyEvent, (e) => { const mode = (e as CustomEvent<ModeChangedManuallyEventDetail>).detail.mode; if (mode === 'pause') { this._setCommands(); } }, ); // this is the timeline, which owns the frame position, telling this element to update this._timelineSk.addEventListener(MoveFrameEvent, (e) => { const frame = (e as CustomEvent<MoveFrameEventDetail>).detail.frame; this._moveFrameTo(frame); }); // this is the command list telling us to show the resource viewer and select an image this._commandsSk.addEventListener(SelectImageEvent, (e) => { this.querySelector<TabsSk>('tabs-sk')!.select(1); const id = (e as CustomEvent<SelectImageEventDetail>).detail.id; this._resourcesSk!.selectItem(id, true); }); this._androidLayersSk.addEventListener(InspectLayerEvent, (e) => { const detail = (e as CustomEvent<InspectLayerEventDetail>).detail; this._inspectLayer(detail.id, detail.frame); this.querySelector<TabsSk>('tabs-sk')!.select(0); }); this.addDocumentEventListener('keydown', this._keyDownHandler.bind(this), true /* useCapture */); this.addDocumentEventListener(MoveCursorEvent, (e) => { const detail = (e as CustomEvent<CursorEventDetail>).detail; // Update this module's cursor-dependent element(s) this._updateJumpButton(detail.position); // re-emit event as render-cursor this.dispatchEvent( new CustomEvent<CursorEventDetail>( RenderCursorEvent, { detail: detail, bubbles: true, }, ), ); }); } private _checkUrlParams() { const params = new URLSearchParams(window.location.search); if (params.has('url')) { const skpurl = params.get('url')!; fetch(skpurl).then((response) => response.arrayBuffer()).then((ab) => { if (ab) { this._openSkpFile(ab); } else { errorMessage(`No data received from ${skpurl}`); } }); } } // Searches for the command which left the given pixel in it's current color, // Updates the Jump button with the result. // Consider disabling this feature alltogether for CPU backed debugging, too slow. private _updateJumpButton(p: Point) { if (!this._debugViewSk!.crosshairActive) { return; // Too slow to do this on every mouse move. } this._pointCommandIndex = this._fileContext!.player.findCommandByPixel( this._surface!, p[0], p[1], this._targetItem, ); this._render(); } // Template helper rendering a number[][] in a table private _matrixTable(m: Matrix3x3 | Matrix4x4) { return (m as number[][]).map((row: number[]) => html`<tr>${row.map((i: number) => html`<td>${i}</td>`)}</tr>`); } // Called when the filename in the file input element changs private _fileInputChanged(e: Event) { // Did the change event result in the file-input element specifing a file? // (user might have cancelled the dialog) const element = e.target as HTMLInputElement; if (element.files?.length === 0) { return; } const file = element.files![0]; // Create a reader and a callback for when the file finishes being read. const reader = new FileReader(); reader.onload = (e: ProgressEvent<FileReader>) => { if (e.target) { this._openSkpFile(e.target.result as ArrayBuffer); } }; reader.readAsArrayBuffer(file); } // Finds the version number from the binary SKP or MSKP file format // This is done in JS because to avoid any chance of SkpFilePlayer crashing on old // versions and not reporting back with a version number. // Overall it was just a lot simpler to do it here. private _skpFileVersion(fileContents: ArrayBuffer): number { const utf8decoder = new TextDecoder(); // only check up to 2000 bytes // MSKP files have a variable sized header before the internal SKP with the version // number we're looking for. const head = new Uint8Array(fileContents).subarray(0, 2000); function isMagicWord(element: number, index: number, array: Uint8Array) { return utf8decoder.decode(array.subarray(index, index + 8)) === 'skiapict'; } // Note that we want to locate the offset in a Uint8Array, not in a string that // might interpret binary stuff before "skiapict" as multi-byte code points. const magicOffset = head.findIndex(isMagicWord); // The unint32 after the first occurance of "skiapict" is the SKP version const version = new Uint32Array(head.subarray(magicOffset + 8, magicOffset + 12))[0]; return version; } // Open an SKP or MSKP file. fileContents is expected to be an arraybuffer // with the file's contents private _openSkpFile(fileContents: ArrayBuffer) { if (!this._debugger) { return; } const version = this._skpFileVersion(fileContents); const minVersion = this._debugger.MinVersion(); if (version < minVersion) { errorMessage(`File version (${version}) is older than this skia build's minimum\ supported version (${minVersion}). Debugger may crash if the file contains unreadable sections.`); } // Create the instance of SkpDebugPlayer and load the file. // This function is provided by helper.js in the JS bundled with the wasm module. const playerResult = this._debugger.SkpFilePlayer(fileContents); if (playerResult.error) { errorMessage(`SKP deserialization error: ${playerResult.error}`); return; } const p = playerResult.player; this._fileContext = { player: p, version: version, frameCount: p.getFrameCount(), }; this._replaceSurface(); if (!this._surface) { errorMessage('Could not create SkSurface, try GPU/CPU toggle.'); return; } p.setGpuOpBounds(this._showOpBounds); p.setOverdrawVis(this._showOverdrawViz); p.setAndroidClipViz(this._showAndroidClip); p.setOriginVisible(this._showOrigin); this._showClip = false; p.setClipVizColor(0); console.log(`Loaded SKP file with ${this._fileContext.frameCount} frames`); this._resourcesSk!.reset(); // Determine if we loaded a single-frame or multi-frame SKP. if (this._fileContext.frameCount > 1) { this._timelineSk!.count = this._fileContext.frameCount; this._timelineSk!.hidden = false; // shared images deserialproc only used with mskps this._resourcesSk!.update(p); } else { this._timelineSk!.hidden = true; } // Pull the command list for the first frame. // triggers render this._setCommands(); this._androidLayersSk!.update(this._commandsSk!.layerInfo, this._fileContext!.player.getLayerSummariesJs(), 0); } // Create a new drawing surface. this should be called when // * GPU/CPU mode changes // * Bounds of the skp change (skp loaded) // * (not yet supported) Color mode changes private _replaceSurface() { if (!this._debugger) { return; } let width = 400; let height = 400; if (this._fileContext) { // From the loaded SKP, player knows how large its picture is. Resize our canvas // to match. const bounds = this._fileContext.player.getBounds(); width = bounds.fRight - bounds.fLeft; height = bounds.fBottom - bounds.fTop; // Still ok to proceed if no skp, the toggle still should work before a file // is picked. } this._replaceSurfaceKnownBounds(width, height); } // replace surface, using the given size private _replaceSurfaceKnownBounds(width: number, height: number) { if (!this._debugger) { return; } const canvas = this._debugViewSk!.resize(width, height); // free the wasm memory of the previous surface if (this._surface) { this._surface.dispose(); } if (this._gpuMode) { this._surface = this._debugger.MakeWebGLCanvasSurface(canvas); } else { this._surface = this._debugger.MakeSWCanvasSurface(canvas); } this._zoom!.source = canvas; } // Moves the player to a frame and updates dependent elements // Note that if you want to move the frame for the whole app, just as if a user did it, // this is not the function you're looking for, instead set this._timelineSk.item private _moveFrameTo(n: number) { // bounds may change too, requring a new surface and gl context, but this is costly and // only rarely necessary const oldBounds = this._fileContext!.player.getBounds(); const newBounds = this._fileContext!.player.getBoundsForFrame(n); if (!this._boundsEqual(oldBounds, newBounds)) { const width = newBounds.fRight - newBounds.fLeft; const height = newBounds.fBottom - newBounds.fTop; this._replaceSurfaceKnownBounds(width, height); } else { // When not changing size, it only needs to be cleared. this._surface!.clear(0); } this._fileContext!.player.changeFrame(n); // If the frame moved and the state is paused, also update the command list const mode = this._timelineSk!.querySelector<PlaySk>('play-sk')!.mode; if (mode === 'pause') { this._setCommands(); this._androidLayersSk!.update(this._commandsSk!.layerInfo, this._fileContext!.player.getLayerSummariesJs(), n); } else { this._updateDebuggerView(); } this._timelineSk!.playsk.movedTo(n); } private _boundsEqual(a: SkIRect, b: SkIRect) { return (a.fLeft === b.fLeft && a.fTop === b.fTop && a.fRight === b.fRight && a.fBottom === b.fBottom); } // Fetch the list of commands for the frame or layer the debugger is currently showing // from wasm. private _setCommands() { // Cache only holds the regular frame's commands, not layers. // const json = (self.inspectedLayer === -1 ? this._memoizedJsonCommandList() // : this._player.jsonCommandList(this._surface)); const json = this._fileContext!.player.jsonCommandList(this._surface!); const parsed = JSON.parse(json) as SkpJsonCommandList; // this will eventually cause a move-command-position event this._commandsSk!.processCommands(parsed); } private _jumpToCommand(i: number) { // listened to by commands-sk this.dispatchEvent( new CustomEvent<JumpCommandEventDetail>( JumpCommandEvent, { detail: { unfilteredIndex: i }, bubbles: true, }, ), ); } // Asks the wasm module to draw to the provided surface. // Up to the command index indidated by this._targetItem _updateDebuggerView(): void { if (!this._fileContext) { return; // Return early if no file. commands-sk tests load data to that // modules but not a whole file. } if (this._drawToEnd) { this._fileContext!.player!.draw(this._surface!); } else { this._fileContext!.player!.drawTo(this._surface!, this._targetItem); } if (!this._gpuMode) { this._surface!.flush(); } this.dispatchEvent( new CustomEvent<CursorEventDetail>( RenderCursorEvent, { detail: { position: [0, 0], onlyData: true }, bubbles: true, }, ), ); const clipmatjson = this._fileContext.player.lastCommandInfo(); this._info = JSON.parse(clipmatjson) as MatrixClipInfo; this._render(); } // controls change handlers private _gpuHandler(e: Event) { this._gpuMode = (e.target as CheckOrRadio).checked; this._replaceSurface(); if (!this._surface) { errorMessage('Could not create SkSurface.'); return; } this._setCommands(); } private _lightDarkHandler(e: Event) { this._darkBackgrounds = (e.target as CheckOrRadio).checked; // should be received by anything in the application that shows a checkerboard // background for transparency this.dispatchEvent( new CustomEvent<ToggleBackgroundEventDetail>( ToggleBackgroundEvent, { detail: { mode: this._darkBackgrounds ? 'dark-checkerboard' : 'light-checkerboard' }, bubbles: true, }, ), ); } private _opBoundsHandler(e: Event) { this._showOpBounds = (e.target as CheckOrRadio).checked; this._fileContext!.player.setGpuOpBounds(this._showOpBounds); this._updateDebuggerView(); } private _overdrawHandler(e: Event) { this._showOverdrawViz = (e.target as CheckOrRadio).checked; this._fileContext!.player.setOverdrawVis(this._showOverdrawViz); this._updateDebuggerView(); } private _clipHandler(e: Event) { this._showClip = (e.target as CheckOrRadio).checked; if (this._showClip) { // ON: 30% transparent dark teal this._fileContext!.player.setClipVizColor(0x500e978d); } else { // OFF: transparent black this._fileContext!.player.setClipVizColor(0); } this._updateDebuggerView(); } private _androidClipHandler(e: Event) { this._showAndroidClip = (e.target as CheckOrRadio).checked; this._fileContext!.player.setAndroidClipViz(this._showAndroidClip); this._updateDebuggerView(); } private _originHandler(e: Event) { this._showOrigin = (e.target as CheckOrRadio).checked; this._fileContext!.player.setOriginVisible(this._showOrigin); this._updateDebuggerView(); } private _updateCursor(x: number, y: number) { this._updateJumpButton([x, y]); this.dispatchEvent( new CustomEvent<CursorEventDetail>( RenderCursorEvent, { detail: { position: [x, y], onlyData: false }, bubbles: true, }, ), ); } private _keyDownHandler(e: KeyboardEvent) { if (this.querySelector<HTMLInputElement>('#text-filter') === document.activeElement) { return; // don't interfere with the filter textbox. } const [x, y] = this._zoom!.point; // If adding a case here, document it in the user-visible keyboard shortcuts area. switch (e.keyCode) { case 74: // J this._updateCursor(x, y + 1); break; case 75: // K this._updateCursor(x, y - 1); break; case 72: // H this._updateCursor(x - 1, y); break; case 76: // L this._updateCursor(x + 1, y); break; case 190: // Period, step command forward this._commandsSk!.keyMove(1); break; case 188: // Comma, step command back this._commandsSk!.keyMove(-1); break; case 87: // w this._timelineSk!.playsk.prev(); break; case 83: // s this._timelineSk!.playsk.next(); break; case 80: // p this._timelineSk!.playsk.togglePlay(); break; default: return; } e.stopPropagation(); } private _inspectLayer(layerId: number, frame: number) { // This method is called any time one of the Inspector/Exit buttons is pressed. // if the the button was on the layer already being inspected, it says "exit" // and -1 is passed to layerId. // It is also called from the jump action in the image resorce viewer. // TODO(nifong): Either disable the timeline or make it have some kind of layer-aware // mode that would jump between updates. At the moment if you move the frame while viewing // a layer, you'll bork the app. this._timelineSk!.item = frame; this._fileContext!.player.setInspectedLayer(layerId); this._replaceSurface(); this._setCommands(); this._commandsSk!.end(); } } define('debugger-page-sk', DebuggerPageSk);
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { debounceTime, filter, tap } from 'rxjs/operators'; import { Ng2SmartTableComponent } from 'ng2-smart-table'; import { NbDialogService } from '@nebular/theme'; import { IProposal, ComponentLayoutStyleEnum, IOrganization, IProposalViewModel, ProposalStatusEnum, IOrganizationContact } from '@gauzy/contracts'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { distinctUntilChange } from '@gauzy/common-angular'; import { combineLatest, Subject } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import * as moment from 'moment'; import { ContactLinksComponent, DateViewComponent, EmployeeLinksComponent, NotesWithTagsComponent } from '../../@shared/table-components'; import { ActionConfirmationComponent, DeleteConfirmationComponent } from '../../@shared/user/forms'; import { PaginationFilterBaseComponent } from '../../@shared/pagination/pagination-filter-base.component'; import { API_PREFIX, ComponentEnum } from '../../@core/constants'; import { StatusBadgeComponent } from '../../@shared/status-badge/status-badge.component'; import { ErrorHandlingService, ProposalsService, Store, ToastrService } from '../../@core/services'; import { ServerDataSource } from '../../@core/utils/smart-table/server.data-source'; import { InputFilterComponent } from '../../@shared/table-filters/input-filter.component'; import { OrganizationContactFilterComponent } from '../../@shared/table-filters'; @UntilDestroy({ checkProperties: true }) @Component({ selector: 'ga-proposals', templateUrl: './proposals.component.html', styleUrls: ['./proposals.component.scss'] }) export class ProposalsComponent extends PaginationFilterBaseComponent implements OnInit, OnDestroy { proposalsTable: Ng2SmartTableComponent; @ViewChild('proposalsTable') set content(content: Ng2SmartTableComponent) { if (content) { this.proposalsTable = content; this.onChangedSource(); } } smartTableSettings: object; employeeId: string | null; selectedDate: Date; proposals: IProposalViewModel[]; smartTableSource: ServerDataSource; dataLayoutStyle = ComponentLayoutStyleEnum.TABLE; componentLayoutStyleEnum = ComponentLayoutStyleEnum; viewComponentName: ComponentEnum = ComponentEnum.PROPOSALS; selectedProposal: IProposalViewModel; proposalStatusEnum = ProposalStatusEnum; successRate: string; totalProposals: number; countAccepted: number = 0; loading: boolean; disableButton = true; organization: IOrganization; subject$: Subject<any> = new Subject(); constructor( private readonly store: Store, private readonly router: Router, private readonly proposalsService: ProposalsService, private readonly toastrService: ToastrService, private readonly dialogService: NbDialogService, private readonly errorHandler: ErrorHandlingService, readonly translateService: TranslateService, private readonly httpClient: HttpClient, ) { super(translateService); this.setView(); } ngOnInit() { this._loadSettingsSmartTable(); this._applyTranslationOnSmartTable(); this.subject$ .pipe( debounceTime(300), tap(() => this.loading = true), tap(() => this.clearItem()), tap(() => this.getProposals()), untilDestroyed(this) ) .subscribe(); const storeOrganization$ = this.store.selectedOrganization$; const storeEmployee$ = this.store.selectedEmployee$; const selectedDate$ = this.store.selectedDate$; combineLatest([storeOrganization$, storeEmployee$, selectedDate$]) .pipe( debounceTime(500), filter(([organization]) => !!organization), tap(([organization]) => (this.organization = organization)), distinctUntilChange(), tap(([organization, employee, date]) => { if (organization) { this.selectedDate = date; this.employeeId = employee ? employee.id : null; this.refreshPagination(); this.subject$.next(true); } }), untilDestroyed(this) ) .subscribe(); } ngAfterViewInit() { const { employeeId } = this.store.user; if (employeeId) { delete this.smartTableSettings['columns']['author']; this.smartTableSettings = Object.assign({}, this.smartTableSettings); } } setView() { this.store .componentLayout$(this.viewComponentName) .pipe( distinctUntilChange(), tap((componentLayout) => this.dataLayoutStyle = componentLayout), filter((componentLayout) => componentLayout === ComponentLayoutStyleEnum.CARDS_GRID), tap(() => this.refreshPagination()), tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } /* * Table on changed source event */ onChangedSource() { this.proposalsTable.source.onChangedSource .pipe( untilDestroyed(this), tap(() => this.clearItem()) ) .subscribe(); } details(selectedItem?: IProposal) { if (selectedItem) { this.selectProposal({ isSelected: true, data: selectedItem }); } this.router.navigate([ `/pages/sales/proposals/details`, this.selectedProposal.id]); } delete(selectedItem?: IProposal) { if (selectedItem) { this.selectProposal({ isSelected: true, data: selectedItem }); } this.dialogService .open(DeleteConfirmationComponent, { context: { recordType: 'Proposal' } }) .onClose.pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { await this.proposalsService.delete( this.selectedProposal.id ); this.subject$.next(true); this.toastrService.success('NOTES.PROPOSALS.DELETE_PROPOSAL'); } catch (error) { this.errorHandler.handleError(error); } } }); } switchToAccepted(selectedItem?: IProposal) { if (selectedItem) { this.selectProposal({ isSelected: true, data: selectedItem }); } this.dialogService .open(ActionConfirmationComponent, { context: { recordType: 'status' } }) .onClose.pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { const { tenantId } = this.store.user; await this.proposalsService.update( this.selectedProposal.id, { status: ProposalStatusEnum.ACCEPTED, tenantId } ); this.subject$.next(true); // TODO translate this.toastrService.success( 'NOTES.PROPOSALS.PROPOSAL_ACCEPTED' ); } catch (error) { this.errorHandler.handleError(error); } } }); } switchToSent(selectedItem?: IProposal) { if (selectedItem) { this.selectProposal({ isSelected: true, data: selectedItem }); } this.dialogService .open(ActionConfirmationComponent, { context: { recordType: 'status' } }) .onClose.pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { const { tenantId } = this.store.user; await this.proposalsService.update( this.selectedProposal.id, { status: ProposalStatusEnum.SENT, tenantId } ); this.subject$.next(true); this.toastrService.success('NOTES.PROPOSALS.PROPOSAL_SENT'); } catch (error) { this.errorHandler.handleError(error); } } }); } private statusMapper = (cell: string) => { let badgeClass: string; if (cell === ProposalStatusEnum.SENT) { badgeClass = 'warning'; cell = this.getTranslation('BUTTONS.SENT'); } else { badgeClass = 'success'; cell = this.getTranslation('BUTTONS.ACCEPTED'); } return { text: cell, class: badgeClass }; } private _loadSettingsSmartTable() { this.smartTableSettings = { actions: false, editable: true, noDataMessage: this.getTranslation('SM_TABLE.NO_DATA_MESSAGE'), columns: { valueDate: { title: this.getTranslation('SM_TABLE.DATE'), type: 'custom', width: '10%', renderComponent: DateViewComponent, filter: false, sortDirection: 'desc' }, jobTitle: { title: this.getTranslation('SM_TABLE.JOB_TITLE'), type: 'custom', width: '25%', renderComponent: NotesWithTagsComponent, filter: { type: 'custom', component: InputFilterComponent, }, filterFunction: (value: string) => { this.setFilter({ field: 'jobPostContent', search: value }); } }, jobPostUrl: { title: this.getTranslation('SM_TABLE.JOB_POST_URL'), type: 'html', width: '25%', filter: false }, statusBadge: { title: this.getTranslation('SM_TABLE.STATUS'), type: 'custom', width: '10%', class: 'text-center', filter: false, renderComponent: StatusBadgeComponent }, organizationContact: { title: this.getTranslation('SM_TABLE.CONTACT_NAME'), type: 'custom', renderComponent: ContactLinksComponent, width: '20%', filter: { type: 'custom', component: OrganizationContactFilterComponent }, filterFunction: (value: IOrganizationContact| null) => { this.setFilter({ field: 'organizationContactId', search: (value)?.id || null }); } }, author: { title: this.getTranslation('SM_TABLE.AUTHOR'), type: 'custom', width: '20%', filter: false, renderComponent: EmployeeLinksComponent, } } }; } selectProposal({ isSelected, data }) { this.disableButton = !isSelected; this.selectedProposal = isSelected ? data : null; } /* * Register Smart Table Source Config */ setSmartTableSource() { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const request = {}; if (this.employeeId) { request['employeeId'] = this.employeeId; delete this.smartTableSettings['columns']['author']; } if (moment(this.selectedDate).isValid()) { request['valueDate'] = moment(this.selectedDate).format('YYYY-MM-DD HH:mm:ss'); } this.smartTableSource = new ServerDataSource(this.httpClient, { endPoint: `${API_PREFIX}/proposal/pagination`, relations: [ 'organization', 'employee', 'employee.user', 'tags', 'organizationContact' ], join: { ...(this.filters.join) ? this.filters.join : {} }, where: { ...{ organizationId, tenantId }, ...request, ...this.filters.where }, resultMap: (proposal: IProposal) => { return this.proposalMapper(proposal); }, finalize: () => { this.loading = false; this.calculateStatistics(); } }); } private calculateStatistics() { this.countAccepted = 0 const proposals = this.smartTableSource.getData(); for (const proposal of proposals) { if (proposal.status === ProposalStatusEnum.ACCEPTED) { this.countAccepted++; } } this.totalProposals = this.smartTableSource.count(); if (this.totalProposals) { this.successRate = ((this.countAccepted / this.totalProposals) * 100).toFixed(0) + ' %'; } else { this.successRate = '0 %'; } } private proposalMapper = (i: IProposal) => { return { id: i.id, valueDate: i.valueDate, jobPostUrl: i.jobPostUrl ? '<a href="' + i.jobPostUrl +`" target="_blank">${i.jobPostUrl}</a>`: '', jobTitle: i.jobPostContent .toString() .replace(/<[^>]*(>|$)|&nbsp;/g, '') .split(/[\s,\n]+/) .slice(0, 3) .join(' '), jobPostContent: i.jobPostContent, proposalContent: i.proposalContent, tags: i.tags, status: i.status, statusBadge: this.statusMapper(i.status), author: i.employee ? i.employee.user ? i.employee.user : '' : '', organizationContact: i.organizationContact ? i.organizationContact : null, }; } private async getProposals() { try { this.setSmartTableSource(); if (this.dataLayoutStyle === ComponentLayoutStyleEnum.CARDS_GRID) { // Initiate GRID view pagination const { activePage, itemsPerPage } = this.pagination; this.smartTableSource.setPaging(activePage, itemsPerPage, false); this.smartTableSource.setSort( [{ field: 'valueDate', direction: 'desc' }], false ); await this.smartTableSource.getElements(); this.proposals = this.smartTableSource.getData(); const count = this.smartTableSource.count(); this.pagination['totalItems'] = count; } } catch (error) { this.toastrService.danger(error); } } private _applyTranslationOnSmartTable() { this.translateService.onLangChange .pipe( tap(() => this._loadSettingsSmartTable()), untilDestroyed(this) ) .subscribe(); } /* * Clear selected item */ clearItem() { this.selectProposal({ isSelected: false, data: null }); this.deselectAll(); } /* * Deselect all table rows */ deselectAll() { if (this.proposalsTable && this.proposalsTable.grid) { this.proposalsTable.grid.dataSet['willSelect'] = 'false'; this.proposalsTable.grid.dataSet.deselectAll(); } } ngOnDestroy() {} }
the_stack
declare namespace Box2D.Common { /** * Color for debug drawing. Each value has the range [0, 1]. **/ export class b2Color { /** * Red **/ public r: number; /** * Green **/ public g: number; /** * Blue **/ public b: number; /** * RGB color as hex. **/ public color: number; /** * Constructor * @param rr Red value * @param gg Green value * @param bb Blue value **/ constructor(rr: number, gg: number, bb: number); /** * Sets the Color to new RGB values. * @param rr Red value * @param gg Green value * @param bb Blue value **/ public Set(rr: number, gg: number, bb: number): void; } } declare namespace Box2D.Common { /** * Controls Box2D global settings. **/ export class b2Settings { /** * b2Assert is used internally to handle assertions. By default, calls are commented out to save performance, so they serve more as documentation than anything else. * @param a Asset an expression is true. **/ public static b2Assert(a: boolean): void; /** * Friction mixing law. Feel free to customize this. * Friction values are usually set between 0 and 1. (0 = no friction, 1 = high friction) * By default this is `return Math.sqrt(friction1, friction2);` * @param friction1 Friction 1 to mix. * @param friction2 Friction 2 to mix. * @return The two frictions mixed as one value. **/ public static b2MixFriction(friction1: number, friction2: number): number; /** * Restitution mixing law. Feel free to customize this. Restitution is used to make objects bounce. * Restitution values are usually set between 0 and 1. (0 = no bounce (inelastic), 1 = perfect bounce (perfectly elastic)) * By default this is `return Math.Max(restitution1, restitution2);` * @param restitution1 Restitution 1 to mix. * @param restitution2 Restitution 2 to mix. * @return The two restitutions mixed as one value. **/ public static b2MixRestitution(restitution1: number, restitution2: number): number; /** * This is used to fatten AABBs in the dynamic tree. This allows proxies to move by a small amount without triggering a tree adjustment. This is in meters. **/ public static b2_aabbExtension: number; /** * This is used to fatten AABBs in the dynamic tree. This is used to predict the future position based on the current displacement. This is a dimensionless multiplier. **/ public static b2_aabbMultiplier: number; /** * A body cannot sleep if its angular velocity is above this tolerance. **/ public static b2_angularSleepTolerance: number; /** * A small angle used as a collision and constraint tolerance. Usually it is chosen to be numerically significant, but visually insignificant. **/ public static b2_angularSlop: number; /** * This scale factor controls how fast overlap is resolved. Ideally this would be 1 so that overlap is removed in one time step. However using values close to 1 often lead to overshoot. **/ public static b2_contactBaumgarte: number; /** * A body cannot sleep if its linear velocity is above this tolerance. **/ public static b2_linearSleepTolerance: number; /** * A small length used as a collision and constraint tolerance. Usually it is chosen to be numerically significant, but visually insignificant. **/ public static b2_linearSlop: number; /** * The maximum angular position correction used when solving constraints. This helps to prevent overshoot. **/ public static b2_maxAngularCorrection: number; /** * The maximum linear position correction used when solving constraints. This helps to prevent overshoot. **/ public static b2_maxLinearCorrection: number; /** * Number of manifold points in a b2Manifold. This should NEVER change. **/ public static b2_maxManifoldPoints: number; /** * The maximum angular velocity of a body. This limit is very large and is used to prevent numerical problems. You shouldn't need to adjust this. **/ public static b2_maxRotation: number; /** * b2_maxRotation squared **/ public static b2_maxRotationSquared: number; /** * Maximum number of contacts to be handled to solve a TOI island. **/ public static b2_maxTOIContactsPerIsland: number; /** * Maximum number of joints to be handled to solve a TOI island. **/ public static b2_maxTOIJointsPerIsland: number; /** * The maximum linear velocity of a body. This limit is very large and is used to prevent numerical problems. You shouldn't need to adjust this. **/ public static b2_maxTranslation: number; /** * b2_maxTranslation squared **/ public static b2_maxTranslationSquared: number; /** * 3.141592653589793 **/ public static b2_pi: number; /** * The radius of the polygon/edge shape skin. This should not be modified. Making this smaller means polygons will have and insufficient for continuous collision. Making it larger may create artifacts for vertex collision. **/ public static b2_polygonRadius: number; /** * The time that a body must be still before it will go to sleep. **/ public static b2_timeToSleep: number; /** * Continuous collision detection (CCD) works with core, shrunken shapes. This is the amount by which shapes are automatically shrunk to work with CCD. This must be larger than b2_linearSlop. * @see also b2_linearSlop **/ public static b2_toiSlop: number; /** * A velocity threshold for elastic collisions. Any collision with a relative linear velocity below this threshold will be treated as inelastic. **/ public static b2_velocityThreshold: number; /** * Maximum unsigned short value. **/ public static USHRT_MAX: number; /** * The current version of Box2D. **/ public static VERSION: string; } } declare namespace Box2D.Common.Math { /** * A 2-by-2 matrix. Stored in column-major order. **/ export class b2Mat22 { /** * Column 1 **/ public col1: b2Vec2; /** * Column 2 **/ public col2: b2Vec2; /** * Empty constructor **/ constructor(); /** * Sets all internal matrix values to absolute values. **/ public Abs(): void; /** * Adds the two 2x2 matricies together and stores the result in this matrix. * @param m 2x2 matrix to add. **/ public AddM(m: b2Mat22): void; /** * Creates a copy of the matrix. * @return Copy of this 2x2 matrix. **/ public Copy(): b2Mat22; /** * Creates a rotation 2x2 matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @param angle Matrix angle (theta). * @return 2x2 matrix. **/ public static FromAngle(angle: number): b2Mat22; /** * Creates a 2x2 matrix from two columns. * @param c1 Column 1 vector. * @param c2 Column 2 vector. * @return 2x2 matrix. **/ public static FromVV(c1: b2Vec2, c2: b2Vec2): b2Mat22; /** * Gets the rotation matrix angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @return The rotation matrix angle (theta). **/ public GetAngle(): number; /** * Compute the inverse of this matrix, such that inv(A) A = identity. * @param out Inverse matrix. * @return Inverse matrix. **/ public GetInverse(out: b2Mat22): b2Mat22; /** * Sets the 2x2 rotation matrix from the given angle. * R(theta) = [ cos(theta) -sin(theta) ] * [ sin(theta) cos(theta) ] * @param angle Matrix angle (theta). **/ public Set(angle: number): void; /** * Sets the 2x2 matrix to identity. **/ public SetIdentity(): void; /** * Sets the 2x2 matrix from a 2x2 matrix. * @param m 2x2 matrix values. **/ public SetM(m: b2Mat22): void; /** * Sets the 2x2 matrix from 2 column vectors. * @param c1 Column 1 vector. * @param c2 Column 2 vector. **/ public SetVV(c1: b2Vec2, c2: b2Vec2): void; /** * Sets the 2x2 matrix to all zeros. **/ public SetZero(): void; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @return Solved vector **/ public Solve(out: b2Vec2, bX: number, bY: number): b2Vec2; } } declare namespace Box2D.Common.Math { /** * A 3-by3 matrix. Stored in column-major order. **/ export class b2Mat33 { /** * Column 1 **/ public col1: b2Vec3; /** * Column 2 **/ public col2: b2Vec3; /** * Column 3 **/ public col3: b2Vec3; /** * Constructor * @param c1 Column 1 * @param c2 Column 2 * @param c3 Column 3 **/ constructor(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3); /** * Adds the two 3x3 matricies together and stores the result in this matrix. * @param m 3x3 matrix to add. **/ public AddM(m: b2Mat33): void; /** * Creates a copy of the matrix. * @return Copy of this 3x3 matrix. **/ public Copy(): b2Mat33; /** * Sets the 3x3 matrix to identity. **/ public SetIdentity(): void; /** * Sets the 3x3 matrix from a 3x3 matrix. * @param m 3x3 matrix values. **/ public SetM(m: b2Mat33): void; /** * Sets the 3x3 matrix from 3 column vectors. * @param c1 Column 1 vector. * @param c2 Column 2 vector. * @param c3 Column 2 vector. **/ public SetVVV(c1: b2Vec3, c2: b2Vec3, c3: b2Vec3): void; /** * Sets the 3x3 matrix to all zeros. **/ public SetZero(): void; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @return Solved vector **/ public Solve22(out: b2Vec2, bX: number, bY: number): b2Vec2; /** * TODO, has something to do with the determinant * @param out Solved vector * @param bX * @param bY * @param bZ * @return Solved vector **/ public Solve33(out: b2Vec3, bX: number, bY: number, bZ: number): b2Vec3; } } declare namespace Box2D.Common.Math { /** * Math utility functions. **/ export class b2Math { /** * Determines if a number is valid. A number is valid if it is finite. * @param x Number to check for validity. * @return True if x is valid, otherwise false. **/ public static IsValid(x: number): boolean; /** * Dot product of two vector 2s. * @param a Vector 2 to use in dot product. * @param b Vector 2 to use in dot product. * @return Dot product of a and b. **/ public static Dot(a: b2Vec2, b: b2Vec2): number; /** * Cross product of two vector 2s. * @param a Vector 2 to use in cross product. * @param b Vector 2 to use in cross product. * @return Cross product of a and b. **/ public static CrossVV(a: b2Vec2, b: b2Vec2): number; /** * Cross product of vector 2 and s. * @param a Vector 2 to use in cross product. * @param s s value. * @return Cross product of a and s. **/ public static CrossVF(a: b2Vec2, s: number): b2Vec2; /** * Cross product of s and vector 2. * @param s s value. * @param a Vector 2 to use in cross product. * @return Cross product of s and a. **/ public static CrossFV(s: number, a: b2Vec2): b2Vec2; /** * Multiply matrix and vector. * @param A Matrix. * @param v Vector. * @return Result. **/ public static MulMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * * @param A * @param v * @return **/ public static MulTMV(A: b2Mat22, v: b2Vec2): b2Vec2; /** * * @param T * @param v * @return **/ public static MulX(T: b2Transform, v: b2Vec2): b2Vec2; /** * * @param T * @param v * @return **/ public static MulXT(T: b2Transform, v: b2Vec2): b2Vec2; /** * Adds two vectors. * @param a First vector. * @param b Second vector. * @return a + b. **/ public static AddVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Subtracts two vectors. * @param a First vector. * @param b Second vector. * @return a - b. **/ public static SubtractVV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Calculates the distance between two vectors. * @param a First vector. * @param b Second vector. * @return Distance between a and b. **/ public static Distance(a: b2Vec2, b: b2Vec2): number; /** * Calculates the squared distance between two vectors. * @param a First vector. * @param b Second vector. * @return dist^2 between a and b. **/ public static DistanceSquared(a: b2Vec2, b: b2Vec2): number; /** * * @param s * @param a * @return **/ public static MulFV(s: number, a: b2Vec2): b2Vec2; /** * * @param A * @param B * @return **/ public static AddMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * * @param A * @param B * @return **/ public static MulMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * * @param A * @param B * @return **/ public static MulTMM(A: b2Mat22, B: b2Mat22): b2Mat22; /** * Creates an ABS number. * @param a Number to ABS. * @return Absolute value of a. **/ public static Abs(a: number): number; /** * Creates an ABS vector. * @param a Vector to ABS all values. * @return Vector with all positive values. **/ public static AbsV(a: b2Vec2): b2Vec2; /** * Creates an ABS matrix. * @param A Matrix to ABS all values. * @return Matrix with all positive values. **/ public static AbsM(A: b2Mat22): b2Mat22; /** * Determines the minimum number. * @param a First number. * @param b Second number. * @return a or b depending on which is the minimum. **/ public static Min(a: number, b: number): number; /** * Determines the minimum vector. * @param a First vector. * @param b Second vector. * @return a or b depending on which is the minimum. **/ public static MinV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Determines the max number. * @param a First number. * @param b Second number. * @return a or b depending on which is the maximum. **/ public static Max(a: number, b: number): number; /** * Determines the max vector. * @param a First vector. * @param b Second vector. * @return a or b depending on which is the maximum. **/ public static MaxV(a: b2Vec2, b: b2Vec2): b2Vec2; /** * Clamp a number to the range of low to high. * @param a Number to clamp. * @param low Low range. * @param high High range. * @return Number a clamped to range of low to high. **/ public static Clamp(a: number, low: number, high: number): number; /** * Clamps a vector to the range of low to high. * @param a Vector to clamp. * @param low Low range. * @param high High range. * @return Vector a clamped to range of low to high. **/ public static ClampV(a: b2Vec2, low: b2Vec2, high: b2Vec2): b2Vec2; /** * Swaps a and b objects. * @param a a -> b. * @param b b -> a. **/ public static Swap(a: any, b: any): void; /** * Generates a random number. * @param return Random number. **/ public static Random(): number; /** * Returns a random number between lo and hi. * @param lo Lowest random number. * @param hi Highest random number. * @return Number between lo and hi. **/ public static RandomRange(lo: number, hi: number): number; /** * Calculates the next power of 2 after the given number. * @param x Number to start search for the next power of 2. * @return The next number that is a power of 2. **/ public static NextPowerOfTwo(x: number): number; /** * Check if a number is a power of 2. * @param x Number to check if it is a power of 2. * @return True if x is a power of 2, otherwise false. **/ public static IsPowerOfTwo(x: number): boolean; /** * Global instance of a zero'ed vector. Use as read-only. **/ public static b2Vec2_zero: b2Vec2; /** * Global instance of a 2x2 identity matrix. Use as read-only. **/ public static b2Mat22_identity: b2Mat22; /** * Global instance of an identity transform. Use as read-only. **/ public static b2Transform_identity: b2Transform; } } declare namespace Box2D.Common.Math { /** * This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin, which may no coincide with the center of mass. However, to support dynamics we must interpolate the center of mass position. **/ export class b2Sweep { /** * World angle. **/ public a: number; /** * World angle. **/ public a0: number; /** * Center world position. **/ public c: b2Vec2; /** * Center world position. **/ public c0: b2Vec2; /** * Local center of mass position. **/ public localCenter: b2Vec2; /** * Time interval = [t0,1], where t0 is in [0,1]. **/ public t0: b2Vec2; /** * Advance the sweep forward, yielding a new initial state. * @t The new initial time. **/ public Advance(t: number): void; /** * Creates a copy of the sweep. **/ public Copy(): b2Sweep; /** * Get the interpolated transform at a specific time. * @param xf Transform at specified time, this is an out parameter. * @param alpha Is a factor in [0,1], where 0 indicates t0. **/ public GetTransform(xf: b2Transform, alpha: number): void; /** * Sets the sweep from a sweep. * @param other Sweep values to copy from. **/ public Set(other: b2Sweep): void; } } declare namespace Box2D.Common.Math { /** * A transform contains translation and rotation. It is used to represent the position and orientation of rigid frames. **/ export class b2Transform { /** * Transform position. **/ public position: b2Vec2; /** * Transform rotation. **/ public R: b2Mat22; /** * The default constructor does nothing (for performance). * @param pos Position * @param r Rotation **/ constructor(pos: b2Vec2, r: b2Mat22); /** * Calculate the angle that the rotation matrix represents. * @return Rotation matrix angle. **/ public GetAngle(): number; /** * Initialize using a position vector and rotation matrix. * @param pos Position * @param r Rotation **/ public Initialize(pos: b2Vec2, r: b2Mat22): void; /** * Sets the transfrom from a transfrom. * @param x Transform to copy values from. **/ public Set(x: b2Transform): void; /** * Set this to the identity transform. **/ public SetIdentity(): void; } } declare namespace Box2D.Common.Math { /** * A 2D column vector. **/ export class b2Vec2 { /** * x value **/ public x: number; /** * y value **/ public y: number; /** * Creates a new vector 2. * @param x x value, default = 0. * @param y y value, default = 0. **/ constructor(x?: number, y?: number); /** * Sets x and y to absolute values. **/ public Abs(): void; /** * Adds the vector 2 to this vector 2. The result is stored in this vector 2. * @param v Vector 2 to add. **/ public Add(v: b2Vec2): void; /** * Creates a copy of the vector 2. * @return Copy of this vector 2. **/ public Copy(): b2Vec2; /** * Cross F V * @param s **/ public CrossFV(s: number): void; /** * Cross V F * @param s **/ public CrossVF(s: number): void; /** * Gets the negative of this vector 2. * @return Negative copy of this vector 2. **/ public GetNegative(): b2Vec2; /** * True if the vector 2 is valid, otherwise false. A valid vector has finite values. * @return True if the vector 2 is valid, otherwise false. **/ public IsValid(): boolean; /** * Calculates the length of the vector 2. * @return The length of the vector 2. **/ public Length(): number; /** * Calculates the length squared of the vector2. * @return The length squared of the vector 2. **/ public LengthSquared(): number; /** * Creates a new vector 2 from the given values. * @param x x value. * @param y y value. **/ public static Make(x: number, y: number): b2Vec2; /** * Calculates which vector has the maximum values and sets this vector to those values. * @param b Vector 2 to compare for maximum values. **/ public MaxV(b: b2Vec2): void; /** * Calculates which vector has the minimum values and sets this vector to those values. * @param b Vector 2 to compare for minimum values. **/ public MinV(b: b2Vec2): void; /** * Matrix multiplication. Stores the result in this vector 2. * @param A Matrix to muliply by. **/ public MulM(A: b2Mat22): void; /** * Vector multiplication. Stores the result in this vector 2. * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Dot product multiplication. Stores the result in this vector 2. * @param A Matrix to multiply by. **/ public MulTM(A: b2Mat22): void; /** * Sets this vector 2 to its negative. **/ public NegativeSelf(): void; /** * Normalizes the vector 2 [0,1]. * @return Length. **/ public Normalize(): number; /** * Sets the vector 2. * @param x x value, default is 0. * @param y y value, default is 0. **/ public Set(x?: number, y?: number): void; /** * Sets the vector 2 from a vector 2. * @param v Vector 2 to copy values from. **/ public SetV(v: b2Vec2): void; /** * Sets the vector 2 to zero values. **/ public SetZero(): void; /** * Subtracts the vector 2 from this vector 2. The result is stored in this vector 2. * @param v Vector 2 to subtract. **/ public Subtract(v: b2Vec2): void; } } declare namespace Box2D.Common.Math { /** * A 2D column vector with 3 elements. **/ export class b2Vec3 { /** * x value. **/ public x: number; /** * y value. **/ public y: number; /** * z value. **/ public z: number; /** * Construct using coordinates x,y,z. * @param x x value, default = 0. * @param y y value, default = 0. * @param z z value, default = 0. **/ constructor(x?: number, y?: number, z?: number); /** * Adds the vector 3 to this vector 3. The result is stored in this vector 3. * @param v Vector 3 to add. **/ public Add(v: b2Vec3): void; /** * Creates a copy of the vector 3. * @return Copy of this vector 3. **/ public Copy(): b2Vec3; /** * Gets the negative of this vector 3. * @return Negative copy of this vector 3. **/ public GetNegative(): b2Vec3; /** * Vector multiplication. Stores the result in this vector 3. * @param a Value to multiple the vector's values by. **/ public Multiply(a: number): void; /** * Sets this vector 3 to its negative. **/ public NegativeSelf(): void; /** * Sets the vector 3. * @param x x value, default is 0. * @param y y value, default is 0. * @param z z value, default is 0. **/ public Set(x?: number, y?: number, z?: number): void; /** * Sets the vector 3 from a vector 3. * @param v Vector 3 to copy values from. **/ public SetV(v: b2Vec3): void; /** * Sets the vector 3 to zero values. **/ public SetZero(): void; /** * Subtracts the vector 3 from this vector 3. The result is stored in this vector 3. * @param v Vector 3 to subtract. **/ public Subtract(v: b2Vec3): void; } } declare namespace Box2D.Collision { /** * Axis aligned bounding box. **/ export class b2AABB { /** * Lower bound. **/ public lowerBound: Box2D.Common.Math.b2Vec2; /** * Upper bound. **/ public upperBound: Box2D.Common.Math.b2Vec2; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. * @param aabb1 First AABB to combine. * @param aabb2 Second AABB to combine. * @return New AABB with max values from aabb1 and aabb2. **/ public static Combine(aabb1: b2AABB, aabb2: b2AABB): b2AABB; /** * Combines two AABBs into one with max values for upper bound and min values for lower bound. The result is stored in this AABB. * @param aabb1 First AABB to combine. * @param aabb2 Second AABB to combine. **/ public Combine(aabb1: b2AABB, aabb2: b2AABB): void; /** * Determines if an AABB is contained within this one. * @param aabb AABB to see if it is contained. * @return True if aabb is contained, otherwise false. **/ public Contains(aabb: b2AABB): boolean; /** * Gets the center of the AABB. * @return Center of this AABB. **/ public GetCenter(): Box2D.Common.Math.b2Vec2; /** * Gets the extents of the AABB (half-widths). * @return Extents of this AABB. **/ public GetExtents(): Box2D.Common.Math.b2Vec2; /** * Verify that the bounds are sorted. * @return True if the bounds are sorted, otherwise false. **/ public IsValid(): boolean; /** * Perform a precise raycast against this AABB. * @param output Ray cast output values. * @param input Ray cast input values. * @return True if the ray cast hits this AABB, otherwise false. **/ public RayCast(output: b2RayCastOutput, input: b2RayCastInput): boolean; /** * Tests if another AABB overlaps this AABB. * @param other Other AABB to test for overlap. * @return True if other overlaps this AABB, otherwise false. **/ public TestOverlap(other: b2AABB): boolean; } } declare namespace Box2D.Collision { /** * We use contact ids to facilitate warm starting. **/ export class b2ContactID { /** * Features **/ public features: Features; /** * ID Key **/ public Key: number; /** * Creates a new Contact ID. **/ constructor(); /** * Copies the Contact ID. * @return Copied Contact ID. **/ public Copy(): b2ContactID; /** * Sets the Contact ID from a Contact ID. * @param id The Contact ID to copy values from. **/ public Set(id: b2ContactID): void; } } declare namespace Box2D.Collision { /** * This structure is used to report contact points. **/ export class b2ContactPoint { /** * The combined friction coefficient. **/ public friction: number; /** * The contact id identifies the features in contact. **/ public id: b2ContactID; /** * Points from shape1 to shape2. **/ public normal: Box2D.Common.Math.b2Vec2; /** * Position in world coordinates. **/ public position: Box2D.Common.Math.b2Vec2; /** * The combined restitution coefficient. **/ public restitution: number; /** * The separation is negative when shapes are touching. **/ public separation: number; /** * The first shape. **/ public shape1: Shapes.b2Shape; /** * The second shape. **/ public shape2: Shapes.b2Shape; /** * Velocity of point on body2 relative to point on body1 (pre-solver). **/ public velocity: Box2D.Common.Math.b2Vec2; } } declare namespace Box2D.Collision { /** * Input for b2Distance. You have to option to use the shape radii in the computation. Even **/ export class b2DistanceInput { /** * Proxy A **/ public proxyA: b2DistanceProxy; /** * Proxy B **/ public proxyB: b2DistanceProxy; /** * Transform A **/ public transformA: Box2D.Common.Math.b2Transform; /** * Transform B **/ public transformB: Box2D.Common.Math.b2Transform; /** * Use shape radii in computation? **/ public useRadii: boolean; } } declare namespace Box2D.Collision { /** * Output calculation for b2Distance. **/ export class b2DistanceOutput { /** * Calculated distance. **/ public distance: number; /** * Number of gjk iterations used in calculation. **/ public iterations: number; /** * Closest point on shape A. **/ public pointA: Box2D.Common.Math.b2Vec2; /** * Closest point on shape B. **/ public pointB: Box2D.Common.Math.b2Vec2; } } declare namespace Box2D.Collision { /** * A distance proxy is used by the GJK algorithm. It encapsulates any shape. **/ export class b2DistanceProxy { /** * Count **/ public m_count: number; /** * Radius **/ public m_radius: number; /** * Verticies **/ public m_vertices: Box2D.Common.Math.b2Vec2[]; /** * Get the supporting vertex index in the given direction. * @param d Direction to look for the supporting vertex. * @return Supporting vertex index. **/ public GetSupport(d: Box2D.Common.Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. * @param d Direction to look for the supporting vertex. * @return Supporting vertex. **/ public GetSupportVertex(d: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get a vertex by index. Used by b2Distance. * @param index Vetex's index. * @return Vertex at the given index. **/ public GetVertex(index: number): Box2D.Common.Math.b2Vec2; /** * Get the vertex count. * @return The number of vertices. (m_vertices.length) **/ public GetVertexCount(): number; /** * Initialize the proxy using the given shape. The shape must remain in scope while the proxy is in use. * @param shape Shape to initialize the distance proxy. **/ public Set(shape: Shapes.b2Shape): void; } } declare namespace Box2D.Collision { /** * A dynamic tree arranges data in a binary tree to accelerate queries such as volume queries and ray casts. Leafs are proxies with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor so that the proxy AABB is bigger than the client object. This allows the client object to move by small amounts without triggering a tree update. Nodes are pooled. **/ export class b2DynamicTree { /** * Constructing the tree initializes the node pool. **/ constructor(); /** * Create a proxy. Provide a tight fitting AABB and a userData. * @param aabb AABB. * @param userDate User defined data for this proxy. * @return Dynamic tree node. **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. This asserts if the id is invalid. * @param proxy Proxy to destroy. **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Gets the Fat AABB for the proxy. * @param proxy Proxy to retrieve Fat AABB. * @return Fat AABB for proxy. **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * Get user data from a proxy. Returns null if the proxy is invalid. * Cast to your type on return. * @param proxy Proxy to retrieve user data from. * @return User data for proxy or null if proxy is invalid. **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * Move a proxy with a swept AABB. If the proxy has moved outside of its fattened AABB, then the proxy is removed from the tree and re-inserted. Otherwise the function returns immediately. * @param proxy Proxy to move. * @param aabb Swept AABB. * @param displacement Extra AABB displacement. **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: Box2D.Common.Math.b2Vec2): boolean; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. * @param callback Called for each proxy that overlaps the supplied AABB. * param proxy Proxy overlapping the supplied AABB. * @aabb Proxies are query for overlap on this AABB. **/ public Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. * @param callback Called for each proxy that is hit by the ray. * param input Ray cast input data. * param proxy The proxy hit by the ray cast. * return Return value is the new value for maxFraction. * @param input Ray cast input data. Query all proxies along this ray cast. **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. * @param iterations Number of rebalance iterations to perform. **/ public Rebalance(iterations: number): void; } } declare namespace Box2D.Collision { /** * The broad-phase is used for computing pairs and performing volume queries and ray casts. This broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the client to consume the new pairs and to track subsequent overlap. **/ export class b2DynamicTreeBroadPhase implements IBroadPhase { /** * Creates the dynamic tree broad phase. **/ constructor(); /** * @see IBroadPhase.CreateProxy **/ public CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * @see IBroadPhase.DestroyProxy **/ public DestroyProxy(proxy: b2DynamicTreeNode): void; /** * @see IBroadPhase.GetFatAABB **/ public GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * @see IBroadPhase.GetProxyCount **/ public GetProxyCount(): number; /** * @see IBroadPhase.GetUserData **/ public GetUserData(proxy: b2DynamicTreeNode): any; /** * @see IBroadPhase.MoveProxy **/ public MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: Box2D.Common.Math.b2Vec2): void; /** * @see IBroadPhase.Query **/ public Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * @see IBroadPhase.RayCast **/ public RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * @see IBroadPhase.Rebalance **/ public Rebalance(iterations: number): void; /** * Tests if two proxies overlap. * @param proxyA First proxy to test. * @param proxyB Second proxy to test. * @return True if the proxyA and proxyB overlap with Fat AABBs, otherwise false. **/ public TestOverlap(proxyA: b2DynamicTreeNode, proxyB: b2DynamicTreeNode): boolean; /** * Update the pairs. This results in pair callbacks. This can only add pairs. * @param callback Called for all new proxy pairs. * param userDataA Proxy A in the pair user data. * param userDataB Proxy B in the pair user data. **/ public UpdatePairs(callback: (userDataA: any, userDataB: any) => void ): void; /** * Validates the dynamic tree. * NOTE: this says "todo" in the current Box2DFlash code. **/ public Validate(): void; } } declare namespace Box2D.Collision { /** * Empty declaration, used in many callbacks within b2DynamicTree. * Use the b2DynamicTree functions to extract data from this shell. **/ export class b2DynamicTreeNode { } } declare namespace Box2D.Collision { /** * A manifold for two touching convex shapes. Box2D supports multiple types of contact: - clip point versus plane with radius - point versus point with radius (circles) The local point usage depends on the manifold type: -e_circles: the local center of circleA -e_faceA: the center of faceA -e_faceB: the center of faceB Similarly the local normal usage: -e_circles: not used -e_faceA: the normal on polygonA -e_faceB: the normal on polygonB We store contacts in this way so that position correction can account for movement, which is critical for continuous physics. All contact scenarios must be expressed in one of these types. This structure is stored across time steps, so we keep it small. **/ export class b2Manifold { /** * Circles **/ public static e_circles: number; /** * Face A **/ public static e_faceA: number; /** * Face B **/ public static e_faceB: number; /** * Not used for Type e_points **/ public m_localPlaneNormal: Box2D.Common.Math.b2Vec2; /** * Usage depends on manifold type **/ public m_localPoint: Box2D.Common.Math.b2Vec2; /** * The number of manifold points **/ public m_pointCount: number; /** * The points of contact **/ public m_points: b2ManifoldPoint[]; /** * Manifold type. **/ public m_type: number; /** * Creates a new manifold. **/ constructor(); /** * Copies the manifold. * @return Copy of this manifold. **/ public Copy(): b2Manifold; /** * Resets this manifold. **/ public Reset(): void; /** * Sets this manifold from another manifold. * @param m Manifold to copy values from. **/ public Set(m: b2Manifold): void; } } declare namespace Box2D.Collision { /** * A manifold point is a contact point belonging to a contact manifold. It holds details related to the geometry and dynamics of the contact points. The local point usage depends on the manifold type: -e_circles: the local center of circleB -e_faceA: the local center of cirlceB or the clip point of polygonB -e_faceB: the clip point of polygonA This structure is stored across time steps, so we keep it small. Note: the impulses are used for internal caching and may not provide reliable contact forces, especially for high speed collisions. **/ export class b2ManifoldPoint { /** * Contact ID. **/ public m_id: b2ContactID; /** * Local contact point. **/ public m_localpoint: Box2D.Common.Math.b2Vec2; /** * Normal impluse for this contact point. **/ public m_normalImpulse: number; /** * Tangent impulse for contact point. **/ public m_tangentImpulse: number; /** * Creates a new manifold point. **/ constructor(); /** * Resets this manifold point. **/ public Reset(): void; /** * Sets this manifold point from a manifold point. * @param m The manifold point to copy values from. **/ public Set(m: b2ManifoldPoint): void; } } declare namespace Box2D.Collision { /** * An oriented bounding box. **/ export class b2OBB { /** * The local centroid. **/ public center: Box2D.Common.Math.b2Vec2; /** * The half-widths. **/ public extents: Box2D.Common.Math.b2Vec2; /** * The rotation matrix. **/ public R: Box2D.Common.Math.b2Mat22; } } declare namespace Box2D.Collision { /** * Ray cast input data. **/ export class b2RayCastInput { /** * Truncate the ray to reach up to this fraction from p1 to p2 **/ public maxFraction: number; /** * The start point of the ray. **/ public p1: Box2D.Common.Math.b2Vec2; /** * The end point of the ray. **/ public p2: Box2D.Common.Math.b2Vec2; /** * Creates a new ray cast input. * @param p1 Start point of the ray, default = null. * @param p2 End point of the ray, default = null. * @param maxFraction Truncate the ray to reach up to this fraction from p1 to p2. **/ constructor(p1?: Box2D.Common.Math.b2Vec2, p2?: Box2D.Common.Math.b2Vec2, maxFraction?: number); } } declare namespace Box2D.Collision { /** * Results of a ray cast. **/ export class b2RayCastOutput { /** * The fraction between p1 and p2 that the collision occurs at. **/ public fraction: number; /** * The normal at the point of collision. **/ public normal: Box2D.Common.Math.b2Vec2; } } declare namespace Box2D.Collision { /** * A line in space between two given vertices. **/ export class b2Segment { /** * The starting point. **/ public p1: Box2D.Common.Math.b2Vec2; /** * The ending point. **/ public p2: Box2D.Common.Math.b2Vec2; /** * Extends or clips the segment so that it's ends lie on the boundary of the AABB. * @param aabb AABB to extend/clip the segement. **/ public Extend(aabb: b2AABB): void; /** * See Extend, this works on the ending point. * @param aabb AABB to extend/clip the ending point. **/ public ExtendBackward(aabb: b2AABB): void; /** * See Extend, this works on the starting point. * @param aabb AABB to extend/clip the starting point. **/ public ExtendForward(aabb: b2AABB): void; /** * Ray cast against this segment with another segment. * @param lambda returns the hit fraction. You can use this to compute the contact point * p = (1 - lambda) * segment.p1 + lambda * segment.p2 * @normal Normal at the contact point. If there is no intersection, the normal is not set. * @param segment Defines the begining and end point of the ray cast. * @param maxLambda a number typically in the range [0,1]. * @return True if there is an intersection, otherwise false. **/ public TestSegment( lambda: number[], normal: Box2D.Common.Math.b2Vec2, segment: b2Segment, maxLambda: number): boolean; } } declare namespace Box2D.Collision { /** * Used to warm start b2Distance. Set count to zero on first call. **/ export class b2SimplexCache { /** * Number in cache. **/ public count: number; /** * Vertices on shape a. **/ public indexA: number[]; /** * Vertices on shape b. **/ public indexB: number[]; /** * Length or area. **/ public metric: number; } } declare namespace Box2D.Collision { /** * Inpute parameters for b2TimeOfImpact **/ export class b2TOIInput { /** * Proxy A **/ public proxyA: b2DistanceProxy; /** * Proxy B **/ public proxyB: b2DistanceProxy; /** * Sweep A **/ public sweepA: Box2D.Common.Math.b2Sweep; /** * Sweep B **/ public sweepB: Box2D.Common.Math.b2Sweep; /** * Tolerance **/ public tolerance: number; } } declare namespace Box2D.Collision { /** * This is used to compute the current state of a contact manifold. **/ export class b2WorldManifold { /** * World vector pointing from A to B. **/ public m_normal: Box2D.Common.Math.b2Vec2; /** * World contact point (point of intersection). **/ public m_points: Box2D.Common.Math.b2Vec2[]; /** * Creates a new b2WorldManifold. **/ constructor(); /** * Evaluate the manifold with supplied transforms. This assumes modest motion from the original state. This does not change the point count, impulses, etc. The radii must come from the shapes that generated the manifold. * @param manifold Manifold to evaluate. * @param xfA A transform. * @param radiusA A radius. * @param xfB B transform. * @param radiusB B radius. **/ public Initialize( manifold: b2Manifold, xfA: Box2D.Common.Math.b2Transform, radiusA: number, xfB: Box2D.Common.Math.b2Transform, radiusB: number): void; } } declare namespace Box2D.Collision { /** * We use contact ids to facilitate warm starting. **/ export class Features { /** * A value of 1 indicates that the reference edge is on shape2. **/ public flip: number; /** * The edge most anti-parallel to the reference edge. **/ public incidentEdge: number; /** * The vertex (0 or 1) on the incident edge that was clipped. **/ public incidentVertex: number; /** * The edge that defines the outward contact normal. **/ public referenceEdge: number; } } declare namespace Box2D.Collision { /** * Interface for objects tracking overlap of many AABBs. **/ export interface IBroadPhase { /** * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs is called. * @param aabb Proxy Fat AABB. * @param userData User defined data. * @return Proxy created from aabb and userData. **/ CreateProxy(aabb: b2AABB, userData: any): b2DynamicTreeNode; /** * Destroy a proxy. It is up to the client to remove any pairs. * @param proxy Proxy to destroy. **/ DestroyProxy(proxy: b2DynamicTreeNode): void; /** * Get the Fat AABB for a proxy. * @param proxy Proxy to retrieve the Fat AABB. **/ GetFatAABB(proxy: b2DynamicTreeNode): b2AABB; /** * Get the number of proxies. * @return Number of proxies. **/ GetProxyCount(): number; /** * Get user data from a proxy. Returns null if the proxy is invalid. * @param proxy Proxy to retrieve user data from. * @return Gets the user data from proxy, or null if the proxy is invalid. **/ GetUserData(proxy: b2DynamicTreeNode): any; /** * Call MoveProxy as many times as you like, then when you are done call UpdatePairs to finalized the proxy pairs (for your time step). * @param proxy Proxy to move. * @param aabb Swept AABB. * @param displacement Extra AABB displacement. **/ MoveProxy(proxy: b2DynamicTreeNode, aabb: b2AABB, displacement: Box2D.Common.Math.b2Vec2): void; /** * Query an AABB for overlapping proxies. The callback is called for each proxy that overlaps the supplied AABB. The callback should match function signature fuction callback(proxy:b2DynamicTreeNode):Boolean and should return false to trigger premature termination. * @param callback Called for each proxy that overlaps the supplied AABB. * param proxy Proxy overlapping the supplied AABB. * @param aabb Proxies are query for overlap on this AABB. **/ Query(callback: (proxy: b2DynamicTreeNode) => boolean, aabb: b2AABB): void; /** * Ray-cast against the proxies in the tree. This relies on the callback to perform a exact ray-cast in the case were the proxy contains a shape. The callback also performs the any collision filtering. This has performance roughly equal to k log(n), where k is the number of collisions and n is the number of proxies in the tree. * @param callback Called for each proxy that is hit by the ray. * param input Ray cast input data. * param proxy The proxy hit by the ray cast. * param return Return value is the new value for maxFraction. * @param input Ray cast input data. Query all proxies along this ray cast. **/ RayCast(callback: (input: b2RayCastInput, proxy: b2DynamicTreeNode) => number, input: b2RayCastInput): void; /** * Perform some iterations to re-balance the tree. * @param iterations Number of rebalance iterations to perform. **/ Rebalance(iterations: number): void; } } declare namespace Box2D.Collision.Shapes { /** * A circle shape. **/ export class b2CircleShape extends b2Shape { /** * Creates a new circle shape. * @param radius Circle radius. **/ constructor(radius?: number); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: Box2D.Common.Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. * @param density **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: Box2D.Common.Math.b2Vec2, offset: number, xf: Box2D.Common.Math.b2Transform, c: Box2D.Common.Math.b2Vec2): number; /** * Copies the circle shape. * @return Copy of this circle shape. **/ public Copy(): b2CircleShape; /** * Get the local position of this circle in its parent body. * @return This circle's local position. **/ public GetLocalPosition(): Box2D.Common.Math.b2Vec2; /** * Get the radius of the circle. * @return This circle's radius. **/ public GetRadius(): number; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: Box2D.Common.Math.b2Transform): boolean; /** * Set the circle shape values from another shape. * @param other The other circle shape to copy values from. **/ public Set(other: b2CircleShape): void; /** * Set the local position of this circle in its parent body. * @param position The new local position of this circle. **/ public SetLocalPosition(position: Box2D.Common.Math.b2Vec2): void; /** * Set the radius of the circle. * @param radius The new radius of the circle. **/ public SetRadius(radius: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: Box2D.Common.Math.b2Transform, p: Box2D.Common.Math.b2Vec2): boolean; } } declare namespace Box2D.Collision.Shapes { /** * This structure is used to build edge shapes. **/ export class b2EdgeChainDef { /** * Whether to create an extra edge between the first and last vertices. **/ public isALoop: boolean; /** * The number of vertices in the chain. **/ public vertexCount: number; /** * The vertices in local coordinates. **/ public vertices: Box2D.Common.Math.b2Vec2; /** * Creates a new edge chain def. **/ constructor(); } } declare namespace Box2D.Collision.Shapes { /** * An edge shape. **/ export class b2EdgeShape extends b2Shape { /** * Creates a new edge shape. * @param v1 First vertex * @param v2 Second vertex **/ constructor(v1: Box2D.Common.Math.b2Vec2, v2: Box2D.Common.Math.b2Vec2); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: Box2D.Common.Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: Box2D.Common.Math.b2Vec2, offset: number, xf: Box2D.Common.Math.b2Transform, c: Box2D.Common.Math.b2Vec2): number; /** * Get the distance from vertex1 to vertex2. * @return Distance from vertex1 to vertex2. **/ public GetLength(): number; /** * Get the local position of vertex1 in the parent body. * @return Local position of vertex1 in the parent body. **/ public GetVertex1(): Box2D.Common.Math.b2Vec2; /** * Get the local position of vertex2 in the parent body. * @return Local position of vertex2 in the parent body. **/ public GetVertex2(): Box2D.Common.Math.b2Vec2; /** * Get a core vertex 1 in local coordinates. These vertices represent a smaller edge that is used for time of impact. * @return core vertex 1 in local coordinates. **/ public GetCoreVertex1(): Box2D.Common.Math.b2Vec2; /** * Get a core vertex 2 in local coordinates. These vertices represent a smaller edge that is used for time of impact. * @return core vertex 2 in local coordinates. **/ public GetCoreVertex2(): Box2D.Common.Math.b2Vec2; /** * Get a perpendicular unit vector, pointing from the solid side to the empty side. * @return Normal vector. **/ public GetNormalVector(): Box2D.Common.Math.b2Vec2; /** * Get a parallel unit vector, pointing from vertex 1 to vertex 2. * @return Vertex 1 to vertex 2 directional vector. **/ public GetDirectionVector(): Box2D.Common.Math.b2Vec2; /** * Returns a unit vector halfway between direction and previous direction. * @return Halfway unit vector between direction and previous direction. **/ public GetCorner1Vector(): Box2D.Common.Math.b2Vec2; /** * Returns a unit vector halfway between direction and previous direction. * @return Halfway unit vector between direction and previous direction. **/ public GetCorner2Vector(): Box2D.Common.Math.b2Vec2; /** * Determines if the first corner of this edge bends towards the solid side. * @return True if convex, otherwise false. **/ public Corner1IsConvex(): boolean; /** * Determines if the second corner of this edge bends towards the solid side. * @return True if convex, otherwise false. **/ public Corner2IsConvex(): boolean; /** * Get the first vertex and apply the supplied transform. * @param xf Transform to apply. * @return First vertex with xf transform applied. **/ public GetFirstVertex(xf: Box2D.Common.Math.b2Transform): Box2D.Common.Math.b2Vec2; /** * Get the next edge in the chain. * @return Next edge shape or null if there is no next edge shape. **/ public GetNextEdge(): b2EdgeShape; /** * Get the previous edge in the chain. * @return Previous edge shape or null if there is no previous edge shape. **/ public GetPrevEdge(): b2EdgeShape; /** * Get the support point in the given world direction with the supplied transform. * @param xf Transform to apply. * @param dX X world direction. * @param dY Y world direction. * @return Support point. **/ public Support(xf: Box2D.Common.Math.b2Transform, dX: number, dY: number): Box2D.Common.Math.b2Vec2; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: Box2D.Common.Math.b2Transform): boolean; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: Box2D.Common.Math.b2Transform, p: Box2D.Common.Math.b2Vec2): boolean; } } declare namespace Box2D.Collision.Shapes { /** * This holds the mass data computed for a shape. **/ export class b2MassData { /** * The position of the shape's centroid relative to the shape's origin. **/ public center: Box2D.Common.Math.b2Vec2; /** * The rotational inertia of the shape. This may be about the center or local origin, depending on usage. **/ public I: number; /** * The mass of the shape, usually in kilograms. **/ public mass: number; } } declare namespace Box2D.Collision.Shapes { /** * Convex polygon. The vertices must be in CCW order for a right-handed coordinate system with the z-axis coming out of the screen. **/ export class b2PolygonShape extends b2Shape { /** * Creates a b2PolygonShape from a vertices list. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsArray(vertices: Box2D.Common.Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Build vertices to represent an axis-aligned box. * @param hx The half-width. * @param hy The half-height. * @return Box polygon shape. **/ public static AsBox(hx: number, hy: number): b2PolygonShape; /** * Creates a single edge from two vertices. * @param v1 First vertex. * @param v2 Second vertex. * @return Edge polygon shape. **/ public static AsEdge(v1: Box2D.Common.Math.b2Vec2, b2: Box2D.Common.Math.b2Vec2): b2PolygonShape; /** * Build vertices to represent an oriented box. * @param hx The half-width. * @param hy The half-height. * @param center The center of the box in local coordinates, default is null (no center?) * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public static AsOrientedBox(hx: number, hy: number, center?: Box2D.Common.Math.b2Vec2, angle?: number): b2PolygonShape; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public static AsVector(vertices: Box2D.Common.Math.b2Vec2[], vertexCount?: number): b2PolygonShape; /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: Box2D.Common.Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: Box2D.Common.Math.b2Vec2, offset: number, xf: Box2D.Common.Math.b2Transform, c: Box2D.Common.Math.b2Vec2): number; /** * Clone the shape. **/ public Copy(): b2PolygonShape; /** * Get the edge normal vectors. There is one for each vertex. * @return List of edge normal vectors for each vertex. **/ public GetNormals(): Box2D.Common.Math.b2Vec2[]; /** * Get the supporting vertex index in the given direction. * @param d Direction to look. * @return Vertex index supporting the direction. **/ public GetSupport(d: Box2D.Common.Math.b2Vec2): number; /** * Get the supporting vertex in the given direction. * @param d Direciton to look. * @return Vertex supporting the direction. **/ public GetSupportVertex(d: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the vertex count. * @return Vertex count. **/ public GetVertexCount(): number; /** * Get the vertices in local coordinates. * @return List of the vertices in local coordinates. **/ public GetVertices(): Box2D.Common.Math.b2Vec2[]; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: Box2D.Common.Math.b2Transform): boolean; /** * Set the shape values from another shape. * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Copy vertices. This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount Number of vertices in the shape, default value is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsArray(vertices: Box2D.Common.Math.b2Vec2[], vertexCount?: number): void; /** * Build vertices to represent an axis-aligned box. * @param hx The half-width. * @param hy The half-height. * @return Box polygon shape. **/ public SetAsBox(hx: number, hy: number): void; /** * Creates a single edge from two vertices. * @param v1 First vertex. * @param v2 Second vertex. * @return Edge polygon shape. **/ public SetAsEdge(v1: Box2D.Common.Math.b2Vec2, b2: Box2D.Common.Math.b2Vec2): void; /** * Build vertices to represent an oriented box. * @param hx The half-width. * @param hy The half-height. * @param center The center of the box in local coordinates, default is null (no center?) * @param angle The rotation of the box in local coordinates, default is 0.0. * @return Oriented box shape. **/ public SetAsOrientedBox(hx: number, hy: number, center?: Box2D.Common.Math.b2Vec2, angle?: number): void; /** * This assumes the vertices define a convex polygon. It is assumed that the exterior is the the right of each edge. * @param vertices List of vertices to create the polygon shape from. * @param vertexCount The number of vertices, default is 0 and in the box2dweb.js code it is ignored. * @return Convex polygon shape. **/ public SetAsVector(vertices: any[], vertexCount?: number): void; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: Box2D.Common.Math.b2Transform, p: Box2D.Common.Math.b2Vec2): boolean; } } declare namespace Box2D.Collision.Shapes { /** * A shape is used for collision detection. Shapes are created in b2Body. You can use shape for collision detection before they are attached to the world. * Warning: you cannot reuse shapes. **/ export class b2Shape { /** * Return value for TestSegment indicating a hit. **/ public static e_hitCollide: number; /** * Return value for TestSegment indicating a miss. **/ public static e_missCollide: number; /** * Return value for TestSegment indicating that the segment starting point, p1, is already inside the shape. **/ public static startsInsideCollide: number; // Note: these enums are public in the source but no referenced by the documentation public static e_unknownShape: number; public static e_circleShape: number; public static e_polygonShape: number; public static e_edgeShape: number; public static e_shapeTypeCount: number; /** * Creates a new b2Shape. **/ constructor(); /** * Given a transform, compute the associated axis aligned bounding box for this shape. * @param aabb Calculated AABB, this argument is `out`. * @param xf Transform to calculate the AABB. **/ public ComputeAABB(aabb: b2AABB, xf: Box2D.Common.Math.b2Transform): void; /** * Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. * @param massData Calculate the mass, this argument is `out`. * @param density Density. **/ public ComputeMass(massData: b2MassData, density: number): void; /** * Compute the volume and centroid of this shape intersected with a half plane * @param normal The surface normal. * @param offset The surface offset along the normal. * @param xf The shape transform. * @param c The centroid, this argument is `out`. **/ public ComputeSubmergedArea( normal: Box2D.Common.Math.b2Vec2, offset: number, xf: Box2D.Common.Math.b2Transform, c: Box2D.Common.Math.b2Vec2): number; /** * Clone the shape. **/ public Copy(): b2Shape; /** * Get the type of this shape. You can use this to down cast to the concrete shape. **/ public GetType(): number; /** * Cast a ray against this shape. * @param output Ray cast results, this argument is `out`. * @param input Ray cast input parameters. * @param transform The transform to be applied to the shape. * @param return True if the ray hits the shape, otherwise false. **/ public RayCast( output: b2RayCastOutput, input: b2RayCastInput, transform: Box2D.Common.Math.b2Transform): boolean; /** * Set the shape values from another shape. * @param other The other shape to copy values from. **/ public Set(other: b2Shape): void; /** * Test if two shapes overlap with the applied transforms. * @param shape1 shape to test for overlap with shape2. * @param transform1 shape1 transform to apply. * @param shape2 shape to test for overlap with shape1. * @param transform2 shape2 transform to apply. * @return True if shape1 and shape2 overlap, otherwise false. **/ public static TestOverlap( shape1: b2Shape, transform1: Box2D.Common.Math.b2Transform, shape2: b2Shape, transform2: Box2D.Common.Math.b2Transform): boolean; /** * Test a point for containment in this shape. This only works for convex shapes. * @param xf Shape world transform. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(xf: Box2D.Common.Math.b2Transform, p: Box2D.Common.Math.b2Vec2): boolean; } } declare namespace Box2D.Dynamics { /** * A rigid body. **/ export class b2Body { /** * Dynamic Body **/ public static b2_dynamicBody: number; /** * Kinematic Body **/ public static b2_kinematicBody: number; /** * Static Body **/ public static b2_staticBody: number; /** * Apply a force at a world point. If the force is not applied at the center of mass, it will generate a torque and affect the angular velocity. This wakes up the body. * @param force The world force vector, usually in Newtons (N). * @param point The world position of the point of application. **/ public ApplyForce(force: Box2D.Common.Math.b2Vec2, point: Box2D.Common.Math.b2Vec2): void; /** * Apply an impulse at a point. This immediately modifies the velocity. It also modifies the angular velocity if the point of application is not at the center of mass. This wakes up the body. * @param impules The world impulse vector, usually in N-seconds or kg-m/s. * @param point The world position of the point of application. **/ public ApplyImpulse(impulse: Box2D.Common.Math.b2Vec2, point: Box2D.Common.Math.b2Vec2): void; /** * Apply a torque. This affects the angular velocity without affecting the linear velocity of the center of mass. This wakes up the body. * @param torque Force applied about the z-axis (out of the screen), usually in N-m. **/ public ApplyTorque(torque: number): void; /** * Creates a fixture and attach it to this body. Use this function if you need to set some fixture parameters, like friction. Otherwise you can create the fixture directly from a shape. If the density is non-zero, this function automatically updates the mass of the body. Contacts are not created until the next time step. * @warning This function is locked during callbacks. * @param def The fixture definition; * @return The created fixture. **/ public CreateFixture(def: b2FixtureDef): b2Fixture; /** * Creates a fixture from a shape and attach it to this body. This is a convenience function. Use b2FixtureDef if you need to set parameters like friction, restitution, user data, or filtering. This function automatically updates the mass of the body. * @warning This function is locked during callbacks. * @param shape The shaped of the fixture (to be cloned). * @param density The shape density, default is 0.0, set to zero for static bodies. * @return The created fixture. **/ public CreateFixture2(shape: Box2D.Collision.Shapes.b2Shape, density?: number): b2Fixture; /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys all contacts associated with this fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. All fixtures attached to a body are implicitly destroyed when the body is destroyed. * @warning This function is locked during callbacks. * @param fixture The fixed to be removed. **/ public DestroyFixture(fixture: b2Fixture): void; /** * Get the angle in radians. * @return The current world rotation angle in radians **/ public GetAngle(): number; /** * Get the angular damping of the body. * @return Angular damping of the body. **/ public GetAngularDamping(): number; /** * Get the angular velocity. * @return The angular velocity in radians/second. **/ public GetAngularVelocity(): number; /** * Get the list of all contacts attached to this body. * @return List of all contacts attached to this body. **/ public GetContactList(): Contacts.b2ContactEdge; /** * Get the list of all controllers attached to this body. * @return List of all controllers attached to this body. **/ public GetControllerList(): Controllers.b2ControllerEdge; /** * Get the definition containing the body properties. * @note This provides a feature specific to this port. * @return The body's definition. **/ public GetDefinition(): b2BodyDef; /** * Get the list of all fixtures attached to this body. * @return List of all fixtures attached to this body. **/ public GetFixtureList(): b2Fixture; /** * Get the central rotational inertia of the body. * @return The rotational inertia, usually in kg-m^2. **/ public GetInertia(): number; /** * Get the list of all joints attached to this body. * @return List of all joints attached to this body. **/ public GetJointList(): Joints.b2JointEdge; /** * Get the linear damping of the body. * @return The linear damping of the body. **/ public GetLinearDamping(): number; /** * Get the linear velocity of the center of mass. * @return The linear velocity of the center of mass. **/ public GetLinearVelocity(): Box2D.Common.Math.b2Vec2; /** * Get the world velocity of a local point. * @param localPoint Point in local coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromLocalPoint(localPoint: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the world linear velocity of a world point attached to this body. * @param worldPoint Point in world coordinates. * @return The world velocity of the point. **/ public GetLinearVelocityFromWorldPoint(worldPoint: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the local position of the center of mass. * @return Local position of the center of mass. **/ public GetLocalCenter(): Box2D.Common.Math.b2Vec2; /** * Gets a local point relative to the body's origin given a world point. * @param worldPoint Pointin world coordinates. * @return The corresponding local point relative to the body's origin. **/ public GetLocalPoint(worldPoint: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Gets a local vector given a world vector. * @param worldVector World vector. * @return The corresponding local vector. **/ public GetLocalVector(worldVector: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the total mass of the body. * @return The body's mass, usually in kilograms (kg). **/ public GetMass(): number; /** * Get the mass data of the body. The rotational inertial is relative to the center of mass. * @param data Body's mass data, this argument is `out`. **/ public GetMassData(data: Box2D.Collision.Shapes.b2MassData): void; /** * Get the next body in the world's body list. * @return Next body in the world's body list. **/ public GetNext(): b2Body; /** * Get the world body origin position. * @return World position of the body's origin. **/ public GetPosition(): Box2D.Common.Math.b2Vec2; /** * Get the body transform for the body's origin. * @return World transform of the body's origin. **/ public GetTransform(): Box2D.Common.Math.b2Transform; /** * Get the type of this body. * @return Body type as uint. **/ public GetType(): number; /** * Get the user data pointer that was provided in the body definition. * @return User's data, cast to the correct type. **/ public GetUserData(): any; /** * Get the parent world of this body. * @return Body's world. **/ public GetWorld(): b2World; /** * Get the world position of the center of mass. * @return World position of the center of mass. **/ public GetWorldCenter(): Box2D.Common.Math.b2Vec2; /** * Get the world coordinates of a point given the local coordinates. * @param localPoint Point on the body measured relative to the body's origin. * @return localPoint expressed in world coordinates. **/ public GetWorldPoint(localPoint: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the world coordinates of a vector given the local coordinates. * @param localVector Vector fixed in the body. * @return localVector expressed in world coordinates. **/ public GetWorldVector(localVector: Box2D.Common.Math.b2Vec2): Box2D.Common.Math.b2Vec2; /** * Get the active state of the body. * @return True if the body is active, otherwise false. **/ public IsActive(): boolean; /** * Get the sleeping state of this body. * @return True if the body is awake, otherwise false. **/ public IsAwake(): boolean; /** * Is the body treated like a bullet for continuous collision detection? * @return True if the body is treated like a bullet, otherwise false. **/ public IsBullet(): boolean; /** * Does this body have fixed rotation? * @return True for fixed, otherwise false. **/ public IsFixedRotation(): boolean; /** * Is this body allowed to sleep? * @return True if the body can sleep, otherwise false. **/ public IsSleepingAllowed(): boolean; /** * Merges another body into this. Only fixtures, mass and velocity are effected, Other properties are ignored. * @note This provides a feature specific to this port. **/ public Merge(other: b2Body): void; /** * This resets the mass properties to the sum of the mass properties of the fixtures. This normally does not need to be called unless you called SetMassData to override the mass and later you want to reset the mass. **/ public ResetMassData(): void; /** * Set the active state of the body. An inactive body is not simulated and cannot be collided with or woken up. If you pass a flag of true, all fixtures will be added to the broad-phase. If you pass a flag of false, all fixtures will be removed from the broad-phase and all contacts will be destroyed. Fixtures and joints are otherwise unaffected. You may continue to create/destroy fixtures and joints on inactive bodies. Fixtures on an inactive body are implicitly inactive and will not participate in collisions, ray-casts, or queries. Joints connected to an inactive body are implicitly inactive. An inactive body is still owned by a b2World object and remains in the body list. * @param flag True to activate, false to deactivate. **/ public SetActive(flag: boolean): void; /** * Set the world body angle * @param angle New angle of the body. **/ public SetAngle(angle: number): void; /** * Set the angular damping of the body. * @param angularDamping New angular damping value. **/ public SetAngularDamping(angularDamping: number): void; /** * Set the angular velocity. * @param omega New angular velocity in radians/second. **/ public SetAngularVelocity(omega: number): void; /** * Set the sleep state of the body. A sleeping body has vety low CPU cost. * @param flag True to set the body to awake, false to put it to sleep. **/ public SetAwake(flag: boolean): void; /** * Should this body be treated like a bullet for continuous collision detection? * @param flag True for bullet, false for normal. **/ public SetBullet(flag: boolean): void; /** * Set this body to have fixed rotation. This causes the mass to be reset. * @param fixed True for no rotation, false to allow for rotation. **/ public SetFixedRotation(fixed: boolean): void; /** * Set the linear damping of the body. * @param linearDamping The new linear damping for this body. **/ public SetLinearDamping(linearDamping: number): void; /** * Set the linear velocity of the center of mass. * @param v New linear velocity of the center of mass. **/ public SetLinearVelocity(v: Box2D.Common.Math.b2Vec2): void; /** * Set the mass properties to override the mass properties of the fixtures Note that this changes the center of mass position. Note that creating or destroying fixtures can also alter the mass. This function has no effect if the body isn't dynamic. * @warning The supplied rotational inertia should be relative to the center of mass. * @param massData New mass data properties. **/ public SetMassData(massData: Box2D.Collision.Shapes.b2MassData): void; /** * Set the world body origin position. * @param position New world body origin position. **/ public SetPosition(position: Box2D.Common.Math.b2Vec2): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. * @param position New world body origin position. * @param angle New world rotation angle of the body in radians. **/ public SetPositionAndAngle(position: Box2D.Common.Math.b2Vec2, angle: number): void; /** * Is this body allowed to sleep * @param flag True if the body can sleep, false if not. **/ public SetSleepingAllowed(flag: boolean): void; /** * Set the position of the body's origin and rotation (radians). This breaks any contacts and wakes the other bodies. Note this is less efficient than the other overload - you should use that if the angle is available. * @param xf Body's origin and rotation (radians). **/ public SetTransform(xf: Box2D.Common.Math.b2Transform): void; /** * Set the type of this body. This may alter the mass and velocity * @param type Type enum. **/ public SetType(type: number): void; /** * Set the user data. Use this to store your application specific data. * @param data The user data for this body. **/ public SetUserData(data: any): void; /** * Splits a body into two, preserving dynamic properties * @note This provides a feature specific to this port. * @param callback * @return The newly created bodies from the split. **/ public Split(callback: (fixture: b2Fixture) => boolean): b2Body; } } declare namespace Box2D.Dynamics { /** * A body definition holds all the data needed to construct a rigid body. You can safely re-use body definitions. **/ export class b2BodyDef { /** * Does this body start out active? **/ public active: boolean; /** * Set this flag to false if this body should never fall asleep. Note that this increases CPU usage. **/ public allowSleep: boolean; /** * The world angle of the body in radians. **/ public angle: number; /** * Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large. **/ public angularDamping: number; /** * The angular velocity of the body. **/ public angularVelocity: number; /** * Is this body initially awake or sleeping? **/ public awake: boolean; /** * Is this a fast moving body that should be prevented from tunneling through other moving bodies? Note that all bodies are prevented from tunneling through static bodies. * @warning You should use this flag sparingly since it increases processing time. **/ public bullet: boolean; /** * Should this body be prevented from rotating? Useful for characters. **/ public fixedRotation: boolean; /** * Scales the inertia tensor. * @warning Experimental **/ public inertiaScale: number; /** * Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is large. **/ public linearDamping: number; /** * The linear velocity of the body's origin in world co-ordinates. **/ public linearVelocity: Box2D.Common.Math.b2Vec2; /** * The world position of the body. Avoid creating bodies at the origin since this can lead to many overlapping shapes. **/ public position: Box2D.Common.Math.b2Vec2; /** * The body type: static, kinematic, or dynamic. A member of the b2BodyType class . * @note If a dynamic body would have zero mass, the mass is set to one. **/ public type: number; /** * Use this to store application specific body data. **/ public userData: any; } } declare namespace Box2D.Dynamics { /** * Implement this class to provide collision filtering. In other words, you can implement this class if you want finer control over contact creation. **/ export class b2ContactFilter { /** * Return true if the given fixture should be considered for ray intersection. By default, userData is cast as a b2Fixture and collision is resolved according to ShouldCollide. * @note This function is not in the box2dweb.as code -- might not work. * @see b2World.Raycast() * @see b2ContactFilter.ShouldCollide() * @param userData User provided data. Comments indicate that this might be a b2Fixture. * @return True if the fixture should be considered for ray intersection, otherwise false. **/ public RayCollide(userData: any): boolean; /** * Return true if contact calculations should be performed between these two fixtures. * @warning For performance reasons this is only called when the AABBs begin to overlap. * @param fixtureA b2Fixture potentially colliding with fixtureB. * @param fixtureB b2Fixture potentially colliding with fixtureA. * @return True if fixtureA and fixtureB probably collide requiring more calculations, otherwise false. **/ public ShouldCollide(fixtureA: b2Fixture, fixtureB: b2Fixture): boolean; } } declare namespace Box2D.Dynamics { /** * Contact impulses for reporting. Impulses are used instead of forces because sub-step forces may approach infinity for rigid body collisions. These match up one-to-one with the contact points in b2Manifold. **/ export class b2ContactImpulse { /** * Normal impulses. **/ public normalImpulses: Box2D.Common.Math.b2Vec2; /** * Tangent impulses. **/ public tangentImpulses: Box2D.Common.Math.b2Vec2; } } declare namespace Box2D.Dynamics { /** * Implement this class to get contact information. You can use these results for things like sounds and game logic. You can also get contact results by traversing the contact lists after the time step. However, you might miss some contacts because continuous physics leads to sub-stepping. Additionally you may receive multiple callbacks for the same contact in a single time step. You should strive to make your callbacks efficient because there may be many callbacks per time step. * @warning You cannot create/destroy Box2D entities inside these callbacks. **/ export class b2ContactListener { /** * Called when two fixtures begin to touch. * @param contact Contact point. **/ public BeginContact(contact: Contacts.b2Contact): void; /** * Called when two fixtures cease to touch. * @param contact Contact point. **/ public EndContact(contact: Contacts.b2Contact): void; /** * This lets you inspect a contact after the solver is finished. This is useful for inspecting impulses. Note: the contact manifold does not include time of impact impulses, which can be arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly in a separate data structure. Note: this is only called for contacts that are touching, solid, and awake. * @param contact Contact point. * @param impulse Contact impulse. **/ public PostSolve(contact: Contacts.b2Contact, impulse: b2ContactImpulse): void; /** * This is called after a contact is updated. This allows you to inspect a contact before it goes to the solver. If you are careful, you can modify the contact manifold (e.g. disable contact). A copy of the old manifold is provided so that you can detect changes. Note: this is called only for awake bodies. Note: this is called even when the number of contact points is zero. Note: this is not called for sensors. Note: if you set the number of contact points to zero, you will not get an EndContact callback. However, you may get a BeginContact callback the next step. * @param contact Contact point. * @param oldManifold Old manifold. **/ public PreSolve(contact: Contacts.b2Contact, oldManifold: Box2D.Collision.b2Manifold): void; } } declare namespace Box2D.Dynamics { /** * Implement and register this class with a b2World to provide debug drawing of physics entities in your game. * @example Although Box2D is a physics engine and therefore has nothing to do with drawing, Box2dFlash provides such methods for debugging which are defined in the b2DebugDraw class. In Box2dWeb, a b2DebugDraw takes a canvas-context instead of a Sprite: * * var debugDraw = new Box2D.Dynamics.b2DebugDraw(); * debugDraw.SetSprite(document.GetElementsByTagName("canvas")[0].getContext("2d")); **/ export class b2DebugDraw { /** * Draw axis aligned bounding boxes. **/ public static e_aabbBit: number; /** * Draw center of mass frame. **/ public static e_centerOfMassBit: number; /** * Draw controllers. **/ public static e_controllerBit: number; /** * Draw joint connections. **/ public static e_jointBit: number; /** * Draw broad-phase pairs. **/ public static e_pairBit: number; /** * Draw shapes. **/ public static e_shapeBit: number; /** * Constructor. **/ constructor(); /** * Append flags to the current flags. * @param flags Flags to add. **/ public AppendFlags(flags: number): void; /** * Clear flags from the current flags. * @param flags flags to clear. **/ public ClearFlags(flags: number): void; /** * Draw a circle. * @param center Circle center point. * @param radius Circle radius. * @param color Circle draw color. **/ public DrawCircle(center: Box2D.Common.Math.b2Vec2, radius: number, color: Box2D.Common.b2Color): void; /** * Draw a closed polygon provided in CCW order. * @param vertices Polygon verticies. * @param vertexCount Number of vertices in the polygon, usually vertices.length. * @param color Polygon draw color. **/ public DrawPolygon(vertices: Box2D.Common.Math.b2Vec2[], vertexCount: number, color: Box2D.Common.b2Color): void; /** * Draw a line segment. * @param p1 Line beginpoint. * @param p2 Line endpoint. * @param color Line color. **/ public DrawSegment(p1: Box2D.Common.Math.b2Vec2, p2: Box2D.Common.Math.b2Vec2, color: Box2D.Common.b2Color): void; /** * Draw a solid circle. * @param center Circle center point. * @param radius Circle radius. * @param axis Circle axis. * @param color Circle color. **/ public DrawSolidCircle(center: Box2D.Common.Math.b2Vec2, radius: number, axis: Box2D.Common.Math.b2Vec2, color: Box2D.Common.b2Color): void; /** * Draw a solid closed polygon provided in CCW order. * @param vertices Polygon verticies. * @param vertexCount Number of vertices in the polygon, usually vertices.length. * @param color Polygon draw color. **/ public DrawSolidPolygon(vertices: Box2D.Common.Math.b2Vec2[], vertexCount: number, color: Box2D.Common.b2Color): void; /** * Draw a transform. Choose your own length scale. * @param xf Transform to draw. **/ public DrawTransform(xf: Box2D.Common.Math.b2Transform): void; /** * Get the alpha value used for lines. * @return Alpha value used for drawing lines. **/ public GetAlpha(): number; /** * Get the draw scale. * @return Draw scale ratio. **/ public GetDrawScale(): number; /** * Get the alpha value used for fills. * @return Alpha value used for drawing fills. **/ public GetFillAlpha(): number; /** * Get the drawing flags. * @return Drawing flags. **/ public GetFlags(): number; /** * Get the line thickness. * @return Line thickness. **/ public GetLineThickness(): number; /** * Get the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called GetSprite(). * @return The HTML Canvas Element used for debug drawing. **/ public GetSprite(): CanvasRenderingContext2D; /** * Get the scale used for drawing XForms. * @return Scale for drawing transforms. **/ public GetXFormScale(): number; /** * Set the alpha value used for lines. * @param alpha Alpha value for drawing lines. **/ public SetAlpha(alpha: number): void; /** * Set the draw scale. * @param drawScale Draw scale ratio. **/ public SetDrawScale(drawScale: number): void; /** * Set the alpha value used for fills. * @param alpha Alpha value for drawing fills. **/ public SetFillAlpha(alpha: number): void; /** * Set the drawing flags. * @param flags Sets the drawing flags. **/ public SetFlags(flags: number): void; /** * Set the line thickness. * @param lineThickness The new line thickness. **/ public SetLineThickness(lineThickness: number): void; /** * Set the HTML Canvas Element for drawing. * @note box2dflash uses Sprite object, box2dweb uses CanvasRenderingContext2D, that is why this function is called SetSprite(). * @param canvas HTML Canvas Element to draw debug information to. **/ public SetSprite(canvas: CanvasRenderingContext2D): void; /** * Set the scale used for drawing XForms. * @param xformScale The transform scale. **/ public SetXFormScale(xformScale: number): void; } } declare namespace Box2D.Dynamics { /** * Joints and shapes are destroyed when their associated body is destroyed. Implement this listener so that you may nullify references to these joints and shapes. **/ export class b2DestructionListener { /** * Called when any fixture is about to be destroyed due to the destruction of its parent body. * @param fixture b2Fixture being destroyed. **/ public SayGoodbyeFixture(fixture: b2Fixture): void; /** * Called when any joint is about to be destroyed due to the destruction of one of its attached bodies. * @param joint b2Joint being destroyed. **/ public SayGoodbyeJoint(joint: Joints.b2Joint): void; } } declare namespace Box2D.Dynamics { /** * This holds contact filtering data. **/ export class b2FilterData { /** * The collision category bits. Normally you would just set one bit. **/ public categoryBits: number; /** * Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no collision group. Non-zero group filtering always wins against the mask bits. **/ public groupIndex: number; /** * The collision mask bits. This states the categories that this shape would accept for collision. **/ public maskBits: number; /** * Creates a copy of the filter data. * @return Copy of this filter data. **/ public Copy(): b2FilterData; } } declare namespace Box2D.Dynamics { /** * A fixture is used to attach a shape to a body for collision detection. A fixture inherits its transform from its parent. Fixtures hold additional non-geometric data such as friction, collision filters, etc. Fixtures are created via b2Body::CreateFixture. * @warning you cannot reuse fixtures. **/ export class b2Fixture { /** * Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a more accurate AABB, compute it using the shape and the body transform. * @return Fiture's AABB. **/ public GetAABB(): Box2D.Collision.b2AABB; /** * Get the parent body of this fixture. This is NULL if the fixture is not attached. * @return The parent body. **/ public GetBody(): b2Body; /** * Get the density of this fixture. * @return Density **/ public GetDensity(): number; /** * Get the contact filtering data. * @return Filter data. **/ public GetFilterData(): b2FilterData; /** * Get the coefficient of friction. * @return Friction. **/ public GetFriction(): number; /** * Get the mass data for this fixture. The mass data is based on the density and the shape. The rotational inertia is about the shape's origin. This operation may be expensive. * @param massData This is a reference to a valid b2MassData, if it is null a new b2MassData is allocated and then returned. Default = null. * @return Mass data. **/ public GetMassData(massData?: Box2D.Collision.Shapes.b2MassData): Box2D.Collision.Shapes.b2MassData; /** * Get the next fixture in the parent body's fixture list. * @return Next fixture. **/ public GetNext(): b2Fixture; /** * Get the coefficient of restitution. * @return Restitution. **/ public GetRestitution(): number; /** * Get the child shape. You can modify the child shape, however you should not change the number of vertices because this will crash some collision caching mechanisms. * @return Fixture shape. **/ public GetShape(): Box2D.Collision.Shapes.b2Shape; /** * Get the type of the child shape. You can use this to down cast to the concrete shape. * @return Shape type enum. **/ public GetType(): number; /** * Get the user data that was assigned in the fixture definition. Use this to store your application specific data. * @return User provided data. Cast to your object type. **/ public GetUserData(): any; /** * Is this fixture a sensor (non-solid)? * @return True if the shape is a sensor, otherwise false. **/ public IsSensor(): boolean; /** * Perform a ray cast against this shape. * @param output Ray cast results. This argument is out. * @param input Ray cast input parameters. * @return True if the ray hits the shape, otherwise false. **/ public RayCast(output: Box2D.Collision.b2RayCastOutput, input: Box2D.Collision.b2RayCastInput): boolean; /** * Set the density of this fixture. This will _not_ automatically adjust the mass of the body. You must call b2Body::ResetMassData to update the body's mass. * @param density The new density. **/ public SetDensity(density: number): void; /** * Set the contact filtering data. This will not update contacts until the next time step when either parent body is active and awake. * @param filter The new filter data. **/ public SetFilterData(filter: any): void; /** * Set the coefficient of friction. * @param friction The new friction coefficient. **/ public SetFriction(friction: number): void; /** * Get the coefficient of restitution. * @param resitution The new restitution coefficient. **/ public SetRestitution(restitution: number): void; /** * Set if this fixture is a sensor. * @param sensor True to set as a sensor, false to not be a sensor. **/ public SetSensor(sensor: boolean): void; /** * Set the user data. Use this to store your application specific data. * @param data User provided data. **/ public SetUserData(data: any): void; /** * Test a point for containment in this fixture. * @param p Point to test against, in world coordinates. * @return True if the point is in this shape, otherwise false. **/ public TestPoint(p: Box2D.Common.Math.b2Vec2): boolean; } } declare namespace Box2D.Dynamics { /** * A fixture definition is used to create a fixture. This class defines an abstract fixture definition. You can reuse fixture definitions safely. **/ export class b2FixtureDef { /** * The density, usually in kg/m^2. **/ public density: number; /** * Contact filtering data. **/ public filter: b2FilterData; /** * The friction coefficient, usually in the range [0,1]. **/ public friction: number; /** * A sensor shape collects contact information but never generates a collision response. **/ public isSensor: boolean; /** * The restitution (elasticity) usually in the range [0,1]. **/ public restitution: number; /** * The shape, this must be set. The shape will be cloned, so you can create the shape on the stack. **/ public shape: Box2D.Collision.Shapes.b2Shape; /** * Use this to store application specific fixture data. **/ public userData: any; /** * The constructor sets the default fixture definition values. **/ constructor(); } } declare namespace Box2D.Dynamics { /** * The world class manages all physics entities, dynamic simulation, and asynchronous queries. **/ export class b2World { /** * Locked **/ public static e_locked: number; /** * New Fixture **/ public static e_newFixture: number; /** * Creates a new world. * @param gravity The world gravity vector. * @param doSleep Improvie performance by not simulating inactive bodies. **/ constructor(gravity: Box2D.Common.Math.b2Vec2, doSleep: boolean); /** * Add a controller to the world list. * @param c Controller to add. * @return Controller that was added to the world. **/ public AddController(c: Controllers.b2Controller): Controllers.b2Controller; /** * Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps. **/ public ClearForces(): void; /** * Create a rigid body given a definition. No reference to the definition is retained. * @param def Body's definition. * @return Created rigid body. **/ public CreateBody(def: b2BodyDef): b2Body; /** * Creates a new controller. * @param controller New controller. * @return New controller. **/ public CreateController(controller: Controllers.b2Controller): Controllers.b2Controller; /** * Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies to cease colliding. * @warning This function is locked during callbacks. * @param def Joint definition. * @return New created joint. **/ public CreateJoint(def: Joints.b2JointDef): Joints.b2Joint; /** * Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during callbacks. * @param b Body to destroy. * @warning This function is locked during callbacks. **/ public DestroyBody(b: b2Body): void; /** * Destroy a controller given the controller instance. * @warning This function is locked during callbacks. * @param controller Controller to destroy. **/ public DestroyController(controller: Controllers.b2Controller): void; /** * Destroy a joint. This may cause the connected bodies to begin colliding. * @param j Joint to destroy. **/ public DestroyJoint(j: Joints.b2Joint): void; /** * Call this to draw shapes and other debug draw data. **/ public DrawDebugData(): void; /** * Get the number of bodies. * @return Number of bodies in this world. **/ public GetBodyCount(): number; /** * Get the world body list. With the returned body, use b2Body::GetNext to get the next body in the world list. A NULL body indicates the end of the list. * @return The head of the world body list. **/ public GetBodyList(): b2Body; /** * Get the number of contacts (each may have 0 or more contact points). * @return Number of contacts. **/ public GetContactCount(): number; /** * Get the world contact list. With the returned contact, use b2Contact::GetNext to get the next contact in the world list. A NULL contact indicates the end of the list. * @return The head of the world contact list. **/ public GetContactList(): Contacts.b2Contact; /** * Get the global gravity vector. * @return Global gravity vector. **/ public GetGravity(): Box2D.Common.Math.b2Vec2; /** * The world provides a single static ground body with no collision shapes. You can use this to simplify the creation of joints and static shapes. * @return The ground body. **/ public GetGroundBody(): b2Body; /** * Get the number of joints. * @return The number of joints in the world. **/ public GetJointCount(): number; /** * Get the world joint list. With the returned joint, use b2Joint::GetNext to get the next joint in the world list. A NULL joint indicates the end of the list. * @return The head of the world joint list. **/ public GetJointList(): Joints.b2Joint; /** * Get the number of broad-phase proxies. * @return Number of borad-phase proxies. **/ public GetProxyCount(): number; /** * Is the world locked (in the middle of a time step). * @return True if the world is locked and in the middle of a time step, otherwise false. **/ public IsLocked(): boolean; /** * Query the world for all fixtures that potentially overlap the provided AABB. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param aabb The query bounding box. **/ public QueryAABB(callback: (fixutre: b2Fixture) => boolean, aabb: Box2D.Collision.b2AABB): void; /** * Query the world for all fixtures that contain a point. * @note This provides a feature specific to this port. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param p The query point. **/ public QueryPoint(callback: (fixture: b2Fixture) => boolean, p: Box2D.Common.Math.b2Vec2): void; /** * Query the world for all fixtures that precisely overlap the provided transformed shape. * @note This provides a feature specific to this port. * @param callback A user implemented callback class. It should match signature function Callback(fixture:b2Fixture):Boolean. Return true to continue to the next fixture. * @param shape The query shape. * @param transform Optional transform, default = null. **/ public QueryShape(callback: (fixture: b2Fixture) => boolean, shape: Box2D.Collision.Shapes.b2Shape, transform?: Box2D.Common.Math.b2Transform): void; /** * Ray-cast the world for all fixtures in the path of the ray. Your callback Controls whether you get the closest point, any point, or n-points The ray-cast ignores shapes that contain the starting point. * @param callback A callback function which must be of signature: * function Callback( * fixture:b2Fixture, // The fixture hit by the ray * point:b2Vec2, // The point of initial intersection * normal:b2Vec2, // The normal vector at the point of intersection * fraction:Number // The fractional length along the ray of the intersection * ):Number * Callback should return the new length of the ray as a fraction of the original length. By returning 0, you immediately terminate. By returning 1, you continue wiht the original ray. By returning the current fraction, you proceed to find the closest point. * @param point1 The ray starting point. * @param point2 The ray ending point. **/ public RayCast(callback: (fixture: b2Fixture, point: Box2D.Common.Math.b2Vec2, normal: Box2D.Common.Math.b2Vec2, fraction: number) => number, point1: Box2D.Common.Math.b2Vec2, point2: Box2D.Common.Math.b2Vec2): void; /** * Ray-cast the world for all fixture in the path of the ray. * @param point1 The ray starting point. * @param point2 The ray ending point. * @return Array of all the fixtures intersected by the ray. **/ public RayCastAll(point1: Box2D.Common.Math.b2Vec2, point2: Box2D.Common.Math.b2Vec2): b2Fixture[]; /** * Ray-cast the world for the first fixture in the path of the ray. * @param point1 The ray starting point. * @param point2 The ray ending point. * @return First fixture intersected by the ray. **/ public RayCastOne(point1: Box2D.Common.Math.b2Vec2, point2: Box2D.Common.Math.b2Vec2): b2Fixture; /** * Removes the controller from the world. * @param c Controller to remove. **/ public RemoveController(c: Controllers.b2Controller): void; /** * Use the given object as a broadphase. The old broadphase will not be cleanly emptied. * @warning This function is locked during callbacks. * @param broadphase: Broad phase implementation. **/ public SetBroadPhase(broadPhase: Box2D.Collision.IBroadPhase): void; /** * Register a contact filter to provide specific control over collision. Otherwise the default filter is used (b2_defaultFilter). * @param filter Contact filter'er. **/ public SetContactFilter(filter: b2ContactFilter): void; /** * Register a contact event listener. * @param listener Contact event listener. **/ public SetContactListener(listener: b2ContactListener): void; /** * Enable/disable continuous physics. For testing. * @param flag True for continuous physics, otherwise false. **/ public SetContinuousPhysics(flag: boolean): void; /** * Register a routine for debug drawing. The debug draw functions are called inside the b2World::Step method, so make sure your renderer is ready to consume draw commands when you call Step(). * @param debugDraw Debug drawing instance. **/ public SetDebugDraw(debugDraw: b2DebugDraw): void; /** * Destruct the world. All physics entities are destroyed and all heap memory is released. * @param listener Destruction listener instance. **/ public SetDestructionListener(listener: b2DestructionListener): void; /** * Change the global gravity vector. * @param gravity New global gravity vector. **/ public SetGravity(gravity: Box2D.Common.Math.b2Vec2): void; /** * Enable/disable warm starting. For testing. * @param flag True for warm starting, otherwise false. **/ public SetWarmStarting(flag: boolean): void; /** * Take a time step. This performs collision detection, integration, and constraint solution. * @param dt The amout of time to simulate, this should not vary. * @param velocityIterations For the velocity constraint solver. * @param positionIterations For the position constraint solver. **/ public Step(dt: number, velocityIterations: number, positionIterations: number): void; /** * Perform validation of internal data structures. **/ public Validate(): void; } } declare namespace Box2D.Dynamics.Contacts { /** * The class manages contact between two shapes. A contact exists for each overlapping AABB in the broad-phase (except if filtered). Therefore a contact object may exist that has no contact points. **/ export class b2Contact { /** * Constructor **/ constructor(); /** * Flag this contact for filtering. Filtering will occur the next time step. **/ public FlagForFiltering(): void; /** * Get the first fixture in this contact. * @return First fixture in this contact. **/ public GetFixtureA(): b2Fixture; /** * Get the second fixture in this contact. * @return Second fixture in this contact. **/ public GetFixtureB(): b2Fixture; /** * Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D. * @return Contact manifold. **/ public GetManifold(): Box2D.Collision.b2Manifold; /** * Get the next contact in the world's contact list. * @return Next contact in the world's contact list. **/ public GetNext(): b2Contact; /** * Get the world manifold. * @param worldManifold World manifold out. * @return World manifold. **/ public GetWorldManifold(worldManifold: Box2D.Collision.b2WorldManifold): void; /** * Does this contact generate TOI events for continuous simulation. * @return True for continous, otherwise false. **/ public IsContinuous(): boolean; /** * Has this contact been disabled? * @return True if disabled, otherwise false. **/ public IsEnabled(): boolean; /** * Is this contact a sensor? * @return True if sensor, otherwise false. **/ public IsSensor(): boolean; /** * Is this contact touching. * @return True if contact is touching, otherwise false. **/ public IsTouching(): boolean; /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current time step (or sub-step in continuous collision). * @param flag True to enable, false to disable. **/ public SetEnabled(flag: boolean): void; /** * Change this to be a sensor or-non-sensor contact. * @param sensor True to be sensor, false to not be a sensor. **/ public SetSensor(sensor: boolean): void; } } declare namespace Box2D.Dynamics.Contacts { /** * A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact nodes, one for each attached body. **/ export class b2ContactEdge { /** * Contact. **/ public contact: b2Contact; /** * Next contact edge. **/ public next: b2ContactEdge; /** * Contact body. **/ public other: b2Body; /** * Previous contact edge. **/ public prev: b2ContactEdge; } } declare namespace Box2D.Dynamics.Contacts { /** * This structure is used to report contact point results. **/ export class b2ContactResult { /** * The contact id identifies the features in contact. **/ public id: Box2D.Collision.b2ContactID; /** * Points from shape1 to shape2. **/ public normal: Box2D.Common.Math.b2Vec2; /** * The normal impulse applied to body2. **/ public normalImpulse: number; /** * Position in world coordinates. **/ public position: Box2D.Common.Math.b2Vec2; /** * The first shape. **/ public shape1: Box2D.Collision.Shapes.b2Shape; /** * The second shape. **/ public shape2: Box2D.Collision.Shapes.b2Shape; /** * The tangent impulse applied to body2. **/ public tangentImpulse: number; } } declare namespace Box2D.Dynamics.Controllers { /** * Base class for controllers. Controllers are a convience for encapsulating common per-step functionality. **/ export class b2Controller { /** * Body count. **/ public m_bodyCount: number; /** * List of bodies. **/ public m_bodyList: b2ControllerEdge; /** * Adds a body to the controller. * @param body Body to add. **/ public AddBody(body: b2Body): void; /** * Removes all bodies from the controller. **/ public Clear(): void; /** * Debug drawing. * @param debugDraw Handle to drawer. **/ public Draw(debugDraw: b2DebugDraw): void; /** * Gets the body list. * @return Body list. **/ public GetBodyList(): b2ControllerEdge; /** * Gets the next controller. * @return Next controller. **/ public GetNext(): b2Controller; /** * Gets the world. * @return World. **/ public GetWorld(): b2World; /** * Removes a body from the controller. * @param body Body to remove from this controller. **/ public RemoveBody(body: b2Body): void; /** * Step * @param step b2TimeStep -> Private internal class. Not sure why this is exposed. **/ public Step(step: any/*b2TimeStep*/): void; } } declare namespace Box2D.Dynamics.Controllers { /** * Controller Edge. **/ export class b2ControllerEdge { /** * Body. **/ public body: b2Body; /** * Provides quick access to the other end of this edge. **/ public controller: b2Controller; /** * The next controller edge in the controller's body list. **/ public nextBody: b2ControllerEdge; /** * The next controller edge in the body's controller list. **/ public nextController: b2ControllerEdge; /** * The previous controller edge in the controller's body list. **/ public prevBody: b2ControllerEdge; /** * The previous controller edge in the body's controller list. **/ public prevController: b2ControllerEdge; } } declare namespace Box2D.Dynamics.Controllers { /** * Calculates buoyancy forces for fluids in the form of a half plane. **/ export class b2BuoyancyController extends b2Controller { /** * Linear drag co-efficient. * @default = 1 **/ public angularDrag: number; /** * The fluid density. * @default = 0 **/ public density: number; /** * Gravity vector, if the world's gravity is not used. * @default = null **/ public gravity: Box2D.Common.Math.b2Vec2; /** * Linear drag co-efficient. * @default = 2 **/ public linearDrag: number; /** * The outer surface normal. **/ public normal: Box2D.Common.Math.b2Vec2; /** * The height of the fluid surface along the normal. * @default = 0 **/ public offset: number; /** * If false, bodies are assumed to be uniformly dense, otherwise use the shapes densities. * @default = false. **/ public useDensity: boolean; /** * If true, gravity is taken from the world instead of the gravity parameter. * @default = true. **/ public useWorldGravity: boolean; /** * Fluid velocity, for drag calculations. **/ public velocity: Box2D.Common.Math.b2Vec2; } } declare namespace Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity **/ export class b2ConstantAccelController extends b2Controller { /** * The acceleration to apply. **/ public A: Box2D.Common.Math.b2Vec2; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } declare namespace Box2D.Dynamics.Controllers { /** * Applies an acceleration every frame, like gravity. **/ export class b2ConstantForceController extends b2Controller { /** * The acceleration to apply. **/ public A: Box2D.Common.Math.b2Vec2; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } declare namespace Box2D.Dynamics.Controllers { /** * Applies simplified gravity between every pair of bodies. **/ export class b2GravityController extends b2Controller { /** * Specifies the strength of the gravitation force. * @default = 1 **/ public G: number; /** * If true, gravity is proportional to r^-2, otherwise r^-1. **/ public invSqr: boolean; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } declare namespace Box2D.Dynamics.Controllers { /** * Applies top down linear damping to the controlled bodies The damping is calculated by multiplying velocity by a matrix in local co-ordinates. **/ export class b2TensorDampingController extends b2Controller { /** * Set this to a positive number to clamp the maximum amount of damping done. * @default = 0 **/ public maxTimeStep: number; /** * Tensor to use in damping model. **/ public T: Box2D.Common.Math.b2Mat22; /** * Helper function to set T in a common case. * @param xDamping x * @param yDamping y **/ public SetAxisAligned(xDamping: number, yDamping: number): void; /** * @see b2Controller.Step **/ public Step(step: any/* b2TimeStep*/): void; } } declare namespace Box2D.Dynamics.Joints { /** * The base joint class. Joints are used to constraint two bodies together in various fashions. Some joints also feature limits and motors. **/ export class b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Anchor A point. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Anchor B point. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the first body attached to this joint. * @return Body A. **/ public GetBodyA(): b2Body; /** * Get the second body attached to this joint. * @return Body B. **/ public GetBodyB(): b2Body; /** * Get the next joint the world joint list. * @return Next joint. **/ public GetNext(): b2Joint; /** * Get the reaction force on body2 at the joint anchor in Newtons. * @param inv_dt * @return Reaction force (N) **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body2 in N. * @param inv_dt * @return Reaction torque (N). **/ public GetReactionTorque(inv_dt: number): number; /** * Get the type of the concrete joint. * @return Joint type. **/ public GetType(): number; /** * Get the user data pointer. * @return User data. Cast to your data type. **/ public GetUserData(): any; /** * Short-cut function to determine if either body is inactive. * @return True if active, otherwise false. **/ public IsActive(): boolean; /** * Set the user data pointer. * @param data Your custom data. **/ public SetUserData(data: any): void; } } declare namespace Box2D.Dynamics.Joints { /** * Joint definitions are used to construct joints. **/ export class b2JointDef { /** * The first attached body. **/ public bodyA: b2Body; /** * The second attached body. **/ public bodyB: b2Body; /** * Set this flag to true if the attached bodies should collide. **/ public collideConnected: boolean; /** * The joint type is set automatically for concrete joint types. **/ public type: number; /** * Use this to attach application specific data to your joints. **/ public userData: any; /** * Constructor. **/ constructor(); } } declare namespace Box2D.Dynamics.Joints { /** * A joint edge is used to connect bodies and joints together in a joint graph where each body is a node and each joint is an edge. A joint edge belongs to a doubly linked list maintained in each attached body. Each joint has two joint nodes, one for each attached body. **/ export class b2JointEdge { /** * The joint. **/ public joint: b2Joint; /** * The next joint edge in the body's joint list. **/ public next: b2JointEdge; /** * Provides quick access to the other body attached. **/ public other: b2Body; /** * The previous joint edge in the body's joint list. **/ public prev: b2JointEdge; } } declare namespace Box2D.Dynamics.Joints { /** * A distance joint constrains two points on two bodies to remain at a fixed distance from each other. You can view this as a massless, rigid rod. **/ export class b2DistanceJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Gets the damping ratio. * @return Damping ratio. **/ public GetDampingRatio(): number; /** * Gets the frequency. * @return Frequency. **/ public GetFrequency(): number; /** * Gets the length of distance between the two bodies. * @return Length. **/ public GetLength(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the damping ratio. * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the length of distance between the two bodies. * @param length New length. **/ public SetLength(length: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game. * @warning Do not use a zero or short length. **/ export class b2DistanceJointDef extends b2JointDef { /** * The damping ratio. 0 = no damping, 1 = critical damping. **/ public dampingRatio: number; /** * The mass-spring-damper frequency in Hertz. **/ public frequencyHz: number; /** * The natural length between the anchor points. **/ public length: number; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param anchorA Anchor A. * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, anchorA: Box2D.Common.Math.b2Vec2, anchorB: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * Friction joint. This is used for top-down friction. It provides 2D translational friction and angular friction. **/ export class b2FrictionJoint extends b2Joint { /** * Angular mass. **/ public m_angularMass: number; /** * Linear mass. **/ public m_linearMass: Box2D.Common.Math.b2Mat22; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Gets the max force. * @return Max force. **/ public GetMaxForce(): number; /** * Gets the max torque. * @return Max torque. **/ public GetMaxTorque(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Sets the max force. * @param force New max force. **/ public SetMaxForce(force: number): void; /** * Sets the max torque. * @param torque New max torque. **/ public SetMaxTorque(torque: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Friction joint defintion. **/ export class b2FrictionJointDef extends b2JointDef { /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The maximum force in N. **/ public maxForce: number; /** * The maximum friction torque in N-m. **/ public maxTorque: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. * @param bA Body A. * @param bB Body B. * @param anchor World anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear ratio to bind the motions together: coordinate1 + ratio coordinate2 = constant The ratio can be negative or positive. If one joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of 1/length. * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints). **/ export class b2GearJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the gear ratio. * @return Gear ratio. **/ public GetRatio(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Set the gear ratio. * @param force New gear ratio. **/ public SetRatio(ratio: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Gear joint definition. This definition requires two existing revolute or prismatic joints (any combination will work). The provided joints must attach a dynamic body to a static body. **/ export class b2GearJointDef extends b2JointDef { /** * The first revolute/prismatic joint attached to the gear joint. **/ public joint1: b2Joint; /** * The second revolute/prismatic joint attached to the gear joint. **/ public joint2: b2Joint; /** * The gear ratio. **/ public ratio: number; /** * Constructor. **/ constructor(); } } declare namespace Box2D.Dynamics.Joints { /** * A line joint. This joint provides one degree of freedom: translation along an axis fixed in body1. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. **/ export class b2LineJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable limits **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to disable the motor. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the current joint translation speed, usually in meters per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the current joint translation, usually in meters. * @return Joint translation. **/ public GetJointTranslation(): number; /** * Get the lower joint limit, usually in meters. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the maximum motor force, usually in N. * @return Max motor force. **/ public GetMaxMotorForce(): number; /** * Get the current motor force, usually in N. * @return Motor force. **/ public GetMotorForce(): number; /** * Get the motor speed, usually in meters per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit, usually in meters. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled otherwise false. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, otherwise false. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits, usually in meters. * @param lower Lower limit. * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. * @param force New max motor force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Line joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. **/ export class b2LineJointDef extends b2JointDef { /** * Enable/disable the joint limit. **/ public enableLimit: boolean; /** * Enable/disable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The local translation axis in bodyA. **/ public localAxisA: Box2D.Common.Math.b2Vec2; /** * The lower translation limit, usually in meters. **/ public lowerTranslation: number; /** * The maximum motor torque, usually in N-m. **/ public maxMotorForce: number; /** * The desired motor speed in radians per second. **/ public motorSpeed: number; /** * The upper translation limit, usually in meters. **/ public upperTranslation: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: Box2D.Common.Math.b2Vec2, axis: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * A mouse joint is used to make a point on a body track a specified world point. This a soft constraint with a maximum force. This allows the constraint to stretch and without applying huge forces. Note: this joint is not fully documented as it is intended primarily for the testbed. See that for more instructions. **/ export class b2MouseJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Gets the damping ratio. * @return Damping ratio. **/ public GetDampingRatio(): number; /** * Gets the frequency. * @return Frequency. **/ public GetFrequency(): number; /** * Gets the max force. * @return Max force. **/ public GetMaxForce(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Gets the target. * @return Target. **/ public GetTarget(): Box2D.Common.Math.b2Vec2; /** * Sets the damping ratio. * @param ratio New damping ratio. **/ public SetDampingRatio(ratio: number): void; /** * Sets the frequency. * @param hz New frequency (hertz). **/ public SetFrequency(hz: number): void; /** * Sets the max force. * @param maxForce New max force. **/ public SetMaxForce(maxForce: number): void; /** * Use this to update the target point. * @param target New target. **/ public SetTarget(target: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * Mouse joint definition. This requires a world target point, tuning parameters, and the time step. **/ export class b2MouseJointDef extends b2JointDef { /** * The damping ratio. 0 = no damping, 1 = critical damping. **/ public dampingRatio: number; /** * The response speed. **/ public frequencyHz: number; /** * The maximum constraint force that can be exerted to move the candidate body. **/ public maxForce: number; /** * Constructor. **/ constructor(); } } declare namespace Box2D.Dynamics.Joints { /** * A prismatic joint. This joint provides one degree of freedom: translation along an axis fixed in body1. Relative rotation is prevented. You can use a joint limit to restrict the range of motion and a joint motor to drive the motion or to model joint friction. **/ export class b2PrismaticJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable. **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to disable. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the current joint translation speed, usually in meters per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the current joint translation, usually in meters. * @return Joint translation. **/ public GetJointTranslation(): number; /** * Get the lower joint limit, usually in meters. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the current motor force, usually in N. * @return Motor force. **/ public GetMotorForce(): number; /** * Get the motor speed, usually in meters per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit, usually in meters. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled otherwise false. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, otherwise false. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits, usually in meters. * @param lower Lower limit. * @param upper Upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor force, usually in N. * @param force New max force. **/ public SetMaxMotorForce(force: number): void; /** * Set the motor speed, usually in meters per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Prismatic joint definition. This requires defining a line of motion using an axis and an anchor point. The definition uses local anchor points and a local axis so that the initial configuration can violate the constraint slightly. The joint translation is zero when the local anchor points coincide in world space. Using local anchors and a local axis helps when saving and loading a game. **/ export class b2PrismaticJointDef extends b2JointDef { /** * Enable/disable the joint limit. **/ public enableLimit: boolean; /** * Enable/disable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The local translation axis in body1. **/ public localAxisA: Box2D.Common.Math.b2Vec2; /** * The lower translation limit, usually in meters. **/ public lowerTranslation: number; /** * The maximum motor torque, usually in N-m. **/ public maxMotorForce: number; /** * The desired motor speed in radians per second. **/ public motorSpeed: number; /** * The constrained angle between the bodies: bodyB_angle - bodyA_angle. **/ public referenceAngle: number; /** * The upper translation limit, usually in meters. **/ public upperTranslation: number; /** * Constructor. **/ constructor(); /** * Initialize the joint. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. * @param axis Axis. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: Box2D.Common.Math.b2Vec2, axis: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * The pulley joint is connected to two bodies and two fixed ground points. The pulley supports a ratio such that: length1 + ratio length2 <= constant Yes, the force transmitted is scaled by the ratio. The pulley also enforces a maximum length limit on both sides. This is useful to prevent one side of the pulley hitting the top. **/ export class b2PulleyJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the first ground anchor. **/ public GetGroundAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the second ground anchor. **/ public GetGroundAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the current length of the segment attached to body1. **/ public GetLength1(): number; /** * Get the current length of the segment attached to body2. **/ public GetLength2(): number; /** * Get the pulley ratio. **/ public GetRatio(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } } declare namespace Box2D.Dynamics.Joints { /** * Pulley joint definition. This requires two ground anchors, two dynamic body anchor points, max lengths for each side, and a pulley ratio. **/ export class b2PulleyJointDef extends b2JointDef { /** * The first ground anchor in world coordinates. This point never moves. **/ public groundAnchorA: Box2D.Common.Math.b2Vec2; /** * The second ground anchor in world coordinates. This point never moves. **/ public groundAnchorB: Box2D.Common.Math.b2Vec2; /** * The a reference length for the segment attached to bodyA. **/ public lengthA: number; /** * The a reference length for the segment attached to bodyB. **/ public lengthB: number; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The maximum length of the segment attached to bodyA. **/ public maxLengthA: number; /** * The maximum length of the segment attached to bodyB. **/ public maxLengthB: number; /** * The pulley ratio, used to simulate a block-and-tackle. **/ public ratio: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, and length using the world anchors. * @param bA Body A. * @param bB Body B. * @param gaA Ground anchor A. * @param gaB Ground anchor B. * @param anchorA Anchor A. * @param anchorB Anchor B. **/ public Initialize(bA: b2Body, bB: b2Body, gaA: Box2D.Common.Math.b2Vec2, gaB: Box2D.Common.Math.b2Vec2, anchorA: Box2D.Common.Math.b2Vec2, anchorB: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * A revolute joint constrains to bodies to share a common point while they are free to rotate about the point. The relative rotation about the shared point is the joint angle. You can limit the relative rotation with a joint limit that specifies a lower and upper angle. You can use a motor to drive the relative rotation about the shared point. A maximum motor torque is provided so that infinite forces are not generated. **/ export class b2RevoluteJoint extends b2Joint { /** * Enable/disable the joint limit. * @param flag True to enable, false to disable. **/ public EnableLimit(flag: boolean): void; /** * Enable/disable the joint motor. * @param flag True to enable, false to diasable. **/ public EnableMotor(flag: boolean): void; /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the current joint angle in radians. * @return Joint angle. **/ public GetJointAngle(): number; /** * Get the current joint angle speed in radians per second. * @return Joint speed. **/ public GetJointSpeed(): number; /** * Get the lower joint limit in radians. * @return Lower limit. **/ public GetLowerLimit(): number; /** * Get the motor speed in radians per second. * @return Motor speed. **/ public GetMotorSpeed(): number; /** * Get the current motor torque, usually in N-m. * @return Motor torque. **/ public GetMotorTorque(): number; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; /** * Get the upper joint limit in radians. * @return Upper limit. **/ public GetUpperLimit(): number; /** * Is the joint limit enabled? * @return True if enabled, false if disabled. **/ public IsLimitEnabled(): boolean; /** * Is the joint motor enabled? * @return True if enabled, false if disabled. **/ public IsMotorEnabled(): boolean; /** * Set the joint limits in radians. * @param lower New lower limit. * @param upper New upper limit. **/ public SetLimits(lower: number, upper: number): void; /** * Set the maximum motor torque, usually in N-m. * @param torque New max torque. **/ public SetMaxMotorTorque(torque: number): void; /** * Set the motor speed in radians per second. * @param speed New motor speed. **/ public SetMotorSpeed(speed: number): void; } } declare namespace Box2D.Dynamics.Joints { /** * Revolute joint definition. This requires defining an anchor point where the bodies are joined. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. You also need to specify the initial relative angle for joint limits. This helps when saving and loading a game. The local anchor points are measured from the body's origin rather than the center of mass because: 1. you might not know where the center of mass will be. 2. if you add/remove shapes from a body and recompute the mass, the joints will be broken. **/ export class b2RevoluteJointDef extends b2JointDef { /** * A flag to enable joint limits. **/ public enableLimit: boolean; /** * A flag to enable the joint motor. **/ public enableMotor: boolean; /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The lower angle for the joint limit (radians). **/ public lowerAngle: number; /** * The maximum motor torque used to achieve the desired motor speed. Usually in N-m. **/ public maxMotorTorque: number; /** * The desired motor speed. Usually in radians per second. **/ public motorSpeed: number; /** * The bodyB angle minus bodyA angle in the reference state (radians). **/ public referenceAngle: number; /** * The upper angle for the joint limit (radians). **/ public upperAngle: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, achors, and reference angle using the world anchor. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: Box2D.Common.Math.b2Vec2): void; } } declare namespace Box2D.Dynamics.Joints { /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the island constraint solver is approximate. **/ export class b2WeldJoint extends b2Joint { /** * Get the anchor point on bodyA in world coordinates. * @return Body A anchor. **/ public GetAnchorA(): Box2D.Common.Math.b2Vec2; /** * Get the anchor point on bodyB in world coordinates. * @return Body B anchor. **/ public GetAnchorB(): Box2D.Common.Math.b2Vec2; /** * Get the reaction force on body2 at the joint anchor in N. * @param inv_dt * @return Reaction force in N. **/ public GetReactionForce(inv_dt: number): Box2D.Common.Math.b2Vec2; /** * Get the reaction torque on body 2 in N. * @param inv_dt * @return Reaction torque in N. **/ public GetReactionTorque(inv_dt: number): number; } } declare namespace Box2D.Dynamics.Joints { /** * Weld joint definition. You need to specify local anchor points where they are attached and the relative body angle. The position of the anchor points is important for computing the reaction torque. **/ export class b2WeldJointDef extends b2JointDef { /** * The local anchor point relative to body1's origin. **/ public localAnchorA: Box2D.Common.Math.b2Vec2; /** * The local anchor point relative to body2's origin. **/ public localAnchorB: Box2D.Common.Math.b2Vec2; /** * The body2 angle minus body1 angle in the reference state (radians). **/ public referenceAngle: number; /** * Constructor. **/ constructor(); /** * Initialize the bodies, anchors, axis, and reference angle using the world anchor and world axis. * @param bA Body A. * @param bB Body B. * @param anchor Anchor. **/ public Initialize(bA: b2Body, bB: b2Body, anchor: Box2D.Common.Math.b2Vec2): void; } }
the_stack
import * as functions from "firebase-functions"; import * as admin from "firebase-admin"; admin.initializeApp(); import Stripe from "stripe"; const stripe = process.env.FUNCTIONS_EMULATOR ? (null as any) : new Stripe(functions.config().stripe.secret, { apiVersion: "2020-08-27", }); import { generateDeck, replayEvents, findSet, GameMode } from "./game"; const MAX_GAME_ID_LENGTH = 64; const MAX_UNFINISHED_GAMES_PER_HOUR = 4; // Rating system parameters. const SCALING_FACTOR = 800; const BASE_RATING = 1200; type TransactionResult = { committed: boolean; snapshot: functions.database.DataSnapshot; }; /** Ends the game with the correct time and updates ratings */ export const finishGame = functions.https.onCall(async (data, context) => { const gameId = data.gameId; if ( !(typeof gameId === "string") || gameId.length === 0 || gameId.length > MAX_GAME_ID_LENGTH ) { throw new functions.https.HttpsError( "invalid-argument", "The function must be called with " + "argument `gameId` to be finished at `/games/:gameId`." ); } if (!context.auth) { throw new functions.https.HttpsError( "failed-precondition", "The function must be called while authenticated." ); } const gameData = await admin .database() .ref(`gameData/${gameId}`) .once("value"); const gameSnap = await admin.database().ref(`games/${gameId}`).once("value"); const gameMode = (gameSnap.child("mode").val() as GameMode) || "normal"; const { lastSet, deck, finalTime, scores } = replayEvents(gameData, gameMode); if (findSet(Array.from(deck), gameMode, lastSet)) { throw new functions.https.HttpsError( "failed-precondition", "The requested game has not yet ended." ); } // The game has ended, so we attempt to do an atomic update. // Safety: Events can only be appended to the game, so the final time must remain the same. const { committed, snapshot }: TransactionResult = await admin .database() .ref(`games/${gameId}`) .transaction((game) => { if (game.status !== "ingame") { // Someone beat us to the atomic update, so we cancel the transaction. return; } game.status = "done"; game.endedAt = finalTime; return game; }); if (!committed) { return; } // Check if hints are enabled; and if so, ignore the game in statistics if ( snapshot.child("enableHint").val() && snapshot.child("users").numChildren() === 1 && snapshot.child("access").val() === "private" && gameMode === "normal" ) { return; } /** * Update statistics and ratings of players involved based on an extension of * the Elo system. */ // Retrieve userIds of players in the game. const players: string[] = []; snapshot.child("users").forEach(function (childSnap) { if (childSnap.key !== null) { players.push(childSnap.key); } }); // Add scores for players without a single set. for (const player of players) { scores[player] ??= 0; } // Differentiate between solo and multiplayer games. const variant = players.length === 1 ? "solo" : "multiplayer"; const time = finalTime - gameSnap.child("startedAt").val(); const topScore = Math.max(...Object.values(scores)); // Update statistics for all users const userStats: Record<string, any> = {}; await Promise.all( players.map(async (player) => { const result: TransactionResult = await admin .database() .ref(`userStats/${player}/${gameMode}/${variant}`) .transaction((stats) => { stats ??= {}; // tslint:disable-line no-parameter-reassignment stats.finishedGames = (stats.finishedGames ?? 0) + 1; stats.totalSets = (stats.totalSets ?? 0) + scores[player]; if (scores[player] === topScore) { stats.wonGames = (stats.wonGames ?? 0) + 1; stats.fastestTime = Math.min(stats.fastestTime ?? Infinity, time); } stats.totalTime = (stats.totalTime ?? 0) + time; return stats; }); // Save these values for use in rating calculation userStats[player] = result.snapshot.val(); }) ); // If the game is solo, we skip rating calculation. if (variant === "solo") { return; } // Retrieve old ratings from the database. const ratings: Record<string, number> = {}; for (const player of players) { const ratingSnap = await admin .database() .ref(`userStats/${player}/${gameMode}/rating`) .once("value"); const rating = ratingSnap.exists() ? ratingSnap.val() : BASE_RATING; ratings[player] = rating; } // Compute expected ratio for each player. const likelihood: Record<string, number> = {}; let totalLikelihood = 0; for (const player of players) { likelihood[player] = Math.pow(10, ratings[player] / SCALING_FACTOR); totalLikelihood += likelihood[player]; } // Compute achieved ratio for each player. const achievedRatio: Record<string, number> = {}; const setCount = Object.values(scores).reduce((a, b) => a + b); for (const player of players) { achievedRatio[player] = scores[player] / setCount; } // Compute new rating for each player. const updates: Record<string, number> = {}; for (const player of players) { /** * Adapt the learning rate to the experience of a player and the * corresponding certainty of the rating system based on the number of * games played. */ const gameCount = userStats[player].finishedGames as number; const learningRate = Math.max(256 / (1 + gameCount / 20), 64); const newRating = ratings[player] + learningRate * (achievedRatio[player] - likelihood[player] / totalLikelihood); updates[`${player}/${gameMode}/rating`] = newRating; } await admin.database().ref("userStats").update(updates); }); /** Create a new game in the database */ export const createGame = functions.https.onCall(async (data, context) => { const gameId = data.gameId; const access = data.access || "public"; const mode = data.mode || "normal"; const enableHint = data.enableHint || false; if ( !(typeof gameId === "string") || gameId.length === 0 || gameId.length > MAX_GAME_ID_LENGTH ) { throw new functions.https.HttpsError( "invalid-argument", "The function must be called with " + "argument `gameId` to be created at `/games/:gameId`." ); } if ( !(typeof access === "string") || (access !== "private" && access !== "public") ) { throw new functions.https.HttpsError( "invalid-argument", "The function must be called with " + 'argument `access` given value "public" or "private".' ); } if (!context.auth) { throw new functions.https.HttpsError( "failed-precondition", "The function must be called while authenticated." ); } const userId = context.auth.uid; const oneHourAgo = Date.now() - 3600000; const recentGameIds = await admin .database() .ref(`userGames/${userId}`) .orderByValue() .startAt(oneHourAgo) .once("value"); const recentGames = await Promise.all( Object.keys(recentGameIds.val() || {}).map((recentGameId) => admin.database().ref(`games/${recentGameId}`).once("value") ) ); let unfinishedGames = 0; for (const snap of recentGames) { if ( snap.child("host").val() === userId && snap.child("status").val() !== "done" && snap.child("access").val() === "public" ) { ++unfinishedGames; } } const gameRef = admin.database().ref(`games/${gameId}`); const { committed, snapshot } = await gameRef.transaction((currentData) => { if (currentData === null) { if ( unfinishedGames >= MAX_UNFINISHED_GAMES_PER_HOUR && access === "public" ) { throw new functions.https.HttpsError( "resource-exhausted", "Too many unfinished public games were recently created." ); } return { host: userId, createdAt: admin.database.ServerValue.TIMESTAMP, status: "waiting", access, mode, enableHint, }; } else { return; } }); if (!committed) { throw new functions.https.HttpsError( "already-exists", "The requested `gameId` already exists." ); } // After this point, the game has successfully been created. // We update the database asynchronously in three different places: // 1. /gameData/:gameId // 2. /stats/gameCount // 3. /publicGames (if access is public) const updates: Array<Promise<any>> = []; updates.push( admin.database().ref(`gameData/${gameId}`).set({ deck: generateDeck(), }) ); updates.push( admin .database() .ref("stats/gameCount") .transaction((count) => (count || 0) + 1) ); if (access === "public") { updates.push( admin .database() .ref("publicGames") .child(gameId) .set(snapshot?.child("createdAt").val()) ); } await Promise.all(updates); return snapshot.val(); }); /** Generate a link to the customer portal. */ export const customerPortal = functions.https.onCall(async (data, context) => { if (!context.auth) { throw new functions.https.HttpsError( "failed-precondition", "This function must be called while authenticated." ); } const user = await admin.auth().getUser(context.auth.uid); if (!user.email) { throw new functions.https.HttpsError( "failed-precondition", "This function must be called by an authenticated user with email." ); } const customerResponse = await stripe.customers.list({ email: user.email }); if (!customerResponse.data.length) { throw new functions.https.HttpsError( "not-found", `A subscription with email ${user.email} was not found.` ); } const portalResponse = await stripe.billingPortal.sessions.create({ customer: customerResponse.data[0].id, return_url: data.returnUrl, }); return portalResponse.url; }); /** Periodically remove stale user connections */ export const clearConnections = functions.pubsub .schedule("every 1 minutes") .onRun(async (context) => { const onlineUsers = await admin .database() .ref("users") .orderByChild("connections") .startAt(false) .once("value"); const actions: Array<Promise<void>> = []; let numUsers = 0; onlineUsers.forEach((snap) => { ++numUsers; if (Math.random() < 0.1) { console.log(`Clearing connections for ${snap.ref.toString()}`); actions.push(snap.ref.child("connections").remove()); } }); actions.push(admin.database().ref("stats/onlineUsers").set(numUsers)); await Promise.all(actions); }); /** Webhook that handles Stripe customer events. */ export const handleStripe = functions.https.onRequest(async (req, res) => { const payload = req.rawBody; const sig = req.get("stripe-signature"); if (!sig) { res.status(400).send("Webhook Error: Missing stripe-signature"); return; } const { endpoint_secret } = functions.config().stripe; let event; try { event = stripe.webhooks.constructEvent(payload, sig, endpoint_secret); } catch (error: any) { res.status(400).send(`Webhook Error: ${error.message}`); return; } console.log(`Received ${event.type}: ${JSON.stringify(event.data)}`); if ( event.type === "customer.subscription.created" || event.type === "customer.subscription.deleted" ) { const subscription = event.data.object as Stripe.Subscription; const { email } = (await stripe.customers.retrieve( subscription.customer as string )) as Stripe.Response<Stripe.Customer>; if (email) { const user = await admin .auth() .getUserByEmail(email) .catch(() => null); if (user) { const newState = event.type === "customer.subscription.created"; await admin.database().ref(`users/${user.uid}/patron`).set(newState); console.log(`Processed ${email} (${user.uid}): newState = ${newState}`); } else { console.log(`Failed to find user: ${email}`); } } else { console.log("Subscription event received with no email, ignoring"); } } res.status(200).end(); });
the_stack
import SearchBar from "./core/search/SearchBar"; import BootstrapDatepicker from "./libs/datepicker/BootstrapDatepicker"; import Scrollbar from "./libs/scrollbar/Scrollbar"; import WindowEvents from "./core/ui/WindowEvents"; import DocumentEvents from "./core/ui/DocumentEvents"; import ApexChartsHandler from "./libs/apexcharts/ApexChartsHandler"; import Selectize from "./libs/selectize/Selectize"; import TinyMce from "./libs/tiny-mce/TinyMce"; import PrismHighlight from "./libs/prism/PrismHighlight"; import FlatPicker from "./libs/datetimepicker/FlatPicker"; import LoadingBar from "./libs/loading-bar/LoadingBar"; import ShuffleWrapper from "./libs/shuffle/ShuffleWrapper"; import BootstrapToggle from "./libs/bootstrap-toggle/BootstrapToggle"; import LightGallery from "./libs/lightgallery/LightGallery"; import DataTable from "./libs/datatable/DataTable"; import FormsUtils from "./core/utils/FormsUtils"; import Accordion from "./libs/accordion/Accordion"; import JsColor from "./libs/jscolor/JsColor"; import Search from "./core/ui/Search"; import UploadSettings from "./modules/Files/UploadSettings"; import LockedResource from "./core/locked-resource/LockedResource"; import CallableViaDataAttrsDialogs from "./core/ui/Dialogs/CallableViaDataAttrsDialogs"; import WidgetsDialogs from "./core/ui/Dialogs/WidgetsDialogs"; import Dialog from "./core/ui/Dialogs/Dialog"; import FilesTransfer from "./modules/Files/FilesTransfer"; import MonthlyPayments from "./modules/Payments/MonthlyPayments"; import UploadBasedModules from "./modules/UploadBasedModules"; import Sidebars from "./core/sidebar/Sidebars"; import CopyToClipboardAction from "./core/ui/Actions/CopyToClipboardAction"; import CreateAction from "./core/ui/Actions/CreateAction"; import EditViaTinyMceAction from "./core/ui/Actions/EditViaTinyMceAction"; import FontawesomeAction from "./core/ui/Actions/FontawesomeAction"; import RemoveAction from "./core/ui/Actions/RemoveAction"; import ToggleBoolvalAction from "./core/ui/Actions/ToggleBoolvalAction"; import UpdateAction from "./core/ui/Actions/UpdateAction"; import NotesTinyMce from "./modules/Notes/NotesTinyMce"; import BootstrapSelect from "./libs/bootstrap-select/BootstrapSelect"; import TodoChecklist from "./modules/Todo/TodoChecklist"; import JsCookie from "./libs/js-cookie/JsCookie"; import Ajax from "./core/ajax/Ajax"; import Loader from "./libs/loader/Loader"; import DomElements from "./core/utils/DomElements"; import VideoJs from "./libs/video-js/VideoJs"; import MassActions from "./core/ui/Actions/MassActions"; import Tippy from "./libs/tippy/Tippy"; import TodoModal from "./modules/Todo/TodoModal"; import FineUploaderService from "./libs/fine-uploader/FineUploaderService"; import AjaxEvents from "./core/ajax/AjaxEvents"; import TuiCalendarService from "./libs/tui-calendar/TuiCalendarService"; import SmartTab from "./libs/smarttab/SmartTab"; import JsSettingsTooltip from "./core/ui/JsSettingsTooltip"; import PasswordPreview from "./core/ui/Form/PasswordPreview"; import GeneratePassword from "./libs/generate-password/GeneratePassword"; import EditViaModalPrefilledWithEntityDataAction from "./core/ui/Actions/EditViaModalPrefilledWithEntityDataAction"; /** * @description The entry point of whole project, this is where the entire logic is being triggered on, every single thing * that might eventually be needed on given page is being triggered or reinitialized */ export default class Initializer { /** * @description Will call initialization all all required standard system logic */ public initializeLogic(): void { // libs let apexChartsHandler = new ApexChartsHandler(); let selectize = new Selectize(); let tinymce = new TinyMce(); let prism = new PrismHighlight(); let flatpicker = new FlatPicker(); let loadingBar = new LoadingBar(); let shuffler = new ShuffleWrapper(); let bootstrapToogle = new BootstrapToggle(); let lightGallery = new LightGallery(); let datatable = new DataTable(); let formsUtils = new FormsUtils(); let accordion = new Accordion(); let videoJs = new VideoJs(); let fineUploadService = new FineUploaderService(); let tuiCalendar = new TuiCalendarService(); let smartTab = new SmartTab(); let generatePassword = new GeneratePassword(); // core let search = new Search(); let uploadSettings = new UploadSettings(); let lockedResource = new LockedResource(); let callableViaAttrDialogs = new CallableViaDataAttrsDialogs(); let widgetsDialogs = new WidgetsDialogs(); let dialog = new Dialog(); let domElements = new DomElements(); let ajaxEvents = new AjaxEvents(); let passwordPreview = new PasswordPreview(); // modules let todoChecklist = new TodoChecklist(); let todoModal = new TodoModal(); let filesTransfer = new FilesTransfer(); let monthlyPayments = new MonthlyPayments(); let uploadBasedModules = new UploadBasedModules(); let notesTinyMce = new NotesTinyMce(); // inits BootstrapSelect.init(); this.initializeActions(); Tippy.init(); Sidebars.init(); Sidebars.markCurrentMenuElementAsActive(); selectize.init(); formsUtils.init(); uploadSettings.init(); datatable.init(); loadingBar.init(); tinymce.init(); todoChecklist.init(); todoModal.init(); lightGallery.init(); shuffler.init(); bootstrapToogle.init(); accordion.init(); filesTransfer.init(); search.init(); apexChartsHandler.init(); lockedResource.init(); prism.init(); callableViaAttrDialogs.init(); widgetsDialogs.init(); flatpicker.init(); notesTinyMce.init(); monthlyPayments.init(); uploadBasedModules.init(); JsColor.init(); domElements.init(); dialog.init(); videoJs.init(); fineUploadService.init(); ajaxEvents.init(); tuiCalendar.init(); smartTab.init(); passwordPreview.init(); generatePassword.init(); } /** * @description Initializes the standard system logic and static one */ public reinitializeLogic(): void { this.initializeLogic(); } /** * @description Initializes everything - should be called only upon opening/reloading page without ajax */ fullInitialization(): void { this.initializeLogic(); this.oneTimeInit(); } /** * @description Will call initialization of logic which should be called only once - in case of reloading page without ajax etc * as window events needs to be bound etc, otherwise will stack on each other */ private oneTimeInit(): void { this.handleFirstTimeLogin(); let windowEvents = new WindowEvents(); let documentEvents = new DocumentEvents(); let jsSettings = new JsSettingsTooltip(); jsSettings.setThemeFromCookie(); // new jsSettings.init(); SearchBar.init(); BootstrapDatepicker.init(); Scrollbar.init(); windowEvents.attachEvents(); documentEvents.attachEvents(); } /** * @description Initialize logic for all actions */ private initializeActions(): void { let copyToClipboardAction = new CopyToClipboardAction(); let createAction = new CreateAction(); let editModalPrefilledWithEntityDataAction = new EditViaModalPrefilledWithEntityDataAction(); let editViaTinyMceAction = new EditViaTinyMceAction(); let fontawesomeAction = new FontawesomeAction(); let removeAction = new RemoveAction(); let toggleBoolvalAction = new ToggleBoolvalAction(); let updateAction = new UpdateAction(); let massActions = new MassActions(); copyToClipboardAction.init(); createAction.init(); editModalPrefilledWithEntityDataAction.init(); editViaTinyMceAction.init(); fontawesomeAction.init(); removeAction.init(); toggleBoolvalAction.init(); updateAction.init(); massActions.init(); } /** * @description Will handle special logic designed for the first time login only * @private */ private handleFirstTimeLogin() { if( !JsCookie.isHideFirstLoginInformation() && location.pathname.indexOf('/login') == -1 ){ let isDemoMode = DomElements.doElementsExists($('[data-guide-mode]')); if( isDemoMode ){ let callableViaDataAttrsDialogs = new CallableViaDataAttrsDialogs(); let dialogUrl = Ajax.getUrlForPathName('dialog_body_first_login_information'); callableViaDataAttrsDialogs.buildDialogBody(dialogUrl, Ajax.REQUEST_TYPE_POST,{}, ()=>{ let prism = new PrismHighlight(); prism.init(); Loader.hideMainLoader(); }, true, "Ok") } JsCookie.setHideFirstLoginInformation() } } } /** * @description triggering all necessary logic - must be handled this way */ $(document).ready(() => { let initializer = new Initializer(); initializer.fullInitialization(); });
the_stack
import ProfileInstallerProvider from '../../../providers/ror2/installing/ProfileInstallerProvider'; import ManifestV2 from '../../../model/ManifestV2'; import FileTree from '../../../model/file/FileTree'; import R2Error from '../../../model/errors/R2Error'; import Profile from '../../../model/Profile'; import ModLoaderPackageMapping from '../../../model/installing/ModLoaderPackageMapping'; import path from 'path'; import PathResolver from '../../../r2mm/manager/PathResolver'; import GameManager from '../../../model/game/GameManager'; import { MOD_LOADER_VARIANTS } from '../../../r2mm/installing/profile_installers/ModLoaderVariantRecord'; import FileUtils from '../../../utils/FileUtils'; import FsProvider from '../../../providers/generic/file/FsProvider'; import yaml from "yaml"; import ModFileTracker from '../../../model/installing/ModFileTracker'; import ConflictManagementProvider from '../../../providers/generic/installing/ConflictManagementProvider'; import ModMode from '../../../model/enums/ModMode'; import { RuleType } from '../../../r2mm/installing/InstallationRules'; /** * TODO: * - Implementations * - Track files (where to store? [profile]/_state? somewhere else?) * - ConflictManagementProvider should be used on enable/disable/uninstall. Newly installed will have higher priority than already installed mods. */ export default class MelonLoaderProfileInstaller extends ProfileInstallerProvider { private rule: RuleType; constructor(rule: RuleType) { super(rule); this.rule = rule; } async applyModMode(mod: ManifestV2, tree: FileTree, profile: Profile, location: string, mode: number): Promise<R2Error | void> { try { const modStateFilePath = path.join(location, "_state", `${mod.getName()}-state.yml`); if (await FsProvider.instance.exists(modStateFilePath)) { const fileContents = (await FsProvider.instance.readFile(modStateFilePath)).toString(); const tracker: ModFileTracker = yaml.parse(fileContents); for (const [key, value] of tracker.files) { if (await ConflictManagementProvider.instance.isFileActive(mod, profile, value)) { if (mode === ModMode.DISABLED) { if (await FsProvider.instance.exists(path.join(location, value))) { await FsProvider.instance.unlink(path.join(location, value)); } } else { if (await FsProvider.instance.exists(path.join(location, value))) { await FsProvider.instance.unlink(path.join(location, value)); await FsProvider.instance.copyFile(key, path.join(location, value)); } } } } } } catch (e) { if (e instanceof R2Error) { return e; } else { const err: Error = e; return new R2Error(`Error installing mod: ${mod.getName()}`, err.message, null); } } } async disableMod(mod: ManifestV2, profile: Profile): Promise<R2Error | void> { return this.applyModMode(mod, new FileTree(), profile, profile.getPathOfProfile(), ModMode.DISABLED); } async enableMod(mod: ManifestV2, profile: Profile): Promise<R2Error | void> { return this.applyModMode(mod, new FileTree(), profile, profile.getPathOfProfile(), ModMode.ENABLED); } async getDescendantFiles(tree: FileTree | null, location: string): Promise<string[]> { return Promise.resolve([]); } async installForManifestV2(mod: ManifestV2, profile: Profile, location: string): Promise<R2Error | null> { const fileTree: FileTree | R2Error = await FileTree.buildFromLocation(location); if (fileTree instanceof R2Error) { return fileTree; } fileTree.removeFiles( path.join(location, "manifest.json"), path.join(location, "README.md"), path.join(location, "icon.png") ); const result = await this.resolveBepInExTree(profile, location, path.basename(location), mod, fileTree); if (result instanceof R2Error) { return result; } await ConflictManagementProvider.instance.overrideInstalledState(mod, profile); try { const modStateFilePath = path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`); if (await FsProvider.instance.exists(modStateFilePath)) { const fileContents = (await FsProvider.instance.readFile(modStateFilePath)).toString(); const tracker: ModFileTracker = yaml.parse(fileContents); for (const [key, value] of tracker.files) { await FileUtils.ensureDirectory(path.dirname(path.join(profile.getPathOfProfile(), value))); if (await FsProvider.instance.exists(path.join(profile.getPathOfProfile(), value))) { await FsProvider.instance.unlink(path.join(profile.getPathOfProfile(), value)); } await FsProvider.instance.copyFile(key, path.join(profile.getPathOfProfile(), value)) } } } catch (e) { if (e instanceof R2Error) { return e; } const err: Error = e; return new R2Error(`Error installing mod: ${mod.getName()}`, err.message, null); } return null; } async installMod(mod: ManifestV2, profile: Profile): Promise<R2Error | null> { const cacheDirectory = path.join(PathResolver.MOD_ROOT, 'cache'); const cachedLocationOfMod: string = path.join(cacheDirectory, mod.getName(), mod.getVersionNumber().toString()); const activeGame = GameManager.activeGame; const bepInExVariant = MOD_LOADER_VARIANTS[activeGame.internalFolderName]; const variant = bepInExVariant.find(value => value.packageName.toLowerCase() === mod.getName().toLowerCase()); if (variant !== undefined) { return this.installModLoader(cachedLocationOfMod, variant, profile); } return this.installForManifestV2(mod, profile, cachedLocationOfMod); } async installModLoader(cacheLocation: string, bepInExVariant: ModLoaderPackageMapping, profile: Profile): Promise<R2Error | null> { const tree = await FileTree.buildFromLocation(cacheLocation); if (tree instanceof R2Error) { return tree; } tree.removeFiles( path.join(cacheLocation, "manifest.json"), path.join(cacheLocation, "README.md"), path.join(cacheLocation, "icon.png") ); for (const value of tree.getRecursiveFiles()) { const relativeFile = path.relative(cacheLocation, value); const dir = path.join(profile.getPathOfProfile(), path.dirname(relativeFile)); await FileUtils.ensureDirectory(dir); if (await FsProvider.instance.exists(path.join(profile.getPathOfProfile(), relativeFile))) { await FsProvider.instance.unlink(path.join(profile.getPathOfProfile(), relativeFile)); } try { await FsProvider.instance.copyFile(value, path.join(profile.getPathOfProfile(), relativeFile)); } catch (e) { if (e instanceof R2Error) { return e; } else { const err: Error = e; return new R2Error("Failed to copy file", err.message, null); } } } return Promise.resolve(null); } async resolveBepInExTree(profile: Profile, location: string, folderName: string, mod: ManifestV2, tree: FileTree): Promise<R2Error | void> { const fileRelocations: Map<string, string> = new Map(); for (const directory of tree.getDirectories()) { let dirMatched = false; const matchingDir = Object.keys(this.rule.rules).find(value => value.toLowerCase() === directory.getDirectoryName().toLowerCase()); if (matchingDir !== undefined) { dirMatched = true; directory.getRecursiveFiles().forEach(file => { fileRelocations.set(file, path.relative(location, file)); }) } else { Object.keys(this.rule.rules) .flatMap(topLevel => { // Need to keep track of parent key for fileRelocationResult path. return { topLevel: topLevel, values: Object.keys((this.rule.rules as any)[topLevel]) } }) .forEach(entry => { entry.values.forEach(subLevel => { if (subLevel.toLowerCase() !== "_files") { if (directory.getDirectoryName().toLowerCase() === subLevel.toLowerCase()) { dirMatched = true; directory.getRecursiveFiles().forEach(file => { fileRelocations.set(file, path.join(entry.topLevel, path.relative(location, file))); }) } } }) }); } if (!dirMatched) { const resolveResult = await this.resolveBepInExTree(profile, path.join(location, directory.getDirectoryName()), directory.getDirectoryName(), mod, directory) if (resolveResult instanceof R2Error) { return resolveResult; } } } const filePaths = this.calculateFilePaths(this.rule.rules); // Sort in descending order. // This way ".dll" will be matched after ".plugin.dll" to ensure .plugin.dll takes priority. const sortedFilePaths = Object.keys(filePaths).sort((a, b) => { return b.length - a.length; }); tree.getFiles().forEach(value => { const firstMatchingEnd = sortedFilePaths.find(fp => value.toLowerCase().endsWith(fp.toLowerCase())); if (firstMatchingEnd !== undefined) { // Is registered extension. fileRelocations.set(value, path.join(filePaths[firstMatchingEnd], path.basename(value))); } else { fileRelocations.set(value, path.join(this.rule._defaultPath, path.basename(value))); } }) try { await this.addToStateFile(mod, fileRelocations, profile) } catch (e) { if (e instanceof R2Error) { return e; } else { const err: Error = e; return new R2Error(`Failed to add mod [${mod.getName()}] to state file`, err.message, null); } } return; } private calculateFilePaths(obj: any): {[ext: string]: string} { const rebuild: any = {}; for (const key of Object.keys(obj)) { if (key.toLowerCase() === "_files") { (obj[key] as string[]).forEach(value => { // Leave blank because parent call will populate the correct directory. rebuild[value] = ""; }) } else { const recursive = this.calculateFilePaths(obj[key]); for (const rKey of Object.keys(recursive)) { rebuild[rKey] = path.join(key, recursive[rKey]); } } } return rebuild; } public async addToStateFile(mod: ManifestV2, files: Map<string, string>, profile: Profile) { await FileUtils.ensureDirectory(path.join(profile.getPathOfProfile(), "_state")); let existing: Map<string, string> = new Map(); if (await FsProvider.instance.exists(path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`))) { const read = await FsProvider.instance.readFile(path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`)); const tracker = (yaml.parse(read.toString()) as ModFileTracker); existing = new Map(tracker.files); } files.forEach((value, key) => { existing.set(key, value); }) const mft: ModFileTracker = { modName: mod.getName(), files: Array.from(existing.entries()) } await FsProvider.instance.writeFile(path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`), yaml.stringify(mft)); } async uninstallMod(mod: ManifestV2, profile: Profile): Promise<R2Error | null> { const stateFilePath = path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`); if (await FsProvider.instance.exists(stateFilePath)) { const read = await FsProvider.instance.readFile(stateFilePath); const tracker = (yaml.parse(read.toString()) as ModFileTracker); for (const [cacheFile, installFile] of tracker.files) { if (await FsProvider.instance.exists(path.join(profile.getPathOfProfile(), installFile))) { await FsProvider.instance.unlink(path.join(profile.getPathOfProfile(), installFile)); } } // TODO: Read state file to know which mods to remove await FsProvider.instance.unlink(path.join(profile.getPathOfProfile(), "_state", `${mod.getName()}-state.yml`)); } // TODO: Apply ConflictManagementProvider to re-populate any loose files from a list of removed ones. return Promise.resolve(null); } }
the_stack
import { axisTop } from 'd3-axis'; import { scaleTime, ScaleTime } from 'd3-scale'; import { select, Selection } from 'd3-selection'; import { timeDay, timeHour, timeMonday, timeMonth, timeWeek, timeYear, TimeInterval } from 'd3-time'; import { timeFormat } from 'd3-time-format'; import { zoom, D3ZoomEvent, ZoomBehavior } from 'd3-zoom'; import { IConfig, Layout, SchedulingPeriod } from './interface'; import * as utils from './utils'; export default class Calender { public layout: Layout; public width: number; public height: number; public timeRange: Date[]; public timeSteps: number = 15; public isInit: boolean = false; protected canvas: Selection<SVGGElement, any, any, any>; protected xScale: ScaleTime<number, number>; protected hourAxis: Selection<SVGGElement, any, any, any>; protected dayAxis: Selection<SVGGElement, any, any, any>; protected zoomScale: ScaleTime<number, number>; protected zoom: ZoomBehavior<Element, any>; protected zoomState: any; protected container: string; constructor(config: IConfig) { const { layout, domain, container } = config; this.container = container; this.layout = Object.assign( { height: 240, width: 1300, top: 0, left: 0, right: 0, bottom: 0, firstAxisTop: 22, secondAxisTop: 40, }, layout ); this.width = this.layout.width - this.layout.left - this.layout.right; this.height = this.layout.height - this.layout.top - this.layout.bottom; this.timeRange = (domain && domain.length && domain) || this.getDefaultTimeRange(); this.xScale = scaleTime().range([0, this.width]).domain(this.timeRange); this.zoomScale = this.xScale; this.zoomState = { small: {}, large: {}, }; /** 缩放zoom相关 */ const zoomExtent: [[number, number], [number, number]] = [ [this.layout.left, this.layout.top], [this.width - this.layout.right, this.height - this.layout.top], ]; this.zoom = zoom().extent(zoomExtent).on('zoom', this.zoomFunc.bind(this)); this.render(); } getDefaultTimeRange(): Date[] { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); return [yesterday, new Date()]; } public getZoomScaleExtend(): [number, number] { const domain = this.xScale.domain(); const leftBoundary = timeYear.offset(domain[0], -1); const rightBoundary = timeYear.offset(domain[1], 1); const minScale = (domain[1].getTime() - domain[0].getTime()) / (rightBoundary.getTime() - leftBoundary.getTime()); const maxScale = (domain[1].getTime() - domain[0].getTime()) / (1000 * 60 * 60); return [minScale, maxScale]; } public initXScale() { this.xScale.domain(this.timeRange); const scaleExtend = this.getZoomScaleExtend(); this.zoom.scaleExtent(scaleExtend); } public render(el: string = this.container) { this.initXScale(); const svg = select(el) .append('svg') .attr('height', this.height + this.layout.top + this.layout.bottom) .attr('width', this.width + this.layout.left + this.layout.right) .attr('class', 'offline-node-chart') .style('background', '#252529') .call(this.zoom); this.canvas = svg.append('g').attr('transform', `translate(${this.layout.left}, ${this.layout.top})`); this.canvas .append('g') .attr('transform', `translate(0, ${this.layout.secondAxisTop})`) .attr('class', 'date-label'); this.hourAxis = utils.addAxis(this.canvas, this.layout.secondAxisTop); this.dayAxis = utils.addAxis(this.canvas, 0); this.canvas .append('g') .attr('transform', `translate(0, ${this.layout.secondAxisTop})`) .attr('class', 'start-time-group'); this.canvas .append('g') .attr('transform', `translate(0, ${this.layout.secondAxisTop})`) .attr('class', 'main-chart'); this.renderAxis(); this.isInit = true; } public renderAxis(scale: ScaleTime<number, number> = this.xScale) { this.setZoomState(scale); this.renderSmallUnitAxis(scale); this.renderLargeUnitAxis(scale); } /** 小单位的tick生成器 */ public hourTicksGenerator(scale: ScaleTime<number, number>) { return axisTop(scale) .ticks(this.zoomState.smallTick) .tickSize(-(this.height - this.layout.secondAxisTop)) .tickFormat(this.zoomState.smallTimeFormat); } /** 大单位的tick生成器 */ public dayTicksGenerator(scale: ScaleTime<number, number>) { const self = this; return axisTop(scale) .ticks(self.zoomState.largeTick) .tickSize(-this.height) .tickFormat(this.zoomState.largeTimeFormat); } /** 将label移至Tick的中间 * @unit 单位,默认为'day' * @offsetTop 渲染label的竖向偏移 */ public translateLableToCenter(selection: Selection<SVGGElement, any, any, any>, unit: string = 'day', offsetTop: number = this.layout.firstAxisTop) { selection .selectAll('.tick text') .attr('transform', `translate(${this.timeToPixels(unit, 1) / 2} , ${offsetTop})`) .attr('font-size', '12px'); } /** 重置label的位置,因为小单位有时在tick上,有时在中间,因此需要根据实际scale重置位置 */ public resetLabelPosition(selection: Selection<SVGGElement, any, any, any>) { selection.selectAll('.tick text').attr('transform', `translate(0, 0)`); } /** 渲染大单位坐标轴 */ public renderLargeUnitAxis(scale: ScaleTime<number, number>) { const renderScale = scale || this.xScale; this.dayAxis .call(this.dayTicksGenerator(renderScale)) .call(utils.removeAxisPath) .call(selection => this.translateLableToCenter(selection, this.zoomState.largeUnit)) .call(selection => { utils.setLineColor(selection, '#4b4b52'); }); } /** 渲染小单位坐标轴 */ public renderSmallUnitAxis(scale: ScaleTime<number, number>) { const renderScale = scale || this.xScale; this.hourAxis .call(this.hourTicksGenerator(renderScale)) .call(utils.removeAxisPath) .call((selection: Selection<SVGGElement, any, any, any>) => { utils.setLineColor(selection, '#38383d'); }) .call((selection: Selection<SVGGElement, any, any, any>) => selection.selectAll('.tick text').attr('font-size', '12px') ) .call((selection: Selection<SVGGElement, any, any, any>) => { if (['day', 'month'].includes(this.zoomState.smallUnit)) { this.translateLableToCenter(selection, this.zoomState.smallUnit, 0); this.zoomState.smallUnit === 'day' && this.renderDayDate('day', renderScale.domain()); return; } this.resetLabelPosition(selection); this.renderDayDate('clear'); }); } /** 在smallAxis为日时,需要添加Date日期的显示 */ public renderDayDate(unit: string, domain?: Date[]) { const scale = this.zoomScale || this.xScale; const data = unit === 'clear' ? [] : utils.getVisableTick(unit, domain); const dates = this.canvas .select('.date-label') .selectAll('.date') .data(data, (d: Date) => d.getTime()); dates .enter() .append('text') .attr('class', 'date') .attr('fill', '#63656e') .attr('font-size', '8px') .merge(dates) .text(d => d.getDate()) .attr('x', d => { return scale(d) + this.timeToPixels('day', 1) / 2 + 8; }) .attr('y', -10); dates.exit().remove(); } /** zoom函数,需要重新绘制坐标和图像 */ public zoomFunc(event: D3ZoomEvent<SVGAElement, number>) { const { transform } = event; // const zoomFactor = transform.k; // this.zoom.translateExtent([[this.layout.left, this.layout.top], [this.width - this.layout.right / zoomFactor, this.height - this.layout.top]]) 根据放大倍数,设置拖拽限制 this.zoomScale = transform.rescaleX(this.xScale); this.renderAxis(this.zoomScale); } /** 不同缩放条件下,tick的周期和单位都不同,因此需要根据scale设置zoom状态 */ public setZoomState(scale: ScaleTime<number, number>) { if (this.timeToPixels('hour', 1, scale) > this.timeSteps) { this.zoomState = { smallTick: timeHour.every(1), smallTimeFormat: (domain: Date) => { const hourFormat = timeFormat('%H:%S'); return this.timeToPixels('hour', 1, scale) > 70 ? hourFormat(domain) : domain.getHours() % 2 === 0 ? hourFormat(domain) : ''; }, smallUnit: 'hour', largeTick: timeDay.every(1), largeTimeFormat: timeFormat('%Y-%m-%d'), largeUnit: 'day', }; } else if ( this.timeToPixels('hour', 1, scale) < this.timeSteps && this.timeToPixels('day', 1, scale) > this.timeSteps ) { this.zoomState = { smallTick: timeDay.every(1), smallTimeFormat: (domain: Date) => { const format = timeFormat('%u'); return utils.toChNum(format(domain)); }, smallUnit: 'day', largeTick: timeMonday.every(1), largeTimeFormat: (domain: Date) => { const headFormat = timeFormat('%Y-%m-%d'); const endFormat = timeFormat('%m-%d'); const end = timeDay.offset(domain, 6); return `${headFormat(domain)} ~ ${endFormat(end)}`; }, largeUnit: 'week', }; } else if ( this.timeToPixels('day', 1, scale) < this.timeSteps && this.timeToPixels('week', 1, scale) > this.timeSteps ) { this.zoomState = { smallTick: timeMonday.every(1), smallTimeFormat: timeFormat('%d'), smallUnit: 'week', largeTick: timeMonth.every(1), largeTimeFormat: (domain: Date) => { return `${domain.getFullYear()}年${utils.toChNum(domain.getMonth() + 1)}月`; }, largeUnit: 'month', }; } else { this.zoomState = { smallTick: timeMonth.every(1), smallTimeFormat: (domain: Date) => { return `${domain.getMonth() + 1}月`; }, smallUnit: 'month', largeTick: timeYear.every(1), largeTimeFormat: (domain: Date) => { return `${domain.getFullYear()}年`; }, largeUnit: 'year', }; } } /** 将时间纬度转换为长度,用于可视化渲染和位置计算 */ public timeToPixels(unit: string, time: number, scale?: ScaleTime<number, number>) { let timeUnit: TimeInterval = timeHour; switch (unit) { case 'hour': timeUnit = timeHour; break; case 'day': timeUnit = timeDay; break; case 'week': timeUnit = timeWeek; break; case 'month': timeUnit = timeMonth; break; case 'year': timeUnit = timeYear; break; } const d = new Date(); const timeScale = scale || this.zoomScale || this.xScale; return timeScale(timeUnit.offset(d, time)) - timeScale(d); } }
the_stack
import { assert } from "chai"; import { AbstractMeasurer, Measurer, SingleLineWrapper, SvgContext, Wrapper, } from "../src"; import { d3Selection, generateSVG } from "./utils"; describe("Wrapper Test Suite", () => { let wrapper: Wrapper; let measurer: AbstractMeasurer; let svg: d3Selection<any>; beforeEach(() => { svg = generateSVG(200, 200); svg.append("text"); const context = new SvgContext(svg.node()); measurer = new Measurer(context.createRuler(), true); wrapper = new Wrapper(); }); describe("Core", () => { it("default text trimming option", () => { assert.equal(wrapper.textTrimming(), "ellipsis", "default text trimming is set correctly"); }); it("text trimming option", () => { wrapper.textTrimming("none"); assert.equal(wrapper.textTrimming(), "none", "text trimming is changed"); }); it("wrong text trimming option", () => { assert.throws(() => wrapper.textTrimming("hello")); assert.equal(wrapper.textTrimming(), "ellipsis", "wrong option does not modify wrapper"); }); it("max lines", () => { assert.equal(wrapper.maxLines(), Infinity, "max lines has been set to default"); wrapper.maxLines(3); assert.equal(wrapper.maxLines(), 3, "max lines has been changed"); }); it("allow breaking words", () => { assert.isFalse(wrapper.allowBreakingWords(), "allow breaking words has been disabled to default"); }); }); describe("One token wrapping", () => { let token: string; beforeEach(() => { token = "hello"; wrapper = new Wrapper().textTrimming("none"); }); it("does not wrap", () => { wrapper.allowBreakingWords(true); const dimensions = measurer.measure(token); const result = wrapper.wrap(token, measurer, dimensions.width * 2); assert.deepEqual(result.originalText, token, "original text has been set"); assert.deepEqual(result.wrappedText, token, "wrapped text is the same as original"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "non of tokens has been broken"); assert.deepEqual(result.noLines, 1, "no wrapping was needed"); }); it("does not wrap becasue of height", () => { wrapper.allowBreakingWords(true); const dimensions = measurer.measure(token); const result = wrapper.wrap(token, measurer, dimensions.width, dimensions.height / 2); assert.deepEqual(result.originalText, token, "original text has been set"); assert.deepEqual(result.wrappedText, "", "wrapped text is empty"); assert.deepEqual(result.truncatedText, token, "whole word has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "non of tokens has been broken"); assert.deepEqual(result.noLines, 0, "no wrapping was needed"); }); it("one time wrapping", () => { wrapper.allowBreakingWords(true); const availableWidth = measurer.measure(token).width * 3 / 4; const result = wrapper.wrap(token, measurer, availableWidth); assert.deepEqual(result.originalText, token, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "none of the text has been truncated"); assert.deepEqual(result.noBrokeWords, 1, "wrapping with breaking one word"); assert.deepEqual(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("does not break words", () => { const wrappableToken = "hello world"; const availableWidth = measurer.measure(wrappableToken).width * 3 / 4; const result = wrapper.wrap(wrappableToken, measurer, availableWidth); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.notInclude(result.wrappedText, "-", "no hyphenation"); assert.deepEqual(result.truncatedText, "", "none of the text has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "no broken words"); assert.deepEqual(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("does not break words, except as last resort", () => { const availableWidth = measurer.measure(token).width * 3 / 4; const result = wrapper.wrap(token, measurer, availableWidth); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.deepEqual(result.noBrokeWords, 1, "wrapping with breaking one word"); assert.deepEqual(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it.skip("multi time wrapping", () => { wrapper.allowBreakingWords(true); const availableWidth = measurer.measure("h-").width; const result = wrapper.wrap(token, measurer, availableWidth); assert.deepEqual(result.originalText, token, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 3, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.deepEqual(result.noBrokeWords, 2, "wrapping with breaking word"); assert.deepEqual(result.noLines, 3, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("wrapping is impossible", () => { wrapper.allowBreakingWords(true); const availableWidth = measurer.measure("h").width - 0.1; const result = wrapper.wrap(token, measurer, availableWidth); assert.deepEqual(result.originalText, token, "original text has been set"); assert.equal(result.wrappedText, "", "wrapping was impossible so no wrapping"); assert.deepEqual(result.truncatedText, token, "whole text has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "no breaks"); assert.deepEqual(result.noLines, 0, "wrapped text has no lines"); }); it("only first sign fits", () => { wrapper.allowBreakingWords(true); const tokenWithSmallFirstSign = "aHHH"; const availableWidth = measurer.measure("a-").width; const result = wrapper.wrap(tokenWithSmallFirstSign, measurer, availableWidth); assert.deepEqual(result.originalText, tokenWithSmallFirstSign, "original text has been set"); assert.equal(result.wrappedText, "", "wrapping was impossible"); assert.deepEqual(result.truncatedText, tokenWithSmallFirstSign, "whole word has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "none word breaks"); assert.deepEqual(result.noLines, 0, "wrapped text has no lines"); }); }); describe("One line wrapping", () => { let line: string; beforeEach(() => { line = "hello world!."; wrapper = new Wrapper().textTrimming("none"); }); it("does not wrap", () => { wrapper.allowBreakingWords(true); const dimensions = measurer.measure(line); const result = wrapper.wrap(line, measurer, dimensions.width * 2); assert.deepEqual(result.originalText, line, "original text has been set"); assert.deepEqual(result.wrappedText, line, "wrapped text is the same as original"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.equal(result.noBrokeWords, 0, "non of tokens has been broken"); assert.equal(result.noLines, 1, "no wrapping was needed"); }); it("does not break words", () => { const availableWidth = measurer.measure(line).width * 0.75; const result = wrapper.wrap(line, measurer, availableWidth); assert.deepEqual(result.originalText, line, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.equal(result.noBrokeWords, 0, "wrapping with breaking no word"); assert.equal(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("only token sign fits", () => { const tokenWithSmallFirstSign = "!HHH"; const availableWidth = measurer.measure("!").width * 2; const result = wrapper.wrap(tokenWithSmallFirstSign, measurer, availableWidth); assert.deepEqual(result.originalText, tokenWithSmallFirstSign, "original text has been set"); assert.equal(result.wrappedText, "!", "wrapping was possible"); assert.deepEqual(result.truncatedText, "HHH", "big letters have been truncated"); assert.deepEqual(result.noBrokeWords, 0, "no breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("one time wrapping", () => { wrapper.allowBreakingWords(true); const availableWidth = measurer.measure(line).width * 0.75; const result = wrapper.wrap(line, measurer, availableWidth); assert.deepEqual(result.originalText, line, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.equal(result.noBrokeWords, 1, "wrapping with breaking one word"); assert.equal(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("whitespaces at the end", () => { line = "hello wor"; const availableWidth = measurer.measure("hello").width; const result = wrapper.wrap(line, measurer, availableWidth); assert.deepEqual(result.originalText, line, "original text has been set"); assert.deepEqual(result.wrappedText, "hello\nwor", "only first word fits"); assert.deepEqual(result.truncatedText, "", "whole line fits"); assert.equal(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("multi time wrapping", () => { const availableWidth = measurer.measure("hell").width; const result = wrapper.wrap(line, measurer, availableWidth); assert.deepEqual(result.originalText, line, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 5, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.closeTo(result.noBrokeWords, 3, 1, "wrapping with breaking two words about three times"); assert.equal(result.noLines, 5, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("wrapping is impossible", () => { const availableWidth = measurer.measure("h").width - 0.1; const result = wrapper.wrap(line, measurer, availableWidth); assert.deepEqual(result.originalText, line, "original text has been set"); assert.equal(result.wrappedText, "", "wrapping was impossible"); assert.deepEqual(result.truncatedText, line, "whole text has been truncated"); assert.deepEqual(result.noBrokeWords, 0, "no breaks"); assert.deepEqual(result.noLines, 0, "wrapped text has no lines"); }); it("wrapping many whitespaces", () => { const lineWithWhitespaces = "hello \t !!!"; const availableWidth = measurer.measure("hello !!!").width; const result = wrapper.wrap(lineWithWhitespaces, measurer, availableWidth); assert.deepEqual(result.originalText, lineWithWhitespaces, "original text has been set"); assert.deepEqual(result.truncatedText, "", "whole text has fit in"); assert.equal(result.noBrokeWords, 0, "no breaks"); assert.equal(result.noLines, 1, "wrapped text has two lines"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); }); describe("multiple line wrapping", () => { let lines: string; beforeEach(() => { lines = "hello world!.\nhello world!."; wrapper = new Wrapper().textTrimming("none"); }); it("does not wrap", () => { const dimensions = measurer.measure(lines); const result = wrapper.wrap(lines, measurer, dimensions.width * 2); assert.deepEqual(result.originalText, lines, "original text has been set"); assert.deepEqual(result.wrappedText, lines, "wrapped text is the same as original"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.equal(result.noBrokeWords, 0, "non of tokens has been broken"); assert.equal(result.noLines, 2, "no wrapping was needed"); }); it("only token sign fits", () => { const tokenWithSmallFirstSign = "!HHH\n."; const availableWidth = measurer.measure("!-").width; const result = wrapper.wrap(tokenWithSmallFirstSign, measurer, availableWidth); assert.deepEqual(result.originalText, tokenWithSmallFirstSign, "original text has been set"); assert.equal(result.wrappedText, tokenWithSmallFirstSign.substring(0, 1), "wrapping was possible"); assert.deepEqual(result.truncatedText, tokenWithSmallFirstSign.substring(1), "big letters have been truncated"); assert.deepEqual(result.noBrokeWords, 0, "no breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("one time wrapping", () => { wrapper.allowBreakingWords(true); const availableWidth = measurer.measure(lines).width * 0.75; const result = wrapper.wrap(lines, measurer, availableWidth); assert.deepEqual(result.originalText, lines, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 4, "wrapping occured"); assert.deepEqual(result.truncatedText, "", "non of the text has been truncated"); assert.equal(result.noBrokeWords, 2, "wrapping with breaking one word"); assert.equal(result.noLines, 4, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); }); describe("Max lines", () => { let text: string; beforeEach(() => { text = "hello world!.\nhello world!."; wrapper = new Wrapper().textTrimming("none"); }); it("no lines fits", () => { const dimensions = measurer.measure(text); wrapper.maxLines(0); const result = wrapper.wrap(text, measurer, dimensions.width * 2); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, "", "wrapped text contains non characters"); assert.deepEqual(result.truncatedText, text, "maxLines truncates both lines"); assert.equal(result.noBrokeWords, 0, "non of tokens has been broken"); assert.equal(result.noLines, 0, "no lines fits"); }); it("does not wrap", () => { const lines = text.split("\n"); const dimensions = measurer.measure(text); wrapper.maxLines(1); const result = wrapper.wrap(text, measurer, dimensions.width * 2); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, lines[0], "wrapped text contains first line"); assert.deepEqual(result.truncatedText, lines[1], "maxLines truncates second line"); assert.equal(result.noBrokeWords, 0, "non of tokens has been broken"); assert.equal(result.noLines, 1, "only first line fits"); }); it("one time wrapping", () => { const lines = text.split("\n"); wrapper.allowBreakingWords(true); wrapper.maxLines(2); const availableWidth = measurer.measure(text).width * 0.75; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 2, "wrapping occured"); assert.deepEqual(result.truncatedText, lines[1], "maxLines truncates second line"); assert.equal(result.noBrokeWords, 1, "wrapping with breaking one word"); assert.equal(result.noLines, 2, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); it("in the middle of line", () => { const availableWidth = measurer.measure(text).width * 0.75; wrapper.allowBreakingWords(true); wrapper.maxLines(3); const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.lengthOf(result.wrappedText.split("\n"), 3, "wrapping occured"); assert.notEqual(result.truncatedText, "", "maxLines truncates second line"); assert.equal(result.noBrokeWords, 2, "wrapping with breaking one word"); assert.equal(result.noLines, 3, "wrapping was needed"); assert.operator(measurer.measure(result.wrappedText).width, "<=", availableWidth, "wrapped text fits in"); }); }); describe("Ellipsis", () => { let text: string; beforeEach(() => { text = "hello"; wrapper = new Wrapper().maxLines(1); }); it("single word", () => { const availableWidth = measurer.measure(text).width - 0.1; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.notEqual(result.wrappedText.indexOf("..."), -1, "ellipsis has been added"); assert.deepEqual(result.noBrokeWords, 1, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); // Failing firefox linux xit("single token fits", () => { text = "!HHH"; const availableWidth = measurer.measure("!...").width; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, "!...", "ellipsis has been added"); assert.deepEqual(result.truncatedText, "HHH", "only first sign fits"); assert.deepEqual(result.noBrokeWords, 0, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("nothing fits", () => { text = "!HHH"; const availableWidth = measurer.measure("...").width; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, "...", "ellipsis has been added"); assert.deepEqual(result.truncatedText, "!HHH", "whole word is truncated"); assert.deepEqual(result.noBrokeWords, 0, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("handling whitespaces", () => { wrapper.allowBreakingWords(true); text = "this aa"; const availableWidth = measurer.measure(text).width - 1; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, "this...", "whitespaces has been ommited"); assert.deepEqual(result.truncatedText, "aa", "suffix has been truncated"); assert.deepEqual(result.noBrokeWords, 1, "one break"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("ellipsis just fit", () => { const availableWidth = measurer.measure("h-").width; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.deepEqual(result.wrappedText, "...", "ellipsis has been added"); assert.deepEqual(result.truncatedText, text, "text has been truncated"); assert.deepEqual(result.noBrokeWords, 1, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("multiple token", () => { wrapper.allowBreakingWords(true); text = "hello world!"; const availableWidth = measurer.measure("hello worl-").width; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.operator(result.wrappedText.indexOf("..."), ">", 0, "ellipsis has been added"); assert.deepEqual(result.wrappedText.substring(0, result.wrappedText.length - 3) + result.truncatedText, text, "non of letters disappeard"); assert.deepEqual(result.noBrokeWords, 1, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); it("multiple lines", () => { wrapper.allowBreakingWords(true); text = "hello world!.\nhello world!."; const availableWidth = measurer.measure("hello worl-").width; const result = wrapper.wrap(text, measurer, availableWidth); assert.deepEqual(result.originalText, text, "original text has been set"); assert.operator(result.wrappedText.indexOf("..."), ">", 0, "ellipsis has been added"); assert.deepEqual(result.wrappedText.substring(0, result.wrappedText.length - 3) + result.truncatedText, text, "non of letters disappeard"); assert.deepEqual(result.noBrokeWords, 1, "one breaks"); assert.deepEqual(result.noLines, 1, "wrapped text has one lines"); }); }); describe("Single Line wrapper", () => { beforeEach(() => { wrapper = new SingleLineWrapper().maxLines(2); }); it("simple", () => { const text = "hello."; const availableWidth = measurer.measure(text).width; const baseWrapper = new Wrapper().maxLines(2); const result = wrapper.wrap(text, measurer, availableWidth); const baseResult = baseWrapper.wrap(text, measurer, availableWidth); const baseDimensions = measurer.measure(baseResult.wrappedText); const dimensions = measurer.measure(result.wrappedText); assert.deepEqual(result.originalText, text, "original text has been set"); assert.equal(result.wrappedText, text, "wrapped text is not the whole line"); assert.equal(result.wrappedText, baseResult.wrappedText, "wrapped text looks better"); assert.equal(dimensions.width, baseDimensions.width, "occupies same width"); assert.equal(dimensions.height, baseDimensions.height, "occupies same height"); assert.operator(dimensions.width, "<=", availableWidth, "wrapped text fits in"); }); it("two lines", () => { const text = "hello world!."; const availableWidth = measurer.measure(text).width - 2; const baseWrapper = new Wrapper().maxLines(2); const result = wrapper.wrap(text, measurer, availableWidth); const baseResult = baseWrapper.wrap(text, measurer, availableWidth); const baseDimensions = measurer.measure(baseResult.wrappedText); const dimensions = measurer.measure(result.wrappedText); assert.deepEqual(result.originalText, text, "original text has been set"); assert.notEqual(result.wrappedText, text, "wrapped text is not the whole line"); assert.notEqual(result.wrappedText, baseResult.wrappedText, "wrapped text looks better"); assert.operator(dimensions.width, "<", baseDimensions.width, "occupies less width"); assert.equal(dimensions.height, baseDimensions.height, "occupies same height"); assert.operator(dimensions.width, "<=", availableWidth, "wrapped text fits in"); }); it("only one line", () => { const text = "hello world!.\naa"; const availableWidth = measurer.measure(text).width - 2; assert.throws(() => wrapper.wrap(text, measurer, availableWidth), "SingleLineWrapper is designed to work only on single line"); }); }); afterEach(() => { svg.remove(); }); });
the_stack
import * as coreClient from "@azure/core-client"; export interface AdapterInformationListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: AdapterInformation[]; location?: string; } export interface AdapterInformation { type?: AdapterInformationType; displayName?: string; inputDataSchema?: string; inputDataForm?: string; } export interface ErrorResult { code?: number; status?: string; errors?: ResultError[]; } export interface ResultError { code?: ResultErrorCode; message?: string; errors?: ValidationError[]; } export interface ValidationError { field?: string; message?: string; } export interface ComponentListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: Component[]; location?: string; } export interface Component { href?: string; organization: string; templateId: string; projectId: string; creator: string; displayName?: string; description?: string; inputJson?: string; valueJson?: string; type: ComponentType; resourceId?: string; resourceUrl?: string; resourceState?: ComponentResourceState; deploymentScopeId?: string; identityId?: string; deleted?: Date; ttl?: number; slug: string; id: string; } export interface ComponentDefinition { templateId: string; displayName: string; inputJson?: string; deploymentScopeId?: string; } export interface ComponentDataResult { code?: number; status?: string; data?: Component; location?: string; } export interface StatusResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly state?: string; stateMessage?: string; location?: string; errors?: ResultError[]; trackingId?: string; } export interface ComponentTaskListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: ComponentTask[]; location?: string; } export interface ComponentTask { organization: string; componentId: string; projectId: string; requestedBy?: string; scheduleId?: string; type?: ComponentTaskType; typeName?: string; created?: Date; started?: Date; finished?: Date; inputJson?: string; output?: string; resourceId?: string; resourceState?: ComponentTaskResourceState; exitCode?: number; id: string; } export interface ComponentTaskDefinition { taskId: string; inputJson?: string; } export interface ComponentTaskDataResult { code?: number; status?: string; data?: ComponentTask; location?: string; } export interface ComponentTemplateListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: ComponentTemplate[]; location?: string; } export interface ComponentTemplate { organization: string; parentId: string; displayName?: string; description?: string; repository: RepositoryReference; permissions?: ComponentTemplatePermissions; inputJsonSchema?: string; tasks?: ComponentTaskTemplate[]; taskRunner?: ComponentTaskRunner; type: ComponentTemplateType; folder?: string; /** Anything */ configuration?: any; id: string; } export interface RepositoryReference { url: string; token?: string; version?: string; baselUrl?: string; mountUrl?: string; ref?: string; provider: RepositoryReferenceProvider; type: RepositoryReferenceType; organization?: string; repository?: string; project?: string; } export interface ComponentTemplatePermissions { none?: string[]; member?: string[]; admin?: string[]; owner?: string[]; adapter?: string[]; } export interface ComponentTaskTemplate { id?: string; displayName?: string; description?: string; inputJsonSchema?: string; type?: ComponentTaskTemplateType; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly typeName?: string; } export interface ComponentTaskRunner { id?: string; /** Dictionary of <string> */ with?: { [propertyName: string]: string; }; } export interface ComponentTemplateDataResult { code?: number; status?: string; data?: ComponentTemplate; location?: string; } export interface DeploymentScopeListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: DeploymentScope[]; location?: string; } export interface DeploymentScope { organization: string; displayName: string; slug: string; isDefault: boolean; type: DeploymentScopeType; inputDataSchema?: string; inputData?: string; managementGroupId?: string; subscriptionIds?: string[]; authorizable?: boolean; authorized?: boolean; authorizeUrl?: string; componentTypes?: DeploymentScopeComponentTypesItem[]; id: string; } export interface DeploymentScopeDefinition { displayName: string; type: DeploymentScopeDefinitionType; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly slug?: string; inputData?: string; isDefault?: boolean; } export interface DeploymentScopeDataResult { code?: number; status?: string; data?: DeploymentScope; location?: string; } export interface CommandAuditEntityListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: CommandAuditEntity[]; location?: string; } export interface CommandAuditEntity { /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly commandId?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly organizationId?: string; commandJson?: string; resultJson?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly projectId?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly userId?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly parentId?: string; command?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly componentTask?: string; runtimeStatus?: CommandAuditEntityRuntimeStatus; customStatus?: string; errors?: string; created?: Date; updated?: Date; } export interface CommandAuditEntityDataResult { code?: number; status?: string; data?: CommandAuditEntity; location?: string; } export interface StringListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: string[]; location?: string; } export interface OrganizationListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: Organization[]; location?: string; } export interface Organization { tenant: string; slug: string; displayName: string; subscriptionId: string; location: string; /** Dictionary of <string> */ tags?: { [propertyName: string]: string; }; resourceId?: string; resourceState?: OrganizationResourceState; galleryId?: string; registryId?: string; storageId?: string; id: string; } export interface OrganizationDefinition { /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly slug?: string; displayName: string; subscriptionId: string; location: string; } export interface OrganizationDataResult { code?: number; status?: string; data?: Organization; location?: string; } export interface UserListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: User[]; location?: string; } export interface User { organization: string; displayName?: string; loginName?: string; mailAddress?: string; userType: UserType; role: UserRole; projectMemberships?: ProjectMembership[]; alternateIdentities?: UserAlternateIdentities; /** Dictionary of <string> */ properties?: { [propertyName: string]: string; }; id: string; } export interface ProjectMembership { projectId: string; role: ProjectMembershipRole; /** Dictionary of <string> */ properties?: { [propertyName: string]: string; }; } export interface UserAlternateIdentities { azureResourceManager?: AlternateIdentity; azureDevOps?: AlternateIdentity; gitHub?: AlternateIdentity; } export interface AlternateIdentity { login?: string; } export interface UserDefinition { identifier: string; role: string; /** Dictionary of <string> */ properties?: { [propertyName: string]: string; }; } export interface UserDataResult { code?: number; status?: string; data?: User; location?: string; } export interface ProjectListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: Project[]; location?: string; } export interface Project { organization: string; slug: string; displayName: string; template: string; templateInput?: string; users?: User[]; /** Dictionary of <string> */ tags?: { [propertyName: string]: string; }; resourceId?: string; resourceState?: ProjectResourceState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly vaultId?: string; sharedVaultId?: string; secretsVaultId?: string; storageId?: string; id: string; } export interface ProjectDefinition { /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly slug?: string; displayName: string; template: string; templateInput: string; users?: UserDefinition[]; } export interface ProjectDataResult { code?: number; status?: string; data?: Project; location?: string; } export interface ProjectIdentityListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: ProjectIdentity[]; location?: string; } export interface ProjectIdentity { projectId: string; organization: string; displayName: string; deploymentScopeId: string; tenantId?: string; clientId?: string; clientSecret?: string; redirectUrls?: string[]; objectId?: string; id: string; } export interface ProjectIdentityDefinition { displayName: string; deploymentScopeId: string; } export interface ProjectIdentityDataResult { code?: number; status?: string; data?: ProjectIdentity; location?: string; } export interface StringDictionaryDataResult { code?: number; status?: string; /** * Dictionary of <string> * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: { [propertyName: string]: string; }; location?: string; } export interface ProjectTemplateListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: ProjectTemplate[]; location?: string; } export interface ProjectTemplate { organization: string; slug: string; name?: string; displayName: string; components?: string[]; repository: RepositoryReference; description?: string; isDefault: boolean; inputJsonSchema?: string; id: string; } export interface ProjectTemplateDefinition { displayName: string; repository: RepositoryDefinition; } export interface RepositoryDefinition { url: string; token?: string; version?: string; } export interface ProjectTemplateDataResult { code?: number; status?: string; data?: ProjectTemplate; location?: string; } export interface ScheduleListDataResult { code?: number; status?: string; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly data?: Schedule[]; location?: string; } export interface Schedule { organization: string; projectId: string; enabled?: boolean; recurring?: boolean; daysOfWeek?: ScheduleDaysOfWeekItem[]; utcHour?: number; utcMinute?: number; creator?: string; created?: Date; lastUpdatedBy?: string; lastUpdated?: Date; lastRun?: Date; componentTasks?: ComponentTaskReference[]; id: string; } export interface ComponentTaskReference { componentId?: string; componentTaskTemplateId?: string; inputJson?: string; } export interface ScheduleDefinition { enabled?: boolean; recurring?: boolean; daysOfWeek?: ScheduleDefinitionDaysOfWeekItem[]; utcHour?: number; utcMinute?: number; componentTasks?: ComponentTaskReference[]; } export interface ScheduleDataResult { code?: number; status?: string; data?: Schedule; location?: string; } /** Known values of {@link AdapterInformationType} that the service accepts. */ export declare const enum KnownAdapterInformationType { AzureResourceManager = "AzureResourceManager", AzureDevOps = "AzureDevOps", GitHub = "GitHub" } /** * Defines values for AdapterInformationType. \ * {@link KnownAdapterInformationType} can be used interchangeably with AdapterInformationType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AzureResourceManager** \ * **AzureDevOps** \ * **GitHub** */ export declare type AdapterInformationType = string; /** Known values of {@link ResultErrorCode} that the service accepts. */ export declare const enum KnownResultErrorCode { Unknown = "Unknown", Failed = "Failed", Conflict = "Conflict", NotFound = "NotFound", ServerError = "ServerError", ValidationError = "ValidationError", Unauthorized = "Unauthorized", Forbidden = "Forbidden" } /** * Defines values for ResultErrorCode. \ * {@link KnownResultErrorCode} can be used interchangeably with ResultErrorCode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Failed** \ * **Conflict** \ * **NotFound** \ * **ServerError** \ * **ValidationError** \ * **Unauthorized** \ * **Forbidden** */ export declare type ResultErrorCode = string; /** Known values of {@link ComponentType} that the service accepts. */ export declare const enum KnownComponentType { Environment = "Environment", Repository = "Repository" } /** * Defines values for ComponentType. \ * {@link KnownComponentType} can be used interchangeably with ComponentType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Environment** \ * **Repository** */ export declare type ComponentType = string; /** Known values of {@link ComponentResourceState} that the service accepts. */ export declare const enum KnownComponentResourceState { Pending = "Pending", Initializing = "Initializing", Provisioning = "Provisioning", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for ComponentResourceState. \ * {@link KnownComponentResourceState} can be used interchangeably with ComponentResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Initializing** \ * **Provisioning** \ * **Succeeded** \ * **Failed** */ export declare type ComponentResourceState = string; /** Known values of {@link ComponentTaskType} that the service accepts. */ export declare const enum KnownComponentTaskType { Custom = "Custom", Create = "Create", Delete = "Delete" } /** * Defines values for ComponentTaskType. \ * {@link KnownComponentTaskType} can be used interchangeably with ComponentTaskType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Custom** \ * **Create** \ * **Delete** */ export declare type ComponentTaskType = string; /** Known values of {@link ComponentTaskResourceState} that the service accepts. */ export declare const enum KnownComponentTaskResourceState { Pending = "Pending", Initializing = "Initializing", Provisioning = "Provisioning", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for ComponentTaskResourceState. \ * {@link KnownComponentTaskResourceState} can be used interchangeably with ComponentTaskResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Initializing** \ * **Provisioning** \ * **Succeeded** \ * **Failed** */ export declare type ComponentTaskResourceState = string; /** Known values of {@link RepositoryReferenceProvider} that the service accepts. */ export declare const enum KnownRepositoryReferenceProvider { Unknown = "Unknown", GitHub = "GitHub", DevOps = "DevOps" } /** * Defines values for RepositoryReferenceProvider. \ * {@link KnownRepositoryReferenceProvider} can be used interchangeably with RepositoryReferenceProvider, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **GitHub** \ * **DevOps** */ export declare type RepositoryReferenceProvider = string; /** Known values of {@link RepositoryReferenceType} that the service accepts. */ export declare const enum KnownRepositoryReferenceType { Unknown = "Unknown", Tag = "Tag", Branch = "Branch", Hash = "Hash" } /** * Defines values for RepositoryReferenceType. \ * {@link KnownRepositoryReferenceType} can be used interchangeably with RepositoryReferenceType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Tag** \ * **Branch** \ * **Hash** */ export declare type RepositoryReferenceType = string; /** Known values of {@link ComponentTaskTemplateType} that the service accepts. */ export declare const enum KnownComponentTaskTemplateType { Custom = "Custom", Create = "Create", Delete = "Delete" } /** * Defines values for ComponentTaskTemplateType. \ * {@link KnownComponentTaskTemplateType} can be used interchangeably with ComponentTaskTemplateType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Custom** \ * **Create** \ * **Delete** */ export declare type ComponentTaskTemplateType = string; /** Known values of {@link ComponentTemplateType} that the service accepts. */ export declare const enum KnownComponentTemplateType { Environment = "Environment", Repository = "Repository" } /** * Defines values for ComponentTemplateType. \ * {@link KnownComponentTemplateType} can be used interchangeably with ComponentTemplateType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Environment** \ * **Repository** */ export declare type ComponentTemplateType = string; /** Known values of {@link DeploymentScopeType} that the service accepts. */ export declare const enum KnownDeploymentScopeType { AzureResourceManager = "AzureResourceManager", AzureDevOps = "AzureDevOps", GitHub = "GitHub" } /** * Defines values for DeploymentScopeType. \ * {@link KnownDeploymentScopeType} can be used interchangeably with DeploymentScopeType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AzureResourceManager** \ * **AzureDevOps** \ * **GitHub** */ export declare type DeploymentScopeType = string; /** Known values of {@link DeploymentScopeComponentTypesItem} that the service accepts. */ export declare const enum KnownDeploymentScopeComponentTypesItem { Environment = "Environment", Repository = "Repository" } /** * Defines values for DeploymentScopeComponentTypesItem. \ * {@link KnownDeploymentScopeComponentTypesItem} can be used interchangeably with DeploymentScopeComponentTypesItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Environment** \ * **Repository** */ export declare type DeploymentScopeComponentTypesItem = string; /** Known values of {@link DeploymentScopeDefinitionType} that the service accepts. */ export declare const enum KnownDeploymentScopeDefinitionType { AzureResourceManager = "AzureResourceManager", AzureDevOps = "AzureDevOps", GitHub = "GitHub" } /** * Defines values for DeploymentScopeDefinitionType. \ * {@link KnownDeploymentScopeDefinitionType} can be used interchangeably with DeploymentScopeDefinitionType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AzureResourceManager** \ * **AzureDevOps** \ * **GitHub** */ export declare type DeploymentScopeDefinitionType = string; /** Known values of {@link CommandAuditEntityRuntimeStatus} that the service accepts. */ export declare const enum KnownCommandAuditEntityRuntimeStatus { Unknown = "Unknown", Running = "Running", Completed = "Completed", ContinuedAsNew = "ContinuedAsNew", Failed = "Failed", Canceled = "Canceled", Terminated = "Terminated", Pending = "Pending" } /** * Defines values for CommandAuditEntityRuntimeStatus. \ * {@link KnownCommandAuditEntityRuntimeStatus} can be used interchangeably with CommandAuditEntityRuntimeStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Running** \ * **Completed** \ * **ContinuedAsNew** \ * **Failed** \ * **Canceled** \ * **Terminated** \ * **Pending** */ export declare type CommandAuditEntityRuntimeStatus = string; /** Known values of {@link OrganizationResourceState} that the service accepts. */ export declare const enum KnownOrganizationResourceState { Pending = "Pending", Initializing = "Initializing", Provisioning = "Provisioning", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for OrganizationResourceState. \ * {@link KnownOrganizationResourceState} can be used interchangeably with OrganizationResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Initializing** \ * **Provisioning** \ * **Succeeded** \ * **Failed** */ export declare type OrganizationResourceState = string; /** Known values of {@link UserType} that the service accepts. */ export declare const enum KnownUserType { User = "User", Group = "Group", System = "System", Service = "Service" } /** * Defines values for UserType. \ * {@link KnownUserType} can be used interchangeably with UserType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Group** \ * **System** \ * **Service** */ export declare type UserType = string; /** Known values of {@link UserRole} that the service accepts. */ export declare const enum KnownUserRole { None = "None", Member = "Member", Admin = "Admin", Owner = "Owner" } /** * Defines values for UserRole. \ * {@link KnownUserRole} can be used interchangeably with UserRole, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Member** \ * **Admin** \ * **Owner** */ export declare type UserRole = string; /** Known values of {@link ProjectMembershipRole} that the service accepts. */ export declare const enum KnownProjectMembershipRole { None = "None", Member = "Member", Admin = "Admin", Owner = "Owner", Adapter = "Adapter" } /** * Defines values for ProjectMembershipRole. \ * {@link KnownProjectMembershipRole} can be used interchangeably with ProjectMembershipRole, * this enum contains the known values that the service supports. * ### Known values supported by the service * **None** \ * **Member** \ * **Admin** \ * **Owner** \ * **Adapter** */ export declare type ProjectMembershipRole = string; /** Known values of {@link ProjectResourceState} that the service accepts. */ export declare const enum KnownProjectResourceState { Pending = "Pending", Initializing = "Initializing", Provisioning = "Provisioning", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for ProjectResourceState. \ * {@link KnownProjectResourceState} can be used interchangeably with ProjectResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Initializing** \ * **Provisioning** \ * **Succeeded** \ * **Failed** */ export declare type ProjectResourceState = string; /** Known values of {@link ScheduleDaysOfWeekItem} that the service accepts. */ export declare const enum KnownScheduleDaysOfWeekItem { Sunday = "Sunday", Monday = "Monday", Tuesday = "Tuesday", Wednesday = "Wednesday", Thursday = "Thursday", Friday = "Friday", Saturday = "Saturday" } /** * Defines values for ScheduleDaysOfWeekItem. \ * {@link KnownScheduleDaysOfWeekItem} can be used interchangeably with ScheduleDaysOfWeekItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Sunday** \ * **Monday** \ * **Tuesday** \ * **Wednesday** \ * **Thursday** \ * **Friday** \ * **Saturday** */ export declare type ScheduleDaysOfWeekItem = string; /** Known values of {@link ScheduleDefinitionDaysOfWeekItem} that the service accepts. */ export declare const enum KnownScheduleDefinitionDaysOfWeekItem { Sunday = "Sunday", Monday = "Monday", Tuesday = "Tuesday", Wednesday = "Wednesday", Thursday = "Thursday", Friday = "Friday", Saturday = "Saturday" } /** * Defines values for ScheduleDefinitionDaysOfWeekItem. \ * {@link KnownScheduleDefinitionDaysOfWeekItem} can be used interchangeably with ScheduleDefinitionDaysOfWeekItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Sunday** \ * **Monday** \ * **Tuesday** \ * **Wednesday** \ * **Thursday** \ * **Friday** \ * **Saturday** */ export declare type ScheduleDefinitionDaysOfWeekItem = string; /** Optional parameters. */ export interface TeamCloudGetAdaptersOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getAdapters operation. */ export declare type TeamCloudGetAdaptersResponse = AdapterInformationListDataResult; /** Optional parameters. */ export interface TeamCloudGetComponentsOptionalParams extends coreClient.OperationOptions { deleted?: boolean; } /** Contains response data for the getComponents operation. */ export declare type TeamCloudGetComponentsResponse = ComponentListDataResult; /** Optional parameters. */ export interface TeamCloudCreateComponentOptionalParams extends coreClient.OperationOptions { body?: ComponentDefinition; } /** Contains response data for the createComponent operation. */ export declare type TeamCloudCreateComponentResponse = ComponentDataResult; /** Optional parameters. */ export interface TeamCloudGetComponentOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getComponent operation. */ export declare type TeamCloudGetComponentResponse = ComponentDataResult; /** Optional parameters. */ export interface TeamCloudDeleteComponentOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteComponent operation. */ export declare type TeamCloudDeleteComponentResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetComponentTasksOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getComponentTasks operation. */ export declare type TeamCloudGetComponentTasksResponse = ComponentTaskListDataResult; /** Optional parameters. */ export interface TeamCloudCreateComponentTaskOptionalParams extends coreClient.OperationOptions { body?: ComponentTaskDefinition; } /** Contains response data for the createComponentTask operation. */ export declare type TeamCloudCreateComponentTaskResponse = ComponentTaskDataResult; /** Optional parameters. */ export interface TeamCloudGetComponentTaskOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getComponentTask operation. */ export declare type TeamCloudGetComponentTaskResponse = ComponentTaskDataResult; /** Optional parameters. */ export interface TeamCloudGetComponentTemplatesOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getComponentTemplates operation. */ export declare type TeamCloudGetComponentTemplatesResponse = ComponentTemplateListDataResult; /** Optional parameters. */ export interface TeamCloudGetComponentTemplateOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getComponentTemplate operation. */ export declare type TeamCloudGetComponentTemplateResponse = ComponentTemplateDataResult; /** Optional parameters. */ export interface TeamCloudGetDeploymentScopesOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getDeploymentScopes operation. */ export declare type TeamCloudGetDeploymentScopesResponse = DeploymentScopeListDataResult; /** Optional parameters. */ export interface TeamCloudCreateDeploymentScopeOptionalParams extends coreClient.OperationOptions { body?: DeploymentScopeDefinition; } /** Contains response data for the createDeploymentScope operation. */ export declare type TeamCloudCreateDeploymentScopeResponse = DeploymentScopeDataResult; /** Optional parameters. */ export interface TeamCloudGetDeploymentScopeOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getDeploymentScope operation. */ export declare type TeamCloudGetDeploymentScopeResponse = DeploymentScopeDataResult; /** Optional parameters. */ export interface TeamCloudUpdateDeploymentScopeOptionalParams extends coreClient.OperationOptions { body?: DeploymentScope; } /** Contains response data for the updateDeploymentScope operation. */ export declare type TeamCloudUpdateDeploymentScopeResponse = DeploymentScopeDataResult; /** Optional parameters. */ export interface TeamCloudDeleteDeploymentScopeOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteDeploymentScope operation. */ export declare type TeamCloudDeleteDeploymentScopeResponse = DeploymentScopeDataResult; /** Optional parameters. */ export interface TeamCloudAuthorizeDeploymentScopeOptionalParams extends coreClient.OperationOptions { body?: DeploymentScope; } /** Contains response data for the authorizeDeploymentScope operation. */ export declare type TeamCloudAuthorizeDeploymentScopeResponse = DeploymentScopeDataResult; /** Optional parameters. */ export interface TeamCloudNegotiateSignalROptionalParams extends coreClient.OperationOptions { } /** Optional parameters. */ export interface TeamCloudGetAuditEntriesOptionalParams extends coreClient.OperationOptions { timeRange?: string; /** Array of Get1ItemsItem */ commands?: string[]; } /** Contains response data for the getAuditEntries operation. */ export declare type TeamCloudGetAuditEntriesResponse = CommandAuditEntityListDataResult; /** Optional parameters. */ export interface TeamCloudGetAuditEntryOptionalParams extends coreClient.OperationOptions { expand?: boolean; } /** Contains response data for the getAuditEntry operation. */ export declare type TeamCloudGetAuditEntryResponse = CommandAuditEntityDataResult; /** Optional parameters. */ export interface TeamCloudGetAuditCommandsOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getAuditCommands operation. */ export declare type TeamCloudGetAuditCommandsResponse = StringListDataResult; /** Optional parameters. */ export interface TeamCloudGetOrganizationsOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getOrganizations operation. */ export declare type TeamCloudGetOrganizationsResponse = OrganizationListDataResult; /** Optional parameters. */ export interface TeamCloudCreateOrganizationOptionalParams extends coreClient.OperationOptions { body?: OrganizationDefinition; } /** Contains response data for the createOrganization operation. */ export declare type TeamCloudCreateOrganizationResponse = OrganizationDataResult; /** Optional parameters. */ export interface TeamCloudGetOrganizationOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getOrganization operation. */ export declare type TeamCloudGetOrganizationResponse = OrganizationDataResult; /** Optional parameters. */ export interface TeamCloudDeleteOrganizationOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteOrganization operation. */ export declare type TeamCloudDeleteOrganizationResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetOrganizationUsersOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getOrganizationUsers operation. */ export declare type TeamCloudGetOrganizationUsersResponse = UserListDataResult; /** Optional parameters. */ export interface TeamCloudCreateOrganizationUserOptionalParams extends coreClient.OperationOptions { body?: UserDefinition; } /** Contains response data for the createOrganizationUser operation. */ export declare type TeamCloudCreateOrganizationUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudGetOrganizationUserOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getOrganizationUser operation. */ export declare type TeamCloudGetOrganizationUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudUpdateOrganizationUserOptionalParams extends coreClient.OperationOptions { body?: User; } /** Contains response data for the updateOrganizationUser operation. */ export declare type TeamCloudUpdateOrganizationUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudDeleteOrganizationUserOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteOrganizationUser operation. */ export declare type TeamCloudDeleteOrganizationUserResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetOrganizationUserMeOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getOrganizationUserMe operation. */ export declare type TeamCloudGetOrganizationUserMeResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudUpdateOrganizationUserMeOptionalParams extends coreClient.OperationOptions { body?: User; } /** Contains response data for the updateOrganizationUserMe operation. */ export declare type TeamCloudUpdateOrganizationUserMeResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectsOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjects operation. */ export declare type TeamCloudGetProjectsResponse = ProjectListDataResult; /** Optional parameters. */ export interface TeamCloudCreateProjectOptionalParams extends coreClient.OperationOptions { body?: ProjectDefinition; } /** Contains response data for the createProject operation. */ export declare type TeamCloudCreateProjectResponse = ProjectDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProject operation. */ export declare type TeamCloudGetProjectResponse = ProjectDataResult; /** Optional parameters. */ export interface TeamCloudDeleteProjectOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteProject operation. */ export declare type TeamCloudDeleteProjectResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetProjectIdentitiesOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectIdentities operation. */ export declare type TeamCloudGetProjectIdentitiesResponse = ProjectIdentityListDataResult; /** Optional parameters. */ export interface TeamCloudCreateProjectIdentityOptionalParams extends coreClient.OperationOptions { body?: ProjectIdentityDefinition; } /** Contains response data for the createProjectIdentity operation. */ export declare type TeamCloudCreateProjectIdentityResponse = ProjectIdentityDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectIdentityOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectIdentity operation. */ export declare type TeamCloudGetProjectIdentityResponse = ProjectIdentityDataResult; /** Optional parameters. */ export interface TeamCloudUpdateProjectIdentityOptionalParams extends coreClient.OperationOptions { body?: ProjectIdentity; } /** Contains response data for the updateProjectIdentity operation. */ export declare type TeamCloudUpdateProjectIdentityResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudDeleteProjectIdentityOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteProjectIdentity operation. */ export declare type TeamCloudDeleteProjectIdentityResponse = ProjectIdentityDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectTagsOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectTags operation. */ export declare type TeamCloudGetProjectTagsResponse = StringDictionaryDataResult; /** Optional parameters. */ export interface TeamCloudCreateProjectTagOptionalParams extends coreClient.OperationOptions { /** Dictionary of <string> */ body?: { [propertyName: string]: string; }; } /** Contains response data for the createProjectTag operation. */ export declare type TeamCloudCreateProjectTagResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudUpdateProjectTagOptionalParams extends coreClient.OperationOptions { /** Dictionary of <string> */ body?: { [propertyName: string]: string; }; } /** Contains response data for the updateProjectTag operation. */ export declare type TeamCloudUpdateProjectTagResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetProjectTagByKeyOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectTagByKey operation. */ export declare type TeamCloudGetProjectTagByKeyResponse = StringDictionaryDataResult; /** Optional parameters. */ export interface TeamCloudDeleteProjectTagOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteProjectTag operation. */ export declare type TeamCloudDeleteProjectTagResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetProjectTemplatesOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectTemplates operation. */ export declare type TeamCloudGetProjectTemplatesResponse = ProjectTemplateListDataResult; /** Optional parameters. */ export interface TeamCloudCreateProjectTemplateOptionalParams extends coreClient.OperationOptions { body?: ProjectTemplateDefinition; } /** Contains response data for the createProjectTemplate operation. */ export declare type TeamCloudCreateProjectTemplateResponse = ProjectTemplateDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectTemplateOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectTemplate operation. */ export declare type TeamCloudGetProjectTemplateResponse = ProjectTemplateDataResult; /** Optional parameters. */ export interface TeamCloudUpdateProjectTemplateOptionalParams extends coreClient.OperationOptions { body?: ProjectTemplate; } /** Contains response data for the updateProjectTemplate operation. */ export declare type TeamCloudUpdateProjectTemplateResponse = ProjectTemplateDataResult; /** Optional parameters. */ export interface TeamCloudDeleteProjectTemplateOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteProjectTemplate operation. */ export declare type TeamCloudDeleteProjectTemplateResponse = ProjectTemplateDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectUsersOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectUsers operation. */ export declare type TeamCloudGetProjectUsersResponse = UserListDataResult; /** Optional parameters. */ export interface TeamCloudCreateProjectUserOptionalParams extends coreClient.OperationOptions { body?: UserDefinition; } /** Contains response data for the createProjectUser operation. */ export declare type TeamCloudCreateProjectUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudGetProjectUserOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectUser operation. */ export declare type TeamCloudGetProjectUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudUpdateProjectUserOptionalParams extends coreClient.OperationOptions { body?: User; } /** Contains response data for the updateProjectUser operation. */ export declare type TeamCloudUpdateProjectUserResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudDeleteProjectUserOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the deleteProjectUser operation. */ export declare type TeamCloudDeleteProjectUserResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetProjectUserMeOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectUserMe operation. */ export declare type TeamCloudGetProjectUserMeResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudUpdateProjectUserMeOptionalParams extends coreClient.OperationOptions { body?: User; } /** Contains response data for the updateProjectUserMe operation. */ export declare type TeamCloudUpdateProjectUserMeResponse = UserDataResult; /** Optional parameters. */ export interface TeamCloudGetSchedulesOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getSchedules operation. */ export declare type TeamCloudGetSchedulesResponse = ScheduleListDataResult; /** Optional parameters. */ export interface TeamCloudCreateScheduleOptionalParams extends coreClient.OperationOptions { body?: ScheduleDefinition; } /** Contains response data for the createSchedule operation. */ export declare type TeamCloudCreateScheduleResponse = ScheduleDataResult; /** Optional parameters. */ export interface TeamCloudGetScheduleOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getSchedule operation. */ export declare type TeamCloudGetScheduleResponse = ScheduleDataResult; /** Optional parameters. */ export interface TeamCloudUpdateScheduleOptionalParams extends coreClient.OperationOptions { body?: Schedule; } /** Contains response data for the updateSchedule operation. */ export declare type TeamCloudUpdateScheduleResponse = ScheduleDataResult; /** Optional parameters. */ export interface TeamCloudRunScheduleOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the runSchedule operation. */ export declare type TeamCloudRunScheduleResponse = ScheduleDataResult; /** Optional parameters. */ export interface TeamCloudGetStatusOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getStatus operation. */ export declare type TeamCloudGetStatusResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetProjectStatusOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getProjectStatus operation. */ export declare type TeamCloudGetProjectStatusResponse = StatusResult; /** Optional parameters. */ export interface TeamCloudGetUserProjectsOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getUserProjects operation. */ export declare type TeamCloudGetUserProjectsResponse = ProjectListDataResult; /** Optional parameters. */ export interface TeamCloudGetUserProjectsMeOptionalParams extends coreClient.OperationOptions { } /** Contains response data for the getUserProjectsMe operation. */ export declare type TeamCloudGetUserProjectsMeResponse = ProjectListDataResult; /** Optional parameters. */ export interface TeamCloudOptionalParams extends coreClient.ServiceClientOptions { /** Overrides client endpoint. */ endpoint?: string; } //# sourceMappingURL=index.d.ts.map
the_stack
import { BlockDocunment, BlockGraphDocunment, BlockGraphVariable } from "../Define/BlockDocunment"; import { BlockPortRegData, BlockRegData } from "../Define/BlockDef"; import { BlockEditor } from "../Editor/BlockEditor"; import BlockServiceInstance from "../../sevices/BlockService"; import StringUtils from "../../utils/StringUtils"; import { BlockPort } from "../Define/Port"; import { ConnectorEditor } from "../Editor/ConnectorEditor"; import { Block } from "../Define/Block"; import { BlockPortEditor } from "../Editor/BlockPortEditor"; import { BlockParameterType, BlockParameterSetType, createParameterTypeFromString } from "../Define/BlockParameterType"; import CommonUtils from "../../utils/CommonUtils"; import { Rect } from "../Rect"; import logger from "@/utils/Logger"; interface BlockFileDocData { name: string, libVersion: number, openEditorVersion: number, mainGraph: any, uid: string, blockMap: string[], portMap: any[], } interface BlockFileGraphData { name: string, uid: string, viewPort: Rect, scale: number, childGraphs: BlockFileGraphData[], comment: string, inputPorts: BlockPortRegData[], outputPorts: BlockPortRegData[], variables: any[], blocks: any[], ports: any[], connectors: any[], boxs: any[], comments: string[], } /** * 流图保存加载解析器 */ export class BlockFileParser { /** * 保存图表 * @param graph 图表 * @param docData 图表数据 * @param saveToEditor 是否是编辑器保存版本 */ private saveGraph(graph : BlockGraphDocunment, docData : { blockMap: Array<any>, portMap: Array<any>, }, saveToEditor : boolean) { let data : BlockFileGraphData = { name: graph.name, uid: graph.uid, viewPort: graph.viewPort, scale: graph.scale, childGraphs: [], comment: graph.comment, inputPorts: [], outputPorts: [], variables: [], blocks: [], ports: [], connectors: [], boxs: [], comments: graph.comments, }; let findBlockGUIDMap = function(guid : string) { for(let i = 0, c = docData.blockMap.length; i < c; i++) if(docData.blockMap[i] == guid) return i; return -1; }; let findPortGUIDMap = function(guid : string) { for(let i = 0, c = docData.portMap.length; i < c; i++) if(docData.portMap[i].guid == guid) return [i,docData.portMap[i]]; return [-1,null]; }; let findBlockIndex = function(uid : string) { for(let i = 0, c = data.blocks.length; i < c; i++) if(data.blocks[i].uid == uid) return i; return -1; }; //写入单元 graph.blocks.forEach(block => { let mapIndex = findBlockGUIDMap(block.guid); if(mapIndex == -1) mapIndex = docData.blockMap.push(block.guid) - 1; //让单元保存自定义数据 if(saveToEditor && typeof (<BlockEditor>block).onSave == 'function') (<BlockEditor>block).onSave(<BlockEditor>block); let blockData = { guidMap: mapIndex, uid: block.uid, mark: saveToEditor ? (<BlockEditor>block).mark : undefined, markOpen: saveToEditor ? (<BlockEditor>block).markOpen : undefined, breakpoint: saveToEditor ? block.breakpoint : undefined, options: block.options, position: saveToEditor ? (<BlockEditor>block).position : undefined, size: saveToEditor && block.userCanResize ? (<BlockEditor>block).size : undefined, }; let blocksIndex = data.blocks.push(blockData) - 1; //写入入参数 for(let i = 0, keys = Object.keys(block.inputPorts), c = keys.length; i < c; i++) { let port : BlockPort = block.inputPorts[keys[i]]; let portData = findPortGUIDMap(block.guid + '-' + port.guid); if(portData[0] == -1) portData[0] = docData.portMap.push({ guid: block.guid + '-' + port.guid, regData: port.isDyamicAdd || port.paramType.isExecute() ? port.regData : undefined, }) - 1; if(!port.paramType.isExecute()) data.ports.push({ blockMap: blocksIndex, guidMap: portData[0], dyamicAdd: port.isDyamicAdd, direction: 'input', options: port.options, value: port.paramUserSetValue, type: port.paramType, }) } //写入出参数 for(let i = 0, keys = Object.keys(block.outputPorts), c = keys.length; i < c; i++) { let port : BlockPort = block.outputPorts[keys[i]]; let portData = findPortGUIDMap(block.guid + '-' + port.guid); if(portData[0] == -1) portData[0] = docData.portMap.push({ guid: block.guid + '-' + port.guid, regData: port.isDyamicAdd || port.paramType.isExecute() ? port.regData : undefined, }) - 1; if(!port.paramType.isExecute()) data.ports.push({ blockMap: blocksIndex, guidMap: portData[0], dyamicAdd: port.isDyamicAdd, direction: 'output', options: port.options, value: port.paramUserSetValue, type: port.paramType.getType(), }) } }); //写入链接 graph.connectors.forEach(connector => { data.connectors.push({ startBlock: findBlockIndex(connector.startPort.parent.uid), startPort: connector.startPort.guid, endBlock: findBlockIndex(connector.endPort.parent.uid), endPort: connector.endPort.guid, flexableCoonIndex: saveToEditor ? (<ConnectorEditor>connector).flexableCoonIndex : 0, }); }); //写入变量 graph.variables.forEach(variable => { data.variables.push({ defaultValue: variable.defaultValue, value: variable.value, name: variable.name, type: variable.type.getType(), setType: variable.setType, dictionaryKeyType: variable.dictionaryKeyType, }); }); if(saveToEditor) { } //写入图表的输入输出接口 graph.inputPorts.forEach((p) => { let port = CommonUtils.clone(p); port.paramType = p.paramType.toString(); if(CommonUtils.isDefinedAndNotNull(p.paramDictionaryKeyType)) port.paramDictionaryKeyType = p.paramDictionaryKeyType.toString(); else port.paramDictionaryKeyType = 'any'; data.inputPorts.push(port); }); graph.outputPorts.forEach((p) => { let port = CommonUtils.clone(p); port.paramType = p.paramType.toString(); if(CommonUtils.isDefinedAndNotNull(p.paramDictionaryKeyType)) port.paramDictionaryKeyType = p.paramDictionaryKeyType.toString(); else port.paramDictionaryKeyType = 'any'; data.outputPorts.push(port); }); //递归保存子图表 graph.children.forEach((childGraph) => data.childGraphs.push(this.saveGraph(childGraph, docData, saveToEditor)) ); return data; } /** * 加载图表 * @param graphData 数据 * @param parentGraph 父图表 * @param blockRegDatas block GUID map * @param portRegDatas port GUID map * @param readToEditor 是否是读取至编辑器 * @param doc 所属文档 */ private loadGraph(graphData : BlockFileGraphData, parentGraph : BlockGraphDocunment, blockRegDatas : Array<BlockRegData>, portRegDatas : any[], readToEditor : boolean, doc : BlockDocunment) { let graph = new BlockGraphDocunment() graph.name = graphData.name; graph.viewPort = graphData.viewPort; graph.scale = graphData.scale; graph.comments = graphData.comments; graph.children = []; graph.blocks = []; graph.connectors = []; graph.isEditor = readToEditor; graph.parent = parentGraph; graph.comment = graphData.comment; graph.inputPorts = graphData.inputPorts; graph.outputPorts = graphData.outputPorts; graph.variables = []; graph.isMainGraph = false; graph.docunment = doc; graph.uid = graphData.uid || CommonUtils.genNonDuplicateIDHEX(16); //递归加载子图表 graphData.childGraphs.forEach(childGraph => { graph.children.push(this.loadGraph(childGraph, graph, blockRegDatas, portRegDatas, readToEditor, doc)); }); //加载变量 graphData.variables.forEach(variable => { let v = new BlockGraphVariable(); v.defaultValue = variable.defaultValue; v.value = variable.value; v.name = variable.name; v.type = createParameterTypeFromString(variable.type); v.setType = <BlockParameterSetType>variable.setType; v.dictionaryKeyType = variable.dictionaryKeyType; graph.variables.push(v); }); //加载单元 graphData.blocks.forEach(block => { let blockInstance = readToEditor ? new BlockEditor(blockRegDatas[block.guidMap]) : new Block(blockRegDatas[block.guidMap]); blockInstance.uid = block.uid; blockInstance.breakpoint = block.breakpoint; blockInstance.currentGraph = graph; blockInstance.options = block.options; blockInstance.createBase(); if(readToEditor) { if(blockInstance.userCanResize) (<BlockEditor>blockInstance).size.Set(block.size); (<BlockEditor>blockInstance).position.Set(block.position); (<BlockEditor>blockInstance).mark = block.mark; (<BlockEditor>blockInstance).markOpen = block.markOpen; } graph.blocks.push(blockInstance); }); //加载单元接口 graphData.ports.forEach(port => { if(port.type == 'execute') graph.blocks[port.blockMap].addPort(portRegDatas[port.guidMap].regData, true); else { let paramPort : BlockPort = null; if(port.dyamicAdd) paramPort = graph.blocks[port.blockMap].addPort(portRegDatas[port.guidMap].regData, true, port.value); else { paramPort = graph.blocks[port.blockMap].getPort(portRegDatas[port.guidMap].guid.substr(37)); if(paramPort != null) paramPort.paramUserSetValue = port.value; } if(paramPort != null) { paramPort.paramUserSetValue = port.value; paramPort.options = port.options; } } }); graph.inputPorts = []; graphData.inputPorts.forEach((p) => { p.paramType = createParameterTypeFromString(p.paramType as string); p.paramDictionaryKeyType = createParameterTypeFromString(p.paramDictionaryKeyType as string); graph.inputPorts.push(p); }); graph.outputPorts = []; graphData.outputPorts.forEach((p) => { p.paramType = createParameterTypeFromString(p.paramType as string); p.paramDictionaryKeyType = createParameterTypeFromString(p.paramDictionaryKeyType as string); graph.outputPorts.push(p); }); //加载单元链接 graphData.connectors.forEach(connector => { let startPort = graph.blocks[connector.startBlock].getPortByGUID(connector.startPort); let endPort = graph.blocks[connector.endBlock].getPortByGUID(connector.endPort); let c = new ConnectorEditor(); c.startPort = <BlockPortEditor>startPort; c.endPort = <BlockPortEditor>endPort; if(startPort != null && endPort != null){ if(readToEditor) { c.flexableCoonIndex = connector.flexableCoonIndex; graph.connectors.push(c); }else { graph.connectors.push(c); } } }); return graph; } /** * 保存流图文档至字符串 * @param doc 流图文档 * @param saveToEditor 是否保存编辑器信息为编辑器版本,否则为运行版本 * @returns 已保存的字符串 */ public saveToString(doc : BlockDocunment, saveToEditor : boolean) { let data : BlockFileDocData = { name: doc.name, libVersion: doc.libVersion, openEditorVersion: doc.openEditorVersion, mainGraph: null, uid: doc.uid, blockMap: [], portMap: [], }; data.mainGraph = this.saveGraph(doc.mainGraph, data, saveToEditor); return JSON.stringify(data); } /** * 从字符串加载流图文档 * @param str 字符串 * @param doc 目标流图文档 * @param readToEditor 是否加载编辑器信息 */ public loadFromString(str : string, doc : BlockDocunment, readToEditor : boolean) { if(StringUtils.isNullOrEmpty(str)) { logger.log('loadFromString', 'invalid string!'); return -1; } let blockRegDatas : Array<BlockRegData> = []; let portRegDatas : Array<any> = []; let data : BlockFileDocData = null; try { data = JSON.parse(str); } catch(e) { logger.log('loadFromString', 'invalid file!'); return -2; } doc.uid = data.uid; doc.libVersion = data.libVersion; doc.openEditorVersion = data.openEditorVersion; doc.name = data.name; doc.isEditor = readToEditor; //block GUID map data.blockMap.forEach(guid => blockRegDatas.push(BlockServiceInstance.getRegisteredBlock(guid))); //port GUID map data.portMap.forEach(port => portRegDatas.push(port)); //load Graph doc.mainGraph = this.loadGraph(data.mainGraph, null, blockRegDatas, portRegDatas, readToEditor, doc); doc.mainGraph.isMainGraph = true; return doc; } }
the_stack
import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; import type * as Platform from '../../core/platform/platform.js'; import * as ARIAUtils from './ARIAUtils.js'; import {AnchorBehavior, GlassPane, MarginBehavior, PointerEventsBehavior, SizeBehavior} from './GlassPane.js'; import {Icon} from './Icon.js'; import * as ThemeSupport from './theme_support/theme_support.js'; // eslint-disable-line rulesdir/es_modules_import import {createTextChild, ElementFocusRestorer} from './UIUtils.js'; const UIStrings = { /** *@description Text exposed to screen readers on checked items. */ checked: 'checked', /** *@description Accessible text exposed to screen readers when the screen reader encounters an unchecked checkbox. */ unchecked: 'unchecked', /** *@description Accessibility label for checkable SoftContextMenuItems with shortcuts *@example {Open File} PH1 *@example {Ctrl + P} PH2 *@example {checked} PH3 */ sSS: '{PH1}, {PH2}, {PH3}', /** *@description Generic text with two placeholders separated by a comma *@example {1 613 680} PH1 *@example {44 %} PH2 */ sS: '{PH1}, {PH2}', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/SoftContextMenu.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class SoftContextMenu { private items: SoftContextMenuDescriptor[]; private itemSelectedCallback: (arg0: number) => void; private parentMenu: SoftContextMenu|undefined; private highlightedMenuItemElement: HTMLElement|null; detailsForElementMap: WeakMap<HTMLElement, ElementMenuDetails>; private document?: Document; private glassPane?: GlassPane; private contextMenuElement?: HTMLElement; private focusRestorer?: ElementFocusRestorer; private hideOnUserGesture?: ((event: Event) => void); private activeSubMenuElement?: HTMLElement; private subMenu?: SoftContextMenu; constructor( items: SoftContextMenuDescriptor[], itemSelectedCallback: (arg0: number) => void, parentMenu?: SoftContextMenu) { this.items = items; this.itemSelectedCallback = itemSelectedCallback; this.parentMenu = parentMenu; this.highlightedMenuItemElement = null; this.detailsForElementMap = new WeakMap(); } show(document: Document, anchorBox: AnchorBox): void { if (!this.items.length) { return; } this.document = document; this.glassPane = new GlassPane(); this.glassPane.setPointerEventsBehavior( this.parentMenu ? PointerEventsBehavior.PierceGlassPane : PointerEventsBehavior.BlockedByGlassPane); this.glassPane.registerRequiredCSS('ui/legacy/softContextMenu.css'); this.glassPane.setContentAnchorBox(anchorBox); this.glassPane.setSizeBehavior(SizeBehavior.MeasureContent); this.glassPane.setMarginBehavior(MarginBehavior.NoMargin); this.glassPane.setAnchorBehavior(this.parentMenu ? AnchorBehavior.PreferRight : AnchorBehavior.PreferBottom); this.contextMenuElement = this.glassPane.contentElement.createChild('div', 'soft-context-menu'); this.contextMenuElement.tabIndex = -1; ARIAUtils.markAsMenu(this.contextMenuElement); this.contextMenuElement.addEventListener('mouseup', e => e.consume(), false); this.contextMenuElement.addEventListener('keydown', this.menuKeyDown.bind(this), false); for (let i = 0; i < this.items.length; ++i) { this.contextMenuElement.appendChild(this.createMenuItem(this.items[i])); } this.glassPane.show(document); this.focusRestorer = new ElementFocusRestorer(this.contextMenuElement); if (!this.parentMenu) { this.hideOnUserGesture = (event: Event): void => { // If a user clicks on any submenu, prevent the menu system from closing. let subMenu: (SoftContextMenu|undefined) = this.subMenu; while (subMenu) { if (subMenu.contextMenuElement === event.composedPath()[0]) { return; } subMenu = subMenu.subMenu; } this.discard(); event.consume(true); }; this.document.body.addEventListener('mousedown', this.hideOnUserGesture, false); if (this.document.defaultView) { this.document.defaultView.addEventListener('resize', this.hideOnUserGesture, false); } } } discard(): void { if (this.subMenu) { this.subMenu.discard(); } if (this.focusRestorer) { this.focusRestorer.restore(); } if (this.glassPane) { this.glassPane.hide(); delete this.glassPane; if (this.hideOnUserGesture) { if (this.document) { this.document.body.removeEventListener('mousedown', this.hideOnUserGesture, false); if (this.document.defaultView) { this.document.defaultView.removeEventListener('resize', this.hideOnUserGesture, false); } } delete this.hideOnUserGesture; } } if (this.parentMenu) { delete this.parentMenu.subMenu; if (this.parentMenu.activeSubMenuElement) { ARIAUtils.setExpanded(this.parentMenu.activeSubMenuElement, false); delete this.parentMenu.activeSubMenuElement; } } } private createMenuItem(item: SoftContextMenuDescriptor): HTMLElement { if (item.type === 'separator') { return this.createSeparator(); } if (item.type === 'subMenu') { return this.createSubMenu(item); } const menuItemElement = document.createElement('div'); menuItemElement.classList.add('soft-context-menu-item'); menuItemElement.tabIndex = -1; ARIAUtils.markAsMenuItem(menuItemElement); const checkMarkElement = Icon.create('smallicon-checkmark', 'checkmark'); menuItemElement.appendChild(checkMarkElement); if (!item.checked) { checkMarkElement.style.opacity = '0'; } const detailsForElement: ElementMenuDetails = { actionId: undefined, isSeparator: undefined, customElement: undefined, subItems: undefined, subMenuTimer: undefined, }; if (item.element) { const wrapper = menuItemElement.createChild('div', 'soft-context-menu-custom-item'); wrapper.appendChild(item.element); detailsForElement.customElement = (item.element as HTMLElement); this.detailsForElementMap.set(menuItemElement, detailsForElement); return menuItemElement; } if (!item.enabled) { menuItemElement.classList.add('soft-context-menu-disabled'); } createTextChild(menuItemElement, item.label || ''); menuItemElement.createChild('span', 'soft-context-menu-shortcut').textContent = item.shortcut || ''; menuItemElement.addEventListener('mousedown', this.menuItemMouseDown.bind(this), false); menuItemElement.addEventListener('mouseup', this.menuItemMouseUp.bind(this), false); // Manually manage hover highlight since :hover does not work in case of click-and-hold menu invocation. menuItemElement.addEventListener('mouseover', this.menuItemMouseOver.bind(this), false); menuItemElement.addEventListener('mouseleave', (this.menuItemMouseLeave.bind(this) as EventListener), false); detailsForElement.actionId = item.id; let accessibleName: Platform.UIString.LocalizedString|string = item.label || ''; if (item.type === 'checkbox') { const checkedState = item.checked ? i18nString(UIStrings.checked) : i18nString(UIStrings.unchecked); if (item.shortcut) { accessibleName = i18nString(UIStrings.sSS, {PH1: String(item.label), PH2: item.shortcut, PH3: checkedState}); } else { accessibleName = i18nString(UIStrings.sS, {PH1: String(item.label), PH2: checkedState}); } } else if (item.shortcut) { accessibleName = i18nString(UIStrings.sS, {PH1: String(item.label), PH2: item.shortcut}); } ARIAUtils.setAccessibleName(menuItemElement, accessibleName); this.detailsForElementMap.set(menuItemElement, detailsForElement); return menuItemElement; } private createSubMenu(item: SoftContextMenuDescriptor): HTMLElement { const menuItemElement = document.createElement('div'); menuItemElement.classList.add('soft-context-menu-item'); menuItemElement.tabIndex = -1; ARIAUtils.markAsMenuItemSubMenu(menuItemElement); this.detailsForElementMap.set(menuItemElement, { subItems: item.subItems, actionId: undefined, isSeparator: undefined, customElement: undefined, subMenuTimer: undefined, }); // Occupy the same space on the left in all items. const checkMarkElement = Icon.create('smallicon-checkmark', 'soft-context-menu-item-checkmark'); checkMarkElement.classList.add('checkmark'); menuItemElement.appendChild(checkMarkElement); checkMarkElement.style.opacity = '0'; createTextChild(menuItemElement, item.label || ''); ARIAUtils.setExpanded(menuItemElement, false); // TODO: Consider removing this branch and use the same icon on all platforms. if (Host.Platform.isMac() && !ThemeSupport.ThemeSupport.instance().hasTheme()) { const subMenuArrowElement = menuItemElement.createChild('span', 'soft-context-menu-item-submenu-arrow'); ARIAUtils.markAsHidden(subMenuArrowElement); subMenuArrowElement.textContent = '\u25B6'; // BLACK RIGHT-POINTING TRIANGLE } else { const subMenuArrowElement = Icon.create('smallicon-triangle-right', 'soft-context-menu-item-submenu-arrow'); menuItemElement.appendChild(subMenuArrowElement); } menuItemElement.addEventListener('mousedown', this.menuItemMouseDown.bind(this), false); menuItemElement.addEventListener('mouseup', this.menuItemMouseUp.bind(this), false); // Manually manage hover highlight since :hover does not work in case of click-and-hold menu invocation. menuItemElement.addEventListener('mouseover', this.menuItemMouseOver.bind(this), false); menuItemElement.addEventListener('mouseleave', (this.menuItemMouseLeave.bind(this) as EventListener), false); return menuItemElement; } private createSeparator(): HTMLElement { const separatorElement = document.createElement('div'); separatorElement.classList.add('soft-context-menu-separator'); this.detailsForElementMap.set(separatorElement, { subItems: undefined, actionId: undefined, isSeparator: true, customElement: undefined, subMenuTimer: undefined, }); separatorElement.createChild('div', 'separator-line'); return separatorElement; } private menuItemMouseDown(event: Event): void { // Do not let separator's mouse down hit menu's handler - we need to receive mouse up! event.consume(true); } private menuItemMouseUp(event: Event): void { this.triggerAction((event.target as HTMLElement), event); event.consume(); } private root(): SoftContextMenu { let root: SoftContextMenu = (this as SoftContextMenu); while (root.parentMenu) { root = root.parentMenu; } return root; } private triggerAction(menuItemElement: HTMLElement, event: Event): void { const detailsForElement = this.detailsForElementMap.get(menuItemElement); if (detailsForElement) { if (!detailsForElement.subItems) { this.root().discard(); event.consume(true); if (typeof detailsForElement.actionId !== 'undefined') { this.itemSelectedCallback(detailsForElement.actionId); delete detailsForElement.actionId; } return; } } this.showSubMenu(menuItemElement); event.consume(); } private showSubMenu(menuItemElement: HTMLElement): void { const detailsForElement = this.detailsForElementMap.get(menuItemElement); if (!detailsForElement) { return; } if (detailsForElement.subMenuTimer) { window.clearTimeout(detailsForElement.subMenuTimer); delete detailsForElement.subMenuTimer; } if (this.subMenu || !this.document) { return; } this.activeSubMenuElement = menuItemElement; ARIAUtils.setExpanded(menuItemElement, true); if (!detailsForElement.subItems) { return; } this.subMenu = new SoftContextMenu(detailsForElement.subItems, this.itemSelectedCallback, this); const anchorBox = menuItemElement.boxInWindow(); // Adjust for padding. anchorBox.y -= 5; anchorBox.x += 3; anchorBox.width -= 6; anchorBox.height += 10; this.subMenu.show(this.document, anchorBox); } private menuItemMouseOver(event: Event): void { this.highlightMenuItem((event.target as HTMLElement), true); } private menuItemMouseLeave(event: MouseEvent): void { if (!this.subMenu || !event.relatedTarget) { this.highlightMenuItem(null, true); return; } const relatedTarget = event.relatedTarget; if (relatedTarget === this.contextMenuElement) { this.highlightMenuItem(null, true); } } private highlightMenuItem(menuItemElement: HTMLElement|null, scheduleSubMenu: boolean): void { if (this.highlightedMenuItemElement === menuItemElement) { return; } if (this.subMenu) { this.subMenu.discard(); } if (this.highlightedMenuItemElement) { const detailsForElement = this.detailsForElementMap.get(this.highlightedMenuItemElement); this.highlightedMenuItemElement.classList.remove('force-white-icons'); this.highlightedMenuItemElement.classList.remove('soft-context-menu-item-mouse-over'); if (detailsForElement && detailsForElement.subItems && detailsForElement.subMenuTimer) { window.clearTimeout(detailsForElement.subMenuTimer); delete detailsForElement.subMenuTimer; } } this.highlightedMenuItemElement = menuItemElement; if (this.highlightedMenuItemElement) { if (ThemeSupport.ThemeSupport.instance().hasTheme() || Host.Platform.isMac()) { this.highlightedMenuItemElement.classList.add('force-white-icons'); } this.highlightedMenuItemElement.classList.add('soft-context-menu-item-mouse-over'); const detailsForElement = this.detailsForElementMap.get(this.highlightedMenuItemElement); if (detailsForElement && detailsForElement.customElement) { detailsForElement.customElement.focus(); } else { this.highlightedMenuItemElement.focus(); } if (scheduleSubMenu && detailsForElement && detailsForElement.subItems && !detailsForElement.subMenuTimer) { detailsForElement.subMenuTimer = window.setTimeout(this.showSubMenu.bind(this, this.highlightedMenuItemElement), 150); } } } private highlightPrevious(): void { let menuItemElement: (ChildNode|null) = this.highlightedMenuItemElement ? this.highlightedMenuItemElement.previousSibling : this.contextMenuElement ? this.contextMenuElement.lastChild : null; let menuItemDetails: (ElementMenuDetails|undefined) = menuItemElement ? this.detailsForElementMap.get((menuItemElement as HTMLElement)) : undefined; while (menuItemElement && menuItemDetails && (menuItemDetails.isSeparator || (menuItemElement as HTMLElement).classList.contains('soft-context-menu-disabled'))) { menuItemElement = menuItemElement.previousSibling; menuItemDetails = menuItemElement ? this.detailsForElementMap.get((menuItemElement as HTMLElement)) : undefined; } if (menuItemElement) { this.highlightMenuItem((menuItemElement as HTMLElement), false); } } private highlightNext(): void { let menuItemElement: (ChildNode|null) = this.highlightedMenuItemElement ? this.highlightedMenuItemElement.nextSibling : this.contextMenuElement ? this.contextMenuElement.firstChild : null; let menuItemDetails: (ElementMenuDetails|undefined) = menuItemElement ? this.detailsForElementMap.get((menuItemElement as HTMLElement)) : undefined; while (menuItemElement && (menuItemDetails && menuItemDetails.isSeparator || (menuItemElement as HTMLElement).classList.contains('soft-context-menu-disabled'))) { menuItemElement = menuItemElement.nextSibling; menuItemDetails = menuItemElement ? this.detailsForElementMap.get((menuItemElement as HTMLElement)) : undefined; } if (menuItemElement) { this.highlightMenuItem((menuItemElement as HTMLElement), false); } } private menuKeyDown(event: Event): void { const keyboardEvent = (event as KeyboardEvent); function onEnterOrSpace(this: SoftContextMenu): void { if (!this.highlightedMenuItemElement) { return; } const detailsForElement = this.detailsForElementMap.get(this.highlightedMenuItemElement); if (!detailsForElement || detailsForElement.customElement) { // The custom element will handle the event, so return early and do not consume it. return; } this.triggerAction(this.highlightedMenuItemElement, keyboardEvent); if (detailsForElement.subItems && this.subMenu) { this.subMenu.highlightNext(); } keyboardEvent.consume(true); } switch (keyboardEvent.key) { case 'ArrowUp': this.highlightPrevious(); keyboardEvent.consume(true); break; case 'ArrowDown': this.highlightNext(); keyboardEvent.consume(true); break; case 'ArrowLeft': if (this.parentMenu) { this.highlightMenuItem(null, false); this.discard(); } keyboardEvent.consume(true); break; case 'ArrowRight': { if (!this.highlightedMenuItemElement) { break; } const detailsForElement = this.detailsForElementMap.get(this.highlightedMenuItemElement); if (detailsForElement && detailsForElement.subItems) { this.showSubMenu(this.highlightedMenuItemElement); if (this.subMenu) { this.subMenu.highlightNext(); } } keyboardEvent.consume(true); break; } case 'Escape': this.discard(); keyboardEvent.consume(true); break; /** * Important: we don't consume the event by default for `Enter` or `Space` * key events, as if there's a custom sub menu we pass the event onto * that. */ case 'Enter': if (!(keyboardEvent.key === 'Enter')) { return; } onEnterOrSpace.call(this); break; case ' ': onEnterOrSpace.call(this); break; default: keyboardEvent.consume(true); } } } export interface SoftContextMenuDescriptor { type: string; id?: number; label?: string; enabled?: boolean; checked?: boolean; subItems?: SoftContextMenuDescriptor[]; element?: Element; shortcut?: string; } interface ElementMenuDetails { customElement?: HTMLElement; isSeparator?: boolean; subMenuTimer?: number; subItems?: SoftContextMenuDescriptor[]; actionId?: number; }
the_stack
import { ForceIgnore } from '@salesforce/source-deploy-retrieve/lib/src/metadata-registry/forceIgnore'; import { AsyncCreatable } from '@salesforce/kit'; import { Logger, SfdxProject } from '@salesforce/core'; import MetadataRegistry = require('./metadataRegistry'); import { WorkspaceFileState } from './workspaceFileState'; import { AggregateSourceElement } from './aggregateSourceElement'; import { MetadataTypeFactory } from './metadataTypeFactory'; import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter'; import { RemoteSourceTrackingService, ChangeElement } from './remoteSourceTrackingService'; export class SrcStatusApi extends AsyncCreatable<SrcStatusApi.Options> { public scratchOrg: any; public force: any; public swa: SourceWorkspaceAdapter; public remoteSourceTrackingService: RemoteSourceTrackingService; public locallyChangedWorkspaceElements: any[]; public localChanges: any[]; public remoteChanges: any[]; public forceIgnore: any; private logger!: Logger; public constructor(options: SrcStatusApi.Options) { super(options); this.scratchOrg = options.org; this.force = this.scratchOrg.force; this.swa = options.adapter; this.locallyChangedWorkspaceElements = []; this.localChanges = []; this.remoteChanges = []; this.forceIgnore = ForceIgnore.findAndCreate(SfdxProject.resolveProjectPathSync()); } protected async init(): Promise<void> { this.logger = await Logger.child(this.constructor.name); this.remoteSourceTrackingService = await RemoteSourceTrackingService.getInstance({ username: this.scratchOrg.name, }); if (!this.swa) { const options: SourceWorkspaceAdapter.Options = { org: this.scratchOrg, metadataRegistryImpl: MetadataRegistry, defaultPackagePath: this.force.getConfig().getAppConfig().defaultPackagePath, }; this.swa = await SourceWorkspaceAdapter.create(options); } } async doStatus(options): Promise<void | any[]> { this.populateLocalChanges(options); await this.populateServerChanges(options); return this.markConflicts(options); } private populateLocalChanges(options) { if (!options.local) { return []; } const localSourceElementsMapByPkg = this.swa.changedSourceElementsCache; return localSourceElementsMapByPkg.forEach((localSourceElementsMap) => localSourceElementsMap.forEach((value) => { value.getWorkspaceElements().forEach((workspaceElement) => { value.validateIfDeletedWorkspaceElement(workspaceElement); if (options.local && !options.remote) { this.localChanges.push(workspaceElement.toObject()); } else { // if we want to find source conflicts between the workspace and the server, // then pass along the locally changed workspace elements and // populate this.localChanges during the _markConflicts() step this.locallyChangedWorkspaceElements.push(workspaceElement); } }); }) ); } // Retrieve metadata CRUD changes from the org, filtering any forceignored metadata, // then assign remote changes for conflict detection and status reporting. private async populateServerChanges(options) { if (!options.remote) { return []; } // Returns false when a changeElement matches a forceignore rule const forceIgnoreAllows = (changeElement: ChangeElement) => { const sourceMemberMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( changeElement.type, this.swa.metadataRegistry ); // if user wants to ignore a permissionset with fullname abc then we check if forceignore denies abc.permissionset if (sourceMemberMetadataType) { const fullName = sourceMemberMetadataType.getAggregateFullNameFromSourceMemberName(changeElement.name); const filename = `${fullName}.${sourceMemberMetadataType.getExt()}`; return this.forceIgnore.accepts(filename); } return true; }; const changeElements = await this.remoteSourceTrackingService.retrieveUpdates(); // Create an array of remote changes from the retrieved updates for (const changeElement of changeElements) { if (forceIgnoreAllows(changeElement)) { const remoteChange = await this.createRemoteChangeElements(changeElement); this.remoteChanges = [...this.remoteChanges, ...remoteChange]; } } } private async createRemoteChangeElements(changeElement: ChangeElement) { const remoteChangeElements = []; const sourceMemberMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( changeElement.type, this.swa.metadataRegistry ); if (sourceMemberMetadataType) { if (sourceMemberMetadataType.trackRemoteChangeForSourceMemberName(changeElement.name)) { const correspondingWorkspaceElements = await this.getCorrespondingWorkspaceElements( changeElement, sourceMemberMetadataType ); const state = this.getRemoteChangeState(changeElement, correspondingWorkspaceElements); const metadataType = sourceMemberMetadataType.getMetadataName(); if (this.swa.metadataRegistry.isSupported(metadataType)) { if ( correspondingWorkspaceElements && correspondingWorkspaceElements.length > 0 && !sourceMemberMetadataType.displayAggregateRemoteChangesOnly() ) { correspondingWorkspaceElements.forEach((workspaceElement) => { const remoteChangeElement = { state, fullName: workspaceElement.getFullName(), type: sourceMemberMetadataType.getDisplayNameForRemoteChange(changeElement.type), filePath: workspaceElement.getSourcePath(), }; remoteChangeElements.push(remoteChangeElement); }); } else { if (state !== WorkspaceFileState.DELETED) { const remoteChangeElement = { state, fullName: changeElement.name, type: sourceMemberMetadataType.getDisplayNameForRemoteChange(changeElement.type), }; remoteChangeElements.push(remoteChangeElement); } else { this.logger.debug( `${changeElement.type}.${changeElement.name} was not locally tracked but deleted in the org.` ); } } } } } return remoteChangeElements; } private getRemoteChangeState(changeElement: ChangeElement, correspondingLocalWorkspaceElements) { if (changeElement.deleted) { return WorkspaceFileState.DELETED; } else if (correspondingLocalWorkspaceElements && correspondingLocalWorkspaceElements.length > 0) { return WorkspaceFileState.CHANGED; } else { return WorkspaceFileState.NEW; } } private async getCorrespondingWorkspaceElements(changeElement: ChangeElement, sourceMemberMetadataType) { const allLocalAggregateElements = await this.swa.getAggregateSourceElements(false); if (!allLocalAggregateElements.isEmpty()) { if (sourceMemberMetadataType) { const aggregateFullName = sourceMemberMetadataType.getAggregateFullNameFromSourceMemberName(changeElement.name); const aggregateMetadataName = sourceMemberMetadataType.getAggregateMetadataName(); const key = AggregateSourceElement.getKeyFromMetadataNameAndFullName(aggregateMetadataName, aggregateFullName); const fileLocation = this.swa.sourceLocations.getFilePath(aggregateMetadataName, changeElement.name); // if we cannot find an existing fileLocation, it means that the SourceMember has been deleted or the metadata // hasn't been retrieved from the org yet. if (!fileLocation) { this.logger.debug( `getCorrespondingWorkspaceElements: Did not find any existing source files for member ${changeElement.name}. Returning empty array...` ); return []; } const pkgName = SfdxProject.getInstance().getPackageNameFromPath(fileLocation); const localAggregateSourceElement = allLocalAggregateElements.getSourceElement(pkgName, key); if (localAggregateSourceElement) { const workspaceElements = localAggregateSourceElement.getWorkspaceElements(); if (workspaceElements.length > 0) { return workspaceElements.filter((workspaceElement) => { const workspaceElementMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( workspaceElement.getMetadataName(), this.swa.metadataRegistry ); return ( workspaceElementMetadataType.sourceMemberFullNameCorrespondsWithWorkspaceFullName( changeElement.name, workspaceElement.getFullName() ) || workspaceElementMetadataType.sourceMemberFullNameCorrespondsWithWorkspaceFullName( `${changeElement.type}s`, // for nonDecomposedTypesWithChildrenMetadataTypes we need to check their type workspaceElement.getFullName() ) ); }); } } } } return []; } private markConflicts(options) { if (options.local && options.remote) { return this.locallyChangedWorkspaceElements.forEach((workspaceElement) => { // a metadata element with same name and type modified both locally and in the server is considered a conflict const localChange: any = { state: workspaceElement.getState(), fullName: workspaceElement.getFullName(), type: workspaceElement.getMetadataName(), filePath: workspaceElement.getSourcePath(), deleteSupported: workspaceElement.getDeleteSupported(), }; const workspaceElementMetadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName( workspaceElement.getMetadataName(), this.swa.metadataRegistry ); const remoteChanges = this.remoteChanges.filter((remoteChange) => workspaceElementMetadataType.conflictDetected( remoteChange.type, remoteChange.fullName, workspaceElement.getFullName() ) ); if (remoteChanges && remoteChanges.length > 0) { localChange.isConflict = true; remoteChanges.forEach((remoteChange) => { remoteChange.isConflict = true; }); } this.localChanges.push(localChange); }); } else { return []; } } getLocalChanges() { return this.localChanges; } getRemoteChanges() { return this.remoteChanges; } getLocalConflicts() { const aggregateKeys = new Set(); return this.localChanges .filter((item) => { const metadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName(item.type, this.swa.metadataRegistry); if (item.isConflict && metadataType.onlyDisplayOneConflictPerAggregate()) { const aggregateFullName = metadataType.getAggregateFullNameFromWorkspaceFullName(item.fullName); const key = `${metadataType.getMetadataName()}#${aggregateFullName}`; if (!aggregateKeys.has(key)) { aggregateKeys.add(key); return true; } return false; } return item.isConflict; }) .map((item) => { const metadataType = MetadataTypeFactory.getMetadataTypeFromMetadataName(item.type, this.swa.metadataRegistry); if (metadataType.onlyDisplayOneConflictPerAggregate()) { return { state: item.state, fullName: metadataType.getAggregateFullNameFromWorkspaceFullName(item.fullName), type: item.type, filePath: metadataType.getDisplayPathForLocalConflict(item.filePath), deleteSupported: item.deleteSupported, }; } return item; }); } } // eslint-disable-next-line no-redeclare export namespace SrcStatusApi { export interface Options { org: any; adapter?: SourceWorkspaceAdapter; } }
the_stack
import XEUtils from 'xe-utils' import { simpleDebounce } from '/@/utils/common/compUtils' import { JVxeDataProps, JVxeRefs, JVxeTableProps, JVxeTypes } from '../types' import { getEnhanced } from '../utils/enhancedUtils' import { VxeTableInstance, VxeTablePrivateMethods } from 'vxe-table' import { cloneDeep } from 'lodash-es' import { isArray, isEmpty, isNull, isString } from '/@/utils/is' import { useLinkage } from './useLinkage' import { useWebSocket } from './useWebSocket' import { getPrefix, getJVxeAuths } from '../utils/authUtils' export function useMethods(props: JVxeTableProps, { emit }, data: JVxeDataProps, refs: JVxeRefs, instance) { let xTableTemp: VxeTableInstance & VxeTablePrivateMethods function getXTable() { if (!xTableTemp) { // !. 为 typescript 的非空断言 xTableTemp = refs.gridRef.value!.getRefMaps().refTable.value } return xTableTemp } // noinspection JSUnusedGlobalSymbols const hookMethods = { getXTable, addRows, pushRows, insertRows, addOrInsert, setValues, getValues, getTableData, getNewData, getNewDataWithId, getIfRowById, getNewRowById, getDeleteData, getSelectionData, removeRows, removeRowsById, removeSelection, resetScrollTop, validateTable, fullValidateTable, clearSelection, filterNewRows, isDisabledRow, recalcDisableRows, rowResort, } // 多级联动 const linkageMethods = useLinkage(props, data, hookMethods) // WebSocket 无痕刷新 const socketMethods = useWebSocket(props, data, hookMethods) // 可显式供外部调用的方法 const publicMethods = { ...hookMethods, ...linkageMethods, ...socketMethods, } /** 监听vxe滚动条位置 */ function handleVxeScroll(event) { let { scroll } = data // 记录滚动条的位置 scroll.top = event.scrollTop scroll.left = event.scrollLeft refs.subPopoverRef.value?.close() data.scrolling.value = true closeScrolling() } // 当手动勾选单选时触发的事件 function handleVxeRadioChange(event) { let row = event.$table.getRadioRecord() data.selectedRows.value = row ? [row] : [] handleSelectChange('radio', data.selectedRows.value, event) } // 当手动勾选全选时触发的事件 function handleVxeCheckboxAll(event) { data.selectedRows.value = event.$table.getCheckboxRecords() handleSelectChange('checkbox-all', data.selectedRows.value, event) } // 当手动勾选并且值发生改变时触发的事件 function handleVxeCheckboxChange(event) { data.selectedRows.value = event.$table.getCheckboxRecords() handleSelectChange('checkbox', data.selectedRows.value, event) } // 行选择change事件 function handleSelectChange(type, selectedRows, $event) { let action if (type === 'radio') { action = 'selected' } else if (type === 'checkbox') { action = selectedRows.includes($event.row) ? 'selected' : 'unselected' } else { action = 'selected-all' } data.selectedRowIds.value = selectedRows.map(row => row.id) trigger('selectRowChange', { type: type, action: action, $event: $event, row: $event.row, selectedRows: data.selectedRows.value, selectedRowIds: data.selectedRowIds.value, }) } // 点击单元格时触发的事件 function handleCellClick(event) { let { row, column, $event, $table } = event // 点击了可编辑的 if (column.editRender) { refs.subPopoverRef.value?.close() return } // 显示详细信息 if (column.params?.showDetails) { refs.detailsModalRef.value?.open(event) } else if (refs.subPopoverRef.value) { refs.subPopoverRef.value.toggle(event) } else if (props.clickSelectRow) { let className = $event.target.className || '' className = isString(className) ? className : className.toString() // 点击的是expand,不做处理 if (className.includes('vxe-table--expand-btn')) { return } // 点击的是checkbox,不做处理 if (className.includes('vxe-checkbox--icon') || className.includes('vxe-cell--checkbox')) { return } // 点击的是radio,不做处理 if (className.includes('vxe-radio--icon') || className.includes('vxe-cell--radio')) { return } if (props.rowSelectionType === 'radio') { $table.setRadioRow(row) handleVxeRadioChange(event) } else { $table.toggleCheckboxRow(row) handleVxeCheckboxChange(event) } } } // 单元格被激活编辑时会触发该事件 function handleEditActived({ column }) { // 执行增强 getEnhanced(column.params.type).aopEvents.editActived!.apply(instance, arguments as any) } // 单元格编辑状态下被关闭时会触发该事件 function handleEditClosed({ column }) { // 执行增强 getEnhanced(column.params.type).aopEvents.editClosed!.apply(instance, arguments as any) } // 返回值决定行是否可选中 function handleCheckMethod({ row }) { if (props.disabled) { return false } return !data.disabledRowIds.includes(row.id) } // 返回值决定单元格是否可以编辑 function handleActiveMethod({ row, column }) { let flag = (() => { if (props.disabled) { return false } if (data.disabledRowIds.includes(row.id)) { return false } if (column.params?.disabled) { return false } // 执行增强 return getEnhanced(column.params.type).aopEvents.activeMethod!.apply(instance, arguments as any) ?? true })() if (!flag) { getXTable().clearActived() } return flag } /** * 判断是否是禁用行 * @param row 行数据 * @param force 是否强制判断 */ function isDisabledRow(row, force = true) { if (!force) { return !data.disabledRowIds.includes(row.id) } if (props.disabledRows == null || isEmpty(props.disabledRows)) { return false } let disabled: boolean = false let keys: string[] = Object.keys(props.disabledRows) for (const key of keys) { // 判断是否有该属性 if (row.hasOwnProperty(key)) { let temp: any = props.disabledRows![key] // 禁用规则可以是一个数组 if (isArray(temp)) { disabled = temp.includes(row[key]) } else { disabled = (temp === row[key]) } if (disabled) { break } } } return disabled } // 重新计算禁用行 function recalcDisableRows() { let xTable = getXTable() data.disabledRowIds = [] const { tableFullData } = xTable.internalData tableFullData.forEach(row => { // 判断是否是禁用行 if (isDisabledRow(row)) { data.disabledRowIds.push(row.id) } }) xTable.updateData() } // 返回值决定是否允许展开、收起行 function handleExpandToggleMethod({ expanded }) { return !(expanded && props.disabled) } // 设置 data.scrolling 防抖模式 const closeScrolling = simpleDebounce(function () { data.scrolling.value = false }, 100) /** 表尾数据处理方法,用于显示统计信息 */ function handleFooterMethod({ columns, data: $data }) { const { statistics } = data let footers: any[] = [] if (statistics.has) { if (statistics.sum.length > 0) { footers.push(getFooterStatisticsMap({ columns: columns, title: '合计', checks: statistics.sum, method: (column) => XEUtils.sum($data, column.property), })) } if (statistics.average.length > 0) { footers.push(getFooterStatisticsMap({ columns: columns, title: '平均', checks: statistics.average, method: (column) => XEUtils.mean($data, column.property), })) } } return footers } /** 获取底部统计Map */ function getFooterStatisticsMap({ columns, title, checks, method }) { return columns.map((column, columnIndex) => { if (columnIndex === 0) { return title } if (checks.includes(column.property)) { return method(column, columnIndex) } return null }) } // 创建新行,自动添加默认值 function createRow(record: Recordable = {}) { let xTable = getXTable() // 添加默认值 xTable.internalData.tableFullColumn.forEach(column => { let col = column.params if (col) { if (col.key && (record[col.key] == null || record[col.key] === '')) { // 设置默认值 let createValue = getEnhanced(col.type).createValue let defaultValue = col.defaultValue ?? '' let ctx = { context: { row: record, column, $table: xTable } } record[col.key] = createValue(defaultValue, ctx) } // 处理联动列 if (col.type === JVxeTypes.select && data.innerLinkageConfig.size > 0) { // 判断当前列是否是联动列 if (data.innerLinkageConfig.has(col.key)) { let configItem = data.innerLinkageConfig.get(col.key) linkageMethods.getLinkageOptionsAsync(configItem, '') } } } }) return record } async function addOrInsert(rows: Recordable | Recordable[] = {}, index, triggerName, options?: IAddRowsOptions) { let xTable = getXTable() let records if (isArray(rows)) { records = rows } else { records = [rows] } // 遍历添加默认值 records.forEach(record => createRow(record)) let setActive = (options?.setActive ?? (props.addSetActive ?? true)) let result = await pushRows(records, { index: index, setActive }) // 遍历插入的行 // online js增强时以传过来值为准,不再赋默认值 if (!(options?.isOnlineJS ?? false)) { if (triggerName != null) { for (let i = 0; i < result.rows.length; i++) { let row = result.rows[i] trigger(triggerName, { row: row, rows: result.rows, insertIndex: index, $table: xTable, target: instance, }) } } } return result } // 新增、插入一行时的可选参数 interface IAddRowsOptions { // 是否是 onlineJS增强 触发的 isOnlineJS?: boolean, // 是否激活编辑状态 setActive?: boolean, } /** * 添加一行或多行 * * @param rows * @param options 参数 * @return */ async function addRows(rows: Recordable | Recordable[] = {}, options?: IAddRowsOptions) { return addOrInsert(rows, -1, 'added', options) } /** * 添加一行或多行临时数据,不会填充默认值,传什么就添加进去什么 * @param rows * @param options 选项 * @param options.setActive 是否激活最后一行的编辑模式 */ async function pushRows(rows: Recordable | Recordable[] = {}, options = { setActive: false, index: -1 }) { let xTable = getXTable() let { setActive, index } = options index = index === -1 ? index : xTable.internalData.tableFullData[index] // 插入行 let result = await xTable.insertAt(rows, index) if (setActive) { // 激活最后一行的编辑模式 xTable.setActiveRow(result.rows[result.rows.length - 1]) } await recalcSortNumber() return result } /** * 插入一行或多行临时数据 * * @param rows * @param index 添加下标,数字,必填 * @param options 参数 * @return */ function insertRows(rows: Recordable | Recordable[] = {}, index: number, options?: IAddRowsOptions) { if (index < 0) { console.warn(`【JVxeTable】insertRows:index必须传递数字,且大于-1`) return } return addOrInsert(rows, index, 'inserted', options) } /** 获取表格表单里的值 */ function getValues(callback, rowIds) { let tableData = getTableData({ rowIds: rowIds }) callback('', tableData) } /** 获取表格数据 */ function getTableData(options: any = {}) { let { rowIds } = options let tableData // 仅查询指定id的行 if (isArray(rowIds) && rowIds.length > 0) { tableData = [] rowIds.forEach(rowId => { let { row } = getIfRowById(rowId) if (row) { tableData.push(row) } }) } else { // 查询所有行 tableData = getXTable().getTableData().fullData } return filterNewRows(tableData, false) } /** 仅获取新增的数据 */ function getNewData() { let newData = getNewDataWithId() newData.forEach(row => delete row.id) return newData } /** 仅获取新增的数据,带有id */ function getNewDataWithId() { let xTable = getXTable() return cloneDeep(xTable.getInsertRecords()) } /** 根据ID获取行,新增的行也能查出来 */ function getIfRowById(id) { let xTable = getXTable() let row = xTable.getRowById(id), isNew = false if (!row) { row = getNewRowById(id) if (!row) { console.warn(`JVxeTable.getIfRowById:没有找到id为"${id}"的行`) return { row: null } } isNew = true } return { row, isNew } } /** 通过临时ID获取新增的行 */ function getNewRowById(id) { let records = getXTable().getInsertRecords() for (let record of records) { if (record.id === id) { return record } } return null } /** * 过滤添加的行 * @param rows 要筛选的行数据 * @param remove true = 删除新增,false=只删除id * @param handler function */ function filterNewRows(rows, remove = true, handler?: Fn) { let insertRecords = getXTable().getInsertRecords() let records: Recordable[] = [] for (let row of rows) { let item = cloneDeep(row) if (insertRecords.includes(row)) { handler ? handler({ item, row, insertRecords }) : null if (remove) { continue } delete item.id } records.push(item) } return records } /** * 重置滚动条Top位置 * @param top 新top位置,留空则滚动到上次记录的位置,用于解决切换tab选项卡时导致白屏以及自动将滚动条滚动到顶部的问题 */ function resetScrollTop(top?) { let xTable = getXTable() xTable.scrollTo(null, (top == null || top === '') ? data.scroll.top : top) } /** 校验table,失败返回errMap,成功返回null */ async function validateTable(rows?) { let xTable = getXTable() const errMap = await xTable.validate(rows ?? true).catch(errMap => errMap) return errMap ? errMap : null } /** 完整校验 */ async function fullValidateTable(rows?) { let xTable = getXTable() const errMap = await xTable.fullValidate(rows ?? true).catch(errMap => errMap) return errMap ? errMap : null } type setValuesParam = { rowKey: string, values: Recordable } /** * 设置某行某列的值 * * @param values * @return 返回受影响的单元格数量 */ function setValues(values: setValuesParam[]): number { if (!isArray(values)) { console.warn(`[JVxeTable] setValues 必须传递数组`) return 0 } let xTable = getXTable() let count = 0 values.forEach((item) => { let { rowKey, values: record } = item let { row } = getIfRowById(rowKey) if (!row) { return } Object.keys(record).forEach(colKey => { let column = xTable.getColumnByField(colKey) if (column) { let oldValue = row[colKey] let newValue = record[colKey] if (newValue !== oldValue) { row[colKey] = newValue // 触发 valueChange 事件 trigger('valueChange', { type: column.params.type, value: newValue, oldValue: oldValue, col: column.params, column: column, isSetValues: true, }) count++ } } else { console.warn(`[JVxeTable] setValues 没有找到key为"${colKey}"的列`) } }) }) if (count > 0) { xTable.updateData() } return count } /** 清空选择行 */ async function clearSelection() { const xTable = getXTable() let event = { $table: xTable, target: instance } if (props.rowSelectionType === JVxeTypes.rowRadio) { await xTable.clearRadioRow() handleVxeRadioChange(event) } else { await xTable.clearCheckboxRow() handleVxeCheckboxChange(event) } } /** * 获取选中数据 * @param isFull 如果 isFull=true 则获取全表已选中的数据 */ function getSelectionData(isFull?: boolean) { const xTable = getXTable() if (props.rowSelectionType === JVxeTypes.rowRadio) { let row = xTable.getRadioRecord(isFull) if (isNull(row)) { return [] } return filterNewRows([row], false) } else { return filterNewRows(xTable.getCheckboxRecords(isFull), false) } } /** 仅获取被删除的数据(新增又被删除的数据不会被获取到) */ function getDeleteData() { return filterNewRows(getXTable().getRemoveRecords(), false) } /** 删除一行或多行数据 */ async function removeRows(rows) { const xTable = getXTable() const res = await xTable.remove(rows) let removeEvent: any = { deleteRows: rows, $table: xTable } trigger('removed', removeEvent) await recalcSortNumber() return res } /** 根据id删除一行或多行 */ function removeRowsById(rowId) { let rowIds if (isArray(rowId)) { rowIds = rowId } else { rowIds = [rowId] } let rows = rowIds.map((id) => { let { row } = getIfRowById(id) if (!row) { return } if (row) { return row } else { console.warn(`【JVxeTable】removeRowsById:${id}不存在`) return null } }).filter((row) => row != null) return removeRows(rows) } // 删除选中的数据 async function removeSelection() { let xTable = getXTable() let res if (props.rowSelectionType === JVxeTypes.rowRadio) { res = await xTable.removeRadioRow() } else { res = await xTable.removeCheckboxRow() } await clearSelection() await recalcSortNumber() return res } /** 重新计算排序字段的数值 */ async function recalcSortNumber(force = false) { if (props.dragSort || force) { let xTable = getXTable() let sortKey = props.sortKey ?? 'orderNum' let sortBegin = props.sortBegin ?? 0 xTable.internalData.tableFullData.forEach((data) => data[sortKey] = sortBegin++) // 4.1.0 await xTable.updateCache() // 4.1.1 // await xTable.cacheRowMap() return await xTable.updateData() } } /** * 排序表格 * @param oldIndex * @param newIndex * @param force 强制排序 */ async function doSort(oldIndex: number, newIndex: number, force = false) { if (props.dragSort || force) { let xTable = getXTable() let sort = (array) => { // 存储old数据,并删除该项 let row = array.splice(oldIndex, 1)[0] // 向newIndex处添加old数据 array.splice(newIndex, 0, row) } sort(xTable.internalData.tableFullData) if (xTable.keepSource) { sort(xTable.internalData.tableSourceData) } return await recalcSortNumber(force) } } /** 行重新排序 */ function rowResort(oldIndex: number, newIndex: number) { return doSort(oldIndex, newIndex, true) } // ---------------- begin 权限控制 ---------------- // 加载权限 function loadAuthsMap() { if (!props.authPre || props.authPre.length == 0) { data.authsMap.value = null } else { data.authsMap.value = getJVxeAuths(props.authPre) } } /** * 根据 权限code 获取权限 * @param authCode */ function getAuth(authCode) { if (data.authsMap.value != null && props.authPre) { let prefix = getPrefix(props.authPre) return data.authsMap.value.get(prefix + authCode) } return null } // 获取列权限 function getColAuth(key: string) { return getAuth(key) } // 判断按钮权限 function hasBtnAuth(key: string) { return getAuth('btn:' + key)?.isAuth ?? true } // ---------------- end 权限控制 ---------------- /* --- 辅助方法 ---*/ function created() { loadAuthsMap() } // 触发事件 function trigger(name, event: any = {}) { event.$target = instance event.$table = getXTable() //online增强参数兼容 event.target = instance emit(name, event) } return { methods: { trigger, ...publicMethods, closeScrolling, doSort, recalcSortNumber, handleVxeScroll, handleVxeRadioChange, handleVxeCheckboxAll, handleVxeCheckboxChange, handleFooterMethod, handleCellClick, handleEditActived, handleEditClosed, handleCheckMethod, handleActiveMethod, handleExpandToggleMethod, getColAuth, hasBtnAuth, }, publicMethods, created, } }
the_stack
module dragonBones { /** *@class dragonBones.DataParser * @classdesc * 老版本数据解析 */ export class Data3Parser{ private static tempDragonBonesData:DragonBonesData; public static parseDragonBonesData(rawDataToParse:any):DragonBonesData{ if(!rawDataToParse){ throw new Error(); } var version:string = rawDataToParse[ConstValues.A_VERSION]; version = version.toString(); if( version.toString() != DragonBones.DATA_VERSION && version.toString() != DragonBones.PARENT_COORDINATE_DATA_VERSION && version.toString() != "2.3") { throw new Error("Nonsupport version!"); } var frameRate:number = Data3Parser.getNumber(rawDataToParse, ConstValues.A_FRAME_RATE, 0) || 0; var outputDragonBonesData:DragonBonesData = new DragonBonesData(); outputDragonBonesData.name = rawDataToParse[ConstValues.A_NAME]; outputDragonBonesData.isGlobal = rawDataToParse[ConstValues.A_IS_GLOBAL] == "0" ? false : true; Data3Parser.tempDragonBonesData = outputDragonBonesData; var armatureList:any = rawDataToParse[ConstValues.ARMATURE]; for(var i:number = 0, len:number = armatureList.length; i < len; i++) { var armatureObject:any = armatureList[i]; outputDragonBonesData.addArmatureData(Data3Parser.parseArmatureData(armatureObject, frameRate)); } Data3Parser.tempDragonBonesData = null; return outputDragonBonesData; } private static parseArmatureData(armatureDataToParse:any, frameRate:number):ArmatureData{ var outputArmatureData:ArmatureData = new ArmatureData(); outputArmatureData.name = armatureDataToParse[ConstValues.A_NAME]; var i:number; var len:number; var boneList:any = armatureDataToParse[ConstValues.BONE]; for(i = 0, len = boneList.length; i < len; i++) { var boneObject:any = boneList[i]; outputArmatureData.addBoneData(Data3Parser.parseBoneData(boneObject)); } var skinList:any = armatureDataToParse[ConstValues.SKIN]; for(i = 0, len = skinList.length; i < len; i++) { var skinSlotList:any = skinList[i]; var skinSlotObject:any = skinSlotList[ConstValues.SLOT]; for(var j:number = 0, jLen:number = skinSlotObject.length; j < jLen; j++) { var slotObject:any = skinSlotObject[j]; outputArmatureData.addSlotData(Data3Parser.parseSlotData(slotObject)) } } for(i = 0, len = skinList.length; i < len; i++) { var skinObject:any = skinList[i]; outputArmatureData.addSkinData(Data3Parser.parseSkinData(skinObject)); } if(Data3Parser.tempDragonBonesData.isGlobal) { DBDataUtil.transformArmatureData(outputArmatureData); } outputArmatureData.sortBoneDataList(); var animationList:any = armatureDataToParse[ConstValues.ANIMATION]; for(i = 0, len = animationList.length; i < len; i++) { var animationObject:any = animationList[i]; var animationData:AnimationData = Data3Parser.parseAnimationData(animationObject, frameRate); DBDataUtil.addHideTimeline(animationData, outputArmatureData); DBDataUtil.transformAnimationData(animationData, outputArmatureData, Data3Parser.tempDragonBonesData.isGlobal); outputArmatureData.addAnimationData(animationData); } return outputArmatureData; } //把bone的初始transform解析并返回 private static parseBoneData(boneObject:any):BoneData{ var boneData:BoneData = new BoneData(); boneData.name = boneObject[ConstValues.A_NAME]; boneData.parent = boneObject[ConstValues.A_PARENT]; boneData.length = Number(boneObject[ConstValues.A_LENGTH]) || 0; boneData.inheritRotation = Data3Parser.getBoolean(boneObject, ConstValues.A_INHERIT_ROTATION, true); boneData.inheritScale = Data3Parser.getBoolean(boneObject, ConstValues.A_INHERIT_SCALE, true); Data3Parser.parseTransform(boneObject[ConstValues.TRANSFORM], boneData.transform); if(Data3Parser.tempDragonBonesData.isGlobal)//绝对数据 { boneData.global.copy(boneData.transform); } return boneData; } private static parseSkinData(skinObject:any):SkinData{ var skinData:SkinData = new SkinData(); skinData.name = skinObject[ConstValues.A_NAME]; var slotList:any = skinObject[ConstValues.SLOT]; for(var i:number = 0, len:number = slotList.length; i < len; i++) { var slotObject:any = slotList[i]; skinData.addSlotData(Data3Parser.parseSkinSlotData(slotObject)); } return skinData; } private static parseSkinSlotData(slotObject:any):SlotData{ var slotData:SlotData = new SlotData(); slotData.name = slotObject[ConstValues.A_NAME]; slotData.parent = slotObject[ConstValues.A_PARENT]; slotData.zOrder = <number><any> (slotObject[ConstValues.A_Z_ORDER]); slotData.zOrder = Data3Parser.getNumber(slotObject,ConstValues.A_Z_ORDER,0)||0; slotData.blendMode = slotObject[ConstValues.A_BLENDMODE]; var displayList:any = slotObject[ConstValues.DISPLAY]; if(displayList) { for(var i:number = 0, len:number = displayList.length; i < len; i++) { var displayObject:any = displayList[i]; slotData.addDisplayData(Data3Parser.parseDisplayData(displayObject)); } } return slotData; } private static parseSlotData(slotObject:any):SlotData{ var slotData:SlotData = new SlotData(); slotData.name = slotObject[ConstValues.A_NAME]; slotData.parent = slotObject[ConstValues.A_PARENT]; slotData.zOrder = <number><any> (slotObject[ConstValues.A_Z_ORDER]); slotData.zOrder = Data3Parser.getNumber(slotObject,ConstValues.A_Z_ORDER,0)||0; slotData.blendMode = slotObject[ConstValues.A_BLENDMODE]; slotData.displayIndex = 0; return slotData; } private static parseDisplayData(displayObject:any):DisplayData{ var displayData:DisplayData = new DisplayData(); displayData.name = displayObject[ConstValues.A_NAME]; displayData.type = displayObject[ConstValues.A_TYPE]; Data3Parser.parseTransform(displayObject[ConstValues.TRANSFORM], displayData.transform, displayData.pivot); if(Data3Parser.tempDragonBonesData!=null){ Data3Parser.tempDragonBonesData.addDisplayData(displayData); } return displayData; } /** @private */ private static parseAnimationData(animationObject:any, frameRate:number):AnimationData{ var animationData:AnimationData = new AnimationData(); animationData.name = animationObject[ConstValues.A_NAME]; animationData.frameRate = frameRate; animationData.duration = Math.round((Data3Parser.getNumber(animationObject, ConstValues.A_DURATION, 1) || 1) * 1000 / frameRate); animationData.playTimes = Data3Parser.getNumber(animationObject, ConstValues.A_LOOP, 1); animationData.playTimes = animationData.playTimes != NaN ? animationData.playTimes : 1; animationData.fadeTime = Data3Parser.getNumber(animationObject, ConstValues.A_FADE_IN_TIME, 0) || 0; animationData.scale = Data3Parser.getNumber(animationObject, ConstValues.A_SCALE, 1) || 0; //use frame tweenEase, NaN //overwrite frame tweenEase, [-1, 0):ease in, 0:line easing, (0, 1]:ease out, (1, 2]:ease in out animationData.tweenEasing = Data3Parser.getNumber(animationObject, ConstValues.A_TWEEN_EASING, NaN); animationData.autoTween = Data3Parser.getBoolean(animationObject, ConstValues.A_AUTO_TWEEN, true); var frameObjectList:Array<any> = animationObject[ConstValues.FRAME]; var i:number = 0; var len:number = 0; if(frameObjectList) { for(i = 0,len = frameObjectList.length; i< len; i++) { var frameObject:any = frameObjectList[i]; var frame:Frame = Data3Parser.parseTransformFrame(frameObject, null, frameRate); animationData.addFrame(frame); } } Data3Parser.parseTimeline(animationObject, animationData); var lastFrameDuration:number = animationData.duration; var displayIndexChangeSlotTimelines:Array<SlotTimeline> = []; var displayIndexChangeTimelines:Array<TransformTimeline> = []; var timelineObjectList:Array<any> = animationObject[ConstValues.TIMELINE]; var displayIndexChange:boolean; if(timelineObjectList) { for(i = 0,len = timelineObjectList.length; i < len; i++) { var timelineObject:any = timelineObjectList[i]; var timeline:TransformTimeline = Data3Parser.parseTransformTimeline(timelineObject, animationData.duration, frameRate); timeline = Data3Parser.parseTransformTimeline(timelineObject, animationData.duration, frameRate); lastFrameDuration = Math.min(lastFrameDuration, timeline.frameList[timeline.frameList.length - 1].duration); animationData.addTimeline(timeline); var slotTimeline:SlotTimeline = Data3Parser.parseSlotTimeline(timelineObject, animationData.duration, frameRate); animationData.addSlotTimeline(slotTimeline); if(animationData.autoTween && !displayIndexChange) { var slotFrame:SlotFrame; for(var j:number = 0, jlen:number = slotTimeline.frameList.length; j < jlen; j++) { slotFrame = <SlotFrame>slotTimeline.frameList[j]; if(slotFrame && slotFrame.displayIndex < 0) { displayIndexChange = true; break; } } } } /** * 如果有slot的displayIndex为空的情况,那么当autoTween为ture时,它对应的bone的补间应该去掉 * 以下就是处理这种情况,把autoTween的全局的tween应用到每一帧上,然后把autoTween变为false * 此时autoTween就不起任何作用了 */ var animationTween:number = animationData.tweenEasing; if(displayIndexChange) { len = animationData.slotTimelineList.length; for ( i = 0; i < len; i++) { slotTimeline = animationData.slotTimelineList[i]; timeline = animationData.timelineList[i]; var curFrame:TransformFrame; var curSlotFrame:SlotFrame; var nextSlotFrame:SlotFrame; for (j = 0, jlen = slotTimeline.frameList.length; j < jlen; j++) { curSlotFrame = <SlotFrame>slotTimeline.frameList[j]; curFrame = <TransformFrame>timeline.frameList[j]; nextSlotFrame = (j == jlen - 1) ? <SlotFrame>slotTimeline.frameList[0] : <SlotFrame>slotTimeline.frameList[j + 1]; if (curSlotFrame.displayIndex < 0 || nextSlotFrame.displayIndex < 0) { curFrame.tweenEasing = curSlotFrame.tweenEasing = NaN; } else if (animationTween == 10) { curFrame.tweenEasing = curSlotFrame.tweenEasing = 0; } else if (!isNaN(animationTween)) { curFrame.tweenEasing = curSlotFrame.tweenEasing = animationTween; } else if(curFrame.tweenEasing == 10) { curFrame.tweenEasing = 0; } } } animationData.autoTween = false; } } if(animationData.frameList.length > 0){ lastFrameDuration = Math.min(lastFrameDuration, animationData.frameList[animationData.frameList.length - 1].duration); } //取得timeline中最小的lastFrameDuration并保存 animationData.lastFrameDuration = lastFrameDuration; return animationData; } private static parseSlotTimeline(timelineObject:any, duration:number, frameRate:number):SlotTimeline{ var outputTimeline:SlotTimeline = new SlotTimeline(); outputTimeline.name = timelineObject[ConstValues.A_NAME]; outputTimeline.scale = Data3Parser.getNumber(timelineObject, ConstValues.A_SCALE, 1) || 0; outputTimeline.offset = Data3Parser.getNumber(timelineObject, ConstValues.A_OFFSET, 0) || 0; outputTimeline.duration = duration; var frameList:any = timelineObject[ConstValues.FRAME]; for(var i:number = 0, len:number = frameList.length; i < len; i++) { var frameObject:any = frameList[i]; var frame:SlotFrame = Data3Parser.parseSlotFrame(frameObject, frameRate); outputTimeline.addFrame(frame); } Data3Parser.parseTimeline(timelineObject, outputTimeline); return outputTimeline; } private static parseSlotFrame(frameObject:any, frameRate:number):SlotFrame{ var outputFrame:SlotFrame = new SlotFrame(); Data3Parser.parseFrame(frameObject, outputFrame, frameRate); outputFrame.visible = !Data3Parser.getBoolean(frameObject, ConstValues.A_HIDE, false); //NaN:no tween, 10:auto tween, [-1, 0):ease in, 0:line easing, (0, 1]:ease out, (1, 2]:ease in out outputFrame.tweenEasing = Data3Parser.getNumber(frameObject, ConstValues.A_TWEEN_EASING, 10); outputFrame.displayIndex = Math.floor(Data3Parser.getNumber(frameObject, ConstValues.A_DISPLAY_INDEX, 0)|| 0); //如果为NaN,则说明没有改变过zOrder outputFrame.zOrder = Data3Parser.getNumber(frameObject, ConstValues.A_Z_ORDER, Data3Parser.tempDragonBonesData.isGlobal ? NaN : 0); var colorTransformObject:any = frameObject[ConstValues.COLOR_TRANSFORM]; if(colorTransformObject){ outputFrame.color = new ColorTransform(); Data3Parser.parseColorTransform(colorTransformObject, outputFrame.color); } return outputFrame; } private static parseTransformTimeline(timelineObject:any, duration:number, frameRate:number):TransformTimeline{ var outputTimeline:TransformTimeline = new TransformTimeline(); outputTimeline.name = timelineObject[ConstValues.A_NAME]; outputTimeline.scale = Data3Parser.getNumber(timelineObject, ConstValues.A_SCALE, 1) || 0; outputTimeline.offset = Data3Parser.getNumber(timelineObject, ConstValues.A_OFFSET, 0) || 0; outputTimeline.originPivot.x = Data3Parser.getNumber(timelineObject, ConstValues.A_PIVOT_X, 0) || 0; outputTimeline.originPivot.y = Data3Parser.getNumber(timelineObject, ConstValues.A_PIVOT_Y, 0) || 0; outputTimeline.duration = duration; var frameList:any = timelineObject[ConstValues.FRAME]; var nextFrameObject:any; for(var i:number = 0, len:number = frameList.length; i < len; i++) { var frameObject:any = frameList[i]; if(i < len - 1) { nextFrameObject = frameList[i+1]; } else if(i != 0) { nextFrameObject = frameList[0]; } else { nextFrameObject = null; } var frame:TransformFrame = Data3Parser.parseTransformFrame(frameObject, nextFrameObject, frameRate); outputTimeline.addFrame(frame); } Data3Parser.parseTimeline(timelineObject, outputTimeline); return outputTimeline; } private static parseTransformFrame(frameObject:any, nextFrameObject:any, frameRate:number):TransformFrame{ var outputFrame:TransformFrame = new TransformFrame(); Data3Parser.parseFrame(frameObject, outputFrame, frameRate); outputFrame.visible = !Data3Parser.getBoolean(frameObject, ConstValues.A_HIDE, false); //NaN:no tween, 10:auto tween, [-1, 0):ease in, 0:line easing, (0, 1]:ease out, (1, 2]:ease in out outputFrame.tweenEasing = Data3Parser.getNumber(frameObject, ConstValues.A_TWEEN_EASING, 10); outputFrame.tweenRotate = Math.floor(Data3Parser.getNumber(frameObject, ConstValues.A_TWEEN_ROTATE, 0) || 0); outputFrame.tweenScale = Data3Parser.getBoolean(frameObject, ConstValues.A_TWEEN_SCALE, true); //outputFrame.displayIndex = Math.floor(Data3Parser.getNumber(frameObject, ConstValues.A_DISPLAY_INDEX, 0)|| 0); if (nextFrameObject && Math.floor(Data3Parser.getNumber(nextFrameObject, ConstValues.A_DISPLAY_INDEX, 0)|| 0) == -1) { outputFrame.tweenEasing = NaN; } Data3Parser.parseTransform(frameObject[ConstValues.TRANSFORM], outputFrame.transform, outputFrame.pivot); if(Data3Parser.tempDragonBonesData.isGlobal)//绝对数据 { outputFrame.global.copy(outputFrame.transform); } outputFrame.scaleOffset.x = Data3Parser.getNumber(frameObject, ConstValues.A_SCALE_X_OFFSET, 0)||0; outputFrame.scaleOffset.y = Data3Parser.getNumber(frameObject, ConstValues.A_SCALE_Y_OFFSET, 0)||0; return outputFrame; } private static parseTimeline(timelineObject:any, outputTimeline:Timeline):void{ var position:number = 0; var frame:Frame; var frameList:any = outputTimeline.frameList; for(var i:number = 0, len:number = frameList.length; i < len; i++) { frame = frameList[i]; frame.position = position; position += frame.duration; } //防止duration计算有误差 if(frame){ frame.duration = outputTimeline.duration - frame.position; } } private static parseFrame(frameObject:any, outputFrame:Frame, frameRate:number = 0):void{ outputFrame.duration = Math.round((<number><any> (frameObject[ConstValues.A_DURATION]) || 1) * 1000 / frameRate); outputFrame.action = frameObject[ConstValues.A_ACTION]; outputFrame.event = frameObject[ConstValues.A_EVENT]; outputFrame.sound = frameObject[ConstValues.A_SOUND]; } private static parseTransform(transformObject:any, transform:DBTransform, pivot:Point = null):void{ if(transformObject){ if(transform){ transform.x = Data3Parser.getNumber(transformObject, ConstValues.A_X, 0) || 0; transform.y = Data3Parser.getNumber(transformObject, ConstValues.A_Y, 0) || 0; transform.skewX = Data3Parser.getNumber (transformObject, ConstValues.A_SKEW_X, 0) * ConstValues.ANGLE_TO_RADIAN || 0; transform.skewY =Data3Parser.getNumber(transformObject, ConstValues.A_SKEW_Y, 0) * ConstValues.ANGLE_TO_RADIAN || 0; transform.scaleX = Data3Parser.getNumber(transformObject, ConstValues.A_SCALE_X, 1) || 0; transform.scaleY = Data3Parser.getNumber(transformObject, ConstValues.A_SCALE_Y, 1) || 0; } if(pivot){ pivot.x = Data3Parser.getNumber(transformObject, ConstValues.A_PIVOT_X, 0) || 0; pivot.y = Data3Parser.getNumber(transformObject, ConstValues.A_PIVOT_Y, 0) || 0; } } } private static parseColorTransform(colorTransformObject:any, colorTransform:ColorTransform):void{ if(colorTransformObject){ if(colorTransform){ colorTransform.alphaOffset =Data3Parser.getNumber(colorTransformObject, ConstValues.A_ALPHA_OFFSET, 0); colorTransform.redOffset = Data3Parser.getNumber(colorTransformObject, ConstValues.A_RED_OFFSET, 0); colorTransform.greenOffset = Data3Parser.getNumber(colorTransformObject, ConstValues.A_GREEN_OFFSET, 0); colorTransform.blueOffset = Data3Parser.getNumber(colorTransformObject, ConstValues.A_BLUE_OFFSET, 0); colorTransform.alphaMultiplier = Data3Parser.getNumber(colorTransformObject, ConstValues.A_ALPHA_MULTIPLIER, 100) * 0.01; colorTransform.redMultiplier = Data3Parser.getNumber(colorTransformObject, ConstValues.A_RED_MULTIPLIER, 100) * 0.01; colorTransform.greenMultiplier =Data3Parser.getNumber(colorTransformObject, ConstValues.A_GREEN_MULTIPLIER, 100) * 0.01; colorTransform.blueMultiplier = Data3Parser.getNumber(colorTransformObject, ConstValues.A_BLUE_MULTIPLIER, 100) * 0.01; } } } private static getBoolean(data:any, key:string, defaultValue:boolean):boolean{ if(data && key in data){ switch(String(data[key])){ case "0": case "NaN": case "": case "false": case "null": case "undefined": return false; case "1": case "true": default: return true; } } return defaultValue; } private static getNumber(data:any, key:string, defaultValue:number):number{ if(data && key in data){ switch(String(data[key])){ case "NaN": case "": case "false": case "null": case "undefined": return NaN; default: return Number(data[key]); } } return defaultValue; } } }
the_stack
import { addMinutes } from 'date-fns'; import { RevisionInfo, RevisionInfoProps, } from '@/shared/models/revision-info.model'; import { FeedPage, FeedPageProps } from '@/shared/models/feed-page.model'; import { MwActionApiClient, MwPageInfo } from '@/shared/mwapi'; import { feedRevisionEngineLogger } from '../common'; import { FeedRevision, FeedRevisionProps, FeedRevisionDoc, } from '~/shared/models/feed-revision.model'; export class FeedRevisionEngine { public static async populateFeedRevisions(feed: string, _wiki: string) { const articleLists = (await FeedPage.find({ wiki: _wiki, feed })).map( (fp) => fp.title, ); for ( let articleIndex = 0; articleIndex < articleLists.length; articleIndex += 50 ) { const titles = articleLists.slice( articleIndex, Math.min(articleIndex + 50, articleLists.length), ); feedRevisionEngineLogger.debug(`Reading the articles ${articleIndex}`, titles); const wiki = _wiki || 'enwiki'; const result = await MwActionApiClient.getLastRevisionsByTitles( titles, wiki, ); if (Object.keys(result.query.pages).length > 0) { const pageIds = Object.keys(result.query.pages); const revisionInfos = []; const feedRevisions = []; for (const pageId of pageIds) { if (result.query.pages[pageId].revisions?.length > 0) { const [ revisionInfo, feedRevision, ] = FeedRevisionEngine.getFeedRevisionPair(feed, wiki, result, pageId); revisionInfos.push(revisionInfo); feedRevisions.push(feedRevision); } } try { const ret = await Promise.all([ RevisionInfo.bulkWrite( revisionInfos.map((ri: RevisionInfoProps) => { return { updateOne: { filter: { wikiRevId: ri.wikiRevId }, update: { $set: ri }, upsert: true, }, }; }), ), FeedRevision.bulkWrite( feedRevisions.map((fr: FeedRevisionProps) => { return { updateOne: { filter: { title: fr.title, $or: [ { claimerInfo: { $exists: false, }, }, { 'claimerInfo.checkedOfAt': { $exists: false, }, 'claimExpiresAt': { $lte: new Date(), }, }, ], }, update: { $set: fr }, upsert: true, }, }; }), ), ]); feedRevisionEngineLogger.debug( `Current articleIndex=${articleIndex} Ret = `, JSON.stringify(ret, null, 2), ); } catch (e) { if (e.code === 11000 && /^E11000 duplicate key error collection.*/.test(e.errmsg)) { feedRevisionEngineLogger.debug('BulkWrite E11000 issue potentially caused by\n\nhttps://jira.mongodb.org/browse/SERVER-14322.\n\nWe are skipping the suggested retry documented by https://jira.mongodb.org/browse/DOCS-12234 '); } else { // otherwise rethrow throw e; } } } } } private static getFeedRevisionPair = function(feed, wiki, result, pageId) { const revisions = result.query.pages[pageId].revisions; if (revisions.length > 1) { feedRevisionEngineLogger.info(`revisions.length > 1 title=${result.query.pages[pageId].title}, revId=${revisions[0].revid} length=${revisions.length}`); } const revision = revisions[0]; const wikiRevId = `${wiki}:${revision.revid}`; const revisionInfo = <RevisionInfoProps>{ wikiRevId, revId: revision.revid, wiki, pageId: parseInt(pageId), title: result.query.pages[pageId].title, wikiCreated: new Date(revision.timestamp), tags: revision.tags, summary: revision.comment, // skip diff // skip ores_damaging // skip ores_damaging prevRevId: revision.parentid, }; if (Object.keys(revision).includes('anon')) { revisionInfo.anonymousIp = revision.user; } else {revisionInfo.wikiUserName = revision.user;} if (revision.oresscores?.damaging) {revisionInfo.ores_damaging = revision.oresscores.damaging.true;} if (revision.oresscores?.badfaith) {revisionInfo.ores_badfaith = revision.oresscores.goodfaith.false;} const feedRevision = <FeedRevisionProps>{ feed, wikiRevId, title: result.query.pages[pageId].title, createdAt: new Date(), wiki, feedRankScore: 0, }; return [revisionInfo, feedRevision]; } /** * Fetch and claim the feedRevisions that is claimable and has no claimerInfo. * * Caveat: we are using a "find-and-then" update approach * there could potentially be racing condition if two users are fetching * the result * @param userGaId * @param wikiUserName * @param feed * @param wiki * @param limit */ public static async fetchAndClaim( userGaId, wikiUserName = '', feed = 'us2020', wiki = 'enwiki', limit = 2, ): Promise<FeedRevisionProps[]> { const feedRevisions: FeedRevisionDoc[] = await FeedRevision.find({ wiki, feed, $or: [ { claimerInfo: { $exists: false } }, // no claimer { $and: [ { claimExpiresAt: { $exists: true } }, { claimExpiresAt: { $lte: new Date() } }, ], }, // claim expired ], }) .sort([['feedRankScore', 1]]) .limit(limit); const results = await Promise.all( feedRevisions.map((fr) => { const now = new Date(); fr.claimerInfo = { userGaId, wikiUserName, claimedAt: now, }; if (wikiUserName) {fr.claimerInfo.wikiUserName = wikiUserName;} fr.claimExpiresAt = addMinutes(now, 15); return fr.save(); }), ); return results.map((doc) => doc as FeedRevisionProps); } /** * Given wikiRevIds for revisions potentially pending review in a feed, * check-off them in the database, and return the number of revisions checked-off * * @param wikiRevIds * @param userGaId * @param wikiUserName * @param feed * * TODO suggest return {Promise<number>} how many wikiRevIds are checked-off. */ public static async checkOff( wikiRevIds: string[], userGaId, wikiUserName = null, feed = 'us2020', ) { return await FeedRevision.bulkWrite( wikiRevIds.map((wikiRevId) => { const filter = { 'wiki': wikiRevId.split(':')[0], wikiRevId, feed, 'claimerInfo.userGaId': userGaId, }; if (wikiUserName) {filter['claimerInfo.wikiUserName'] = wikiUserName;} return { updateOne: { filter, update: { $set: { 'claimerInfo.checkedOfAt': new Date(), }, $unset: { claimExpiresAt: '' }, }, }, }; }), ).then(()=>{ }); } private static traverse = async function(feed, wiki, entryFeedPage) { let numReq = 0; const visitedFeedPages = {}; const toVisitFeedPages:FeedPageProps[] = []; toVisitFeedPages.push(entryFeedPage); // enqueue from its tail const now = new Date(); while (toVisitFeedPages.length > 0) { const currentFeedPage:FeedPageProps = toVisitFeedPages.shift(); // dequeue from it's head, Breadth First Search (BFS) if (visitedFeedPages[currentFeedPage.pageId]) { continue; } else { visitedFeedPages[currentFeedPage.pageId] = currentFeedPage; } feedRevisionEngineLogger.debug(`Current numReq=${numReq}`, currentFeedPage); if (currentFeedPage.namespace === 14) { const mwPageInfos = await MwActionApiClient.getCategoryChildren(wiki, currentFeedPage.title); numReq++; const children:FeedPageProps[] = mwPageInfos.map((mwPageInfo) => { return <FeedPageProps>{ feed, wiki, title: mwPageInfo.title, pageId: parseInt(mwPageInfo.pageid), namespace: parseInt(mwPageInfo.ns), traversedAt: now, }; }); currentFeedPage.categoryChildren = Array.from(new Set(children.map((feedPage) => feedPage.pageId))); children .forEach((feedPage:FeedPageProps) => { if (!feedPage.categoryParents) {feedPage.categoryParents = [];} feedPage.categoryParents = Array.from(new Set(feedPage.categoryParents.concat(currentFeedPage.pageId))); }); feedRevisionEngineLogger.debug('Children = ', children); toVisitFeedPages.push(...(children.filter((feedPage) => !visitedFeedPages[feedPage.pageId]))); } feedRevisionEngineLogger.debug(`=== Total toVisit ${toVisitFeedPages.length}, visited = ${Object.keys(visitedFeedPages).length}, numReq=${numReq}`); } try { const bulkUpdateResult = await FeedPage.bulkWrite(Object.values(visitedFeedPages).map((feedPage:FeedPageProps) => { return { updateOne: { filter: { feed: feedPage.feed, wiki: feedPage.wiki, title: feedPage.title, }, upsert: true, update: { $set: feedPage, }, }, }; })); feedRevisionEngineLogger.debug('Done bulkUpdateResult = ', bulkUpdateResult); } catch (e) { if (e.code === 11000 && /^E11000 duplicate key error collection.*/.test(e.errmsg)) { feedRevisionEngineLogger.debug('BulkWrite E11000 issue potentially caused by\n\nhttps://jira.mongodb.org/browse/SERVER-14322.\n\nWe are skipping the suggested retry documented by https://jira.mongodb.org/browse/DOCS-12234 '); } else { // otherwise rethrow throw e; } } } public static traverseCategoryTree = async function(feed: string, wiki: string, entryTitle: string) { const mwPageInfos = await MwActionApiClient.getMwPageInfosByTitles(wiki, [entryTitle]); const mwPageInfo: MwPageInfo = mwPageInfos[0]; const entryFeedPage: FeedPageProps = <FeedPageProps>{ feed, wiki, title: mwPageInfo.title, pageId: parseInt(mwPageInfo.pageid), namespace: parseInt(mwPageInfo.ns), traversedAt: new Date(), }; await FeedRevisionEngine.traverse(feed, wiki, entryFeedPage); } }
the_stack
import * as assert from 'assert'; import * as Azure from 'azure-storage'; import { execFile } from 'child_process'; import find from 'find-process'; import { BlobServiceClient, newPipeline as blobNewPipeline, StorageSharedKeyCredential as blobStorageSharedKeyCredential } from '@azure/storage-blob'; import { newPipeline as queueNewPipeline, QueueClient, QueueServiceClient, StorageSharedKeyCredential as queueStorageSharedKeyCredential } from '@azure/storage-queue'; import { configLogger } from '../src/common/Logger'; import { HeaderConstants, TABLE_API_VERSION } from '../src/table/utils/constants'; import BlobTestServerFactory from './BlobTestServerFactory'; import { createConnectionStringForTest, HOST, PORT, PROTOCOL } from './table/apis/table.entity.test.utils'; import { bodyToString, EMULATOR_ACCOUNT_KEY, EMULATOR_ACCOUNT_NAME, getUniqueName, overrideRequest, restoreBuildRequestOptions } from './testutils'; // server address used for testing. Note that Azurite.exe has // server address of http://127.0.0.1:10000 and so on by default // and we need to configure them when starting azurite.exe const blobAddress = "http://127.0.0.1:11000"; const queueAddress = "http://127.0.0.1:11001"; const tableAddress = "http://127.0.0.1:11002"; // Set true to enable debug log configLogger(false); // For convenience, we have a switch to control the use // of a local Azurite instance, otherwise we need an // ENV VAR called AZURE_TABLE_STORAGE added to mocha // script or launch.json containing // Azure Storage Connection String (using SAS or Key). const testLocalAzuriteInstance = true; describe("exe test", () => { const tableService = Azure.createTableService( createConnectionStringForTest(testLocalAzuriteInstance) ); tableService.enableGlobalHttpAgent = true; let tableName: string = getUniqueName("table"); const requestOverride = { headers: {} }; let childPid : number; before(async () => { overrideRequest(requestOverride, tableService); tableName = getUniqueName("table"); const child = execFile(".\\release\\azurite.exe", ["--blobPort 11000", "--queuePort 11001", "--tablePort 11002"], {cwd: process.cwd(), shell: true, env: {}}); childPid = child.pid; const fullSuccessMessage = "Azurite Blob service is starting at " + blobAddress + "\nAzurite Blob service is successfully listening at " + blobAddress + "\nAzurite Queue service is starting at " + queueAddress + "\nAzurite Queue service is successfully listening at " + queueAddress + "\nAzurite Table service is starting at " + tableAddress + "\nAzurite Table service is successfully listening at " + tableAddress + "\n"; let messageReceived : string = ""; function stdoutOn() { return new Promise(resolve => { // exclamation mark suppresses the TS error that "child.stdout is possibly null" child.stdout!.on('data', function(data: any) { messageReceived += data.toString(); if (messageReceived == fullSuccessMessage) { resolve("resolveMessage"); } }); }); } await stdoutOn(); }); after(async () => { // TO DO // Currently, the mocha test does not quit unless "--exit" is added to the mocha command // The current fix is to have "--exit" added but the issue causing mocha to be unable to // quit has not been identified restoreBuildRequestOptions(tableService); tableService.removeAllListeners(); await find('name', 'azurite.exe', true).then((list: any) => { process.kill(list[0].pid); }); process.kill(childPid); }); describe("table test", () => { it("createTable, prefer=return-no-content, accept=application/json;odata=minimalmetadata @loki", (done) => { /* Azure Storage Table SDK doesn't support customize Accept header and Prefer header, thus we workaround this by override request headers to test following 3 OData levels responses. - application/json;odata=nometadata - application/json;odata=minimalmetadata - application/json;odata=fullmetadata */ requestOverride.headers = { Prefer: "return-no-content", accept: "application/json;odata=minimalmetadata" }; tableService.createTable(tableName, (error, result, response) => { if (!error) { assert.strictEqual(result.TableName, tableName); assert.strictEqual(result.statusCode, 204); const headers = response.headers!; assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION); assert.deepStrictEqual(response.body, ""); } done(); }); }); it("queryTable, accept=application/json;odata=minimalmetadata @loki", (done) => { /* Azure Storage Table SDK doesn't support customize Accept header and Prefer header, thus we workaround this by override request headers to test following 3 OData levels responses. - application/json;odata=nometadata - application/json;odata=minimalmetadata - application/json;odata=fullmetadata */ requestOverride.headers = { accept: "application/json;odata=minimalmetadata" }; tableService.listTablesSegmented(null as any, (error, result, response) => { if (!error) { assert.strictEqual(response.statusCode, 200); const headers = response.headers!; assert.strictEqual(headers["x-ms-version"], TABLE_API_VERSION); const bodies = response.body! as any; assert.deepStrictEqual( bodies["odata.metadata"], `${PROTOCOL}://${HOST}:${PORT}/${EMULATOR_ACCOUNT_NAME}/$metadata#Tables` ); assert.ok(bodies.value[0].TableName); } done(); }); }); it("deleteTable that exists, @loki", (done) => { /* https://docs.microsoft.com/en-us/rest/api/storageservices/delete-table */ requestOverride.headers = {}; const tableToDelete = tableName + "del"; tableService.createTable(tableToDelete, (error, result, response) => { if (!error) { tableService.deleteTable(tableToDelete, (deleteError, deleteResult) => { if (!deleteError) { // no body expected, we expect 204 no content on successful deletion assert.strictEqual(deleteResult.statusCode, 204); } else { assert.ifError(deleteError); } done(); }); } else { assert.fail("Test failed to create the table"); done(); } }); }); it("deleteTable that does not exist, @loki", (done) => { // https://docs.microsoft.com/en-us/rest/api/storageservices/delete-table requestOverride.headers = {}; const tableToDelete = tableName + "causeerror"; tableService.deleteTable(tableToDelete, (error, result) => { assert.strictEqual(result.statusCode, 404); // no body expected, we expect 404 const storageError = error as any; assert.strictEqual(storageError.code, "ResourceNotFound"); done(); }); }); it("createTable with invalid version, @loki", (done) => { requestOverride.headers = { [HeaderConstants.X_MS_VERSION]: "invalid" }; tableService.createTable("test", (error, result) => { assert.strictEqual(result.statusCode, 400); done(); }); }); }); describe("blob test", () => { const factory = new BlobTestServerFactory(); const blobServer = factory.createServer(); const blobBaseURL = `http://${blobServer.config.host}:${blobServer.config.port}/devstoreaccount1`; const blobServiceClient = new BlobServiceClient( blobBaseURL, blobNewPipeline( new blobStorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 }, // Make sure socket is closed once the operation is done. keepAliveOptions: { enable: false } } ) ); let containerName: string = getUniqueName("container"); let containerClient = blobServiceClient.getContainerClient(containerName); let blobName: string = getUniqueName("blob"); let blobClient = containerClient.getBlobClient(blobName); let blockBlobClient = blobClient.getBlockBlobClient(); const content = "Hello World"; beforeEach(async () => { containerName = getUniqueName("container"); containerClient = blobServiceClient.getContainerClient(containerName); await containerClient.create(); blobName = getUniqueName("blob"); blobClient = containerClient.getBlobClient(blobName); blockBlobClient = blobClient.getBlockBlobClient(); await blockBlobClient.upload(content, content.length); }); afterEach(async () => { await containerClient.delete(); }); it("download with with default parameters @loki @sql", async () => { const result = await blobClient.download(0); assert.deepStrictEqual(await bodyToString(result, content.length), content); assert.equal(result.contentRange, undefined); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("download should work with conditional headers @loki @sql", async () => { const properties = await blobClient.getProperties(); const result = await blobClient.download(0, undefined, { conditions: { ifMatch: properties.etag, ifNoneMatch: "invalidetag", ifModifiedSince: new Date("2018/01/01"), ifUnmodifiedSince: new Date("2188/01/01") } }); assert.deepStrictEqual(await bodyToString(result, content.length), content); assert.equal(result.contentRange, undefined); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); }); describe("queue test", () => { // TODO: Create a server factory as tests utils const host = "127.0.0.1"; const port = 11001; const baseURL = `http://${host}:${port}/devstoreaccount1`; const serviceClient = new QueueServiceClient( baseURL, queueNewPipeline( new queueStorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 } } ) ); let queueName: string; let queueClient: QueueClient; beforeEach(async () => { queueName = getUniqueName("queue"); queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); }); afterEach(async () => { await queueClient.delete(); }); it("setMetadata @loki", async () => { const metadata = { key0: "val0", keya: "vala", keyb: "valb" }; const mResult = await queueClient.setMetadata(metadata); assert.equal( mResult._response.request.headers.get("x-ms-client-request-id"), mResult.clientRequestId ); const result = await queueClient.getProperties(); assert.deepEqual(result.metadata, metadata); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); it("getProperties with default/all parameters @loki", async () => { const result = await queueClient.getProperties(); assert.ok(result.approximateMessagesCount! >= 0); assert.ok(result.requestId); assert.ok(result.version); assert.ok(result.date); }); it("SetAccessPolicy should work @loki", async () => { const queueAcl = [ { accessPolicy: { expiresOn: new Date("2018-12-31T11:22:33.4567890Z"), permissions: "raup", startsOn: new Date("2017-12-31T11:22:33.4567890Z") }, id: "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=" }, { accessPolicy: { expiresOn: new Date("2030-11-31T11:22:33.4567890Z"), permissions: "a", startsOn: new Date("2017-12-31T11:22:33.4567890Z") }, id: "policy2" } ]; const sResult = await queueClient.setAccessPolicy(queueAcl); assert.equal( sResult._response.request.headers.get("x-ms-client-request-id"), sResult.clientRequestId ); const result = await queueClient.getAccessPolicy(); assert.deepEqual(result.signedIdentifiers, queueAcl); assert.equal( result._response.request.headers.get("x-ms-client-request-id"), result.clientRequestId ); }); }); });
the_stack
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- import * as _ from "lodash"; import { DeviceMapping, DeviceValueSet, FhirCodeableConcept, FhirCoding, FhirComponent, FhirMapping, FhirValue, FhirValueType, Mapping } from "../store/Mapping"; export const generateDeviceMappings = (deviceTemplates: string): Promise<Mapping[]> => { return new Promise((resolve, reject) => { let mappings: Mapping[] = []; const errorPrefix = 'Device Mapping Template error:' if (!deviceTemplates || deviceTemplates.trim().length < 1) { resolve(mappings); return; } let templates: any; try { templates = JSON.parse(deviceTemplates); } catch (err) { reject(`${errorPrefix} ${err.message}.`); return; } if (templates.template) { for (const template of templates.template) { const subTemplate = template.template; if (!subTemplate) { continue; } const typename = subTemplate.typeName; if (!typename || typename.trim().length < 1) { reject(`${errorPrefix} The type name cannot be empty.`); return; } if (_.find(mappings, { typeName: typename })) { reject(`${errorPrefix} More than one template has the typeName "${typename}". Please enter unique typeNames for these templates or remove the templates with duplicate typeNames.`); return; } let values: DeviceValueSet[] = []; if (subTemplate.values) { for (const value of subTemplate.values) { values.push({ valueExpression: value.valueExpression, valueName: value.valueName, required: value.required } as DeviceValueSet); } } const deviceMapping = { typeMatchExpression: subTemplate.typeMatchExpression, timestampExpression: subTemplate.timestampExpression, deviceIdExpression: subTemplate.deviceIdExpression, patientIdExpression: subTemplate.patientIdExpression, encounterIdExpression: subTemplate.encounterIdExpression, correlationIdExpression: subTemplate.correlationIdExpression, values: values } as DeviceMapping; const mapping = { typeName: typename, device: deviceMapping } as Mapping; mappings.push(mapping); } } resolve(mappings); return; }); } export const generateDeviceTemplate = (mappings: Mapping[]) => { const deviceTemplates = { templateType: "CollectionContent", template: [] as any } mappings.forEach(m => { const mappingTemplate = { templateType: 'JsonPathContent', template: { typeName: m.typeName, typeMatchExpression: m.device?.typeMatchExpression, timestampExpression: m.device?.timestampExpression, deviceIdExpression: m.device?.deviceIdExpression, patientIdExpression: m.device?.patientIdExpression, encounterIdExpression: m.device?.encounterIdExpression, correlationIdExpression: m.device?.correlationIdExpression, values: m.device?.values } } as any; deviceTemplates.template.push(mappingTemplate) }) return JSON.stringify(deviceTemplates, null, 4); } const generateFhirCodesMapping = (codes: any): FhirCoding[] => { let codings: FhirCoding[] = []; if (codes) { for (const code of codes) { codings.push({ code: code.code, display: code.display, system: code.system } as FhirCoding); } } return codings; } const generateFhirValueMapping = (value: any): FhirValue => { if (value) { return { valueType: value.valueType, valueName: value.valueName, sampledData: value.valueType == FhirValueType.SampledData && { defaultPeriod: value.defaultPeriod, unit: value.unit }, quantity: value.valueType == FhirValueType.Quantity && { unit: value.unit, code: value.code, system: value.system } } as FhirValue; } return {} as FhirValue; } export const generateFhirMappings = (fhirTemplates: string): Promise<Mapping[]> => { return new Promise((resolve, reject) => { let mappings: Mapping[] = []; const errorPrefix = 'FHIR Mapping Template error:' if (!fhirTemplates || fhirTemplates.trim().length < 1) { resolve(mappings); return; } let templates: any; try { templates = JSON.parse(fhirTemplates); } catch (err) { reject(`${errorPrefix} ${err.message}.`); return; } if (templates.template) { for (const template of templates.template) { const subTemplate = template.template; if (!subTemplate) { continue; } const typename = subTemplate.typeName; if (!typename || typename.trim().length < 1) { reject(`${errorPrefix} The type name cannot be empty.`); return; } if (_.find(mappings, { typeName: typename })) { reject(`${errorPrefix} More than one template has the typeName "${typename}". Please enter unique typeNames for these templates or remove the templates with duplicate typeNames.`); return; } let categories: FhirCodeableConcept[] = []; if (subTemplate.category) { for (const category of subTemplate.category) { categories.push({ text: category.text, codes: generateFhirCodesMapping(category.codes) } as FhirCodeableConcept); } } if (subTemplate.value?.valueType && subTemplate.value?.valueType == FhirValueType.CodeableConcept) { console.log(`FHIR Mapping Template note: CodeableConcept values are not supported in the Data Mapper yet. "${typename}" will be imported without a value.`) } let components: FhirComponent[] = []; if (subTemplate.components) { for (const component of subTemplate.components) { if (component.value?.valueType && component.value?.valueType == FhirValueType.CodeableConcept) { console.log(`FHIR Mapping Template note: CodeableConcept values are not supported in the Data Mapper yet. "${typename}" will be imported without CodeableConcept component values.`) } components.push({ value: generateFhirValueMapping(component.value), codes: generateFhirCodesMapping(component.codes) } as FhirComponent); } } let fhirMapping = { periodInterval: subTemplate.periodInterval, category: categories, codes: generateFhirCodesMapping(subTemplate.codes), value: generateFhirValueMapping(subTemplate.value), components: components } as FhirMapping; const mapping = { typeName: typename, fhir: fhirMapping } as Mapping; mappings.push(mapping); } } resolve(mappings); return; }); } const generateFhirValueTemplate = (fhirValue: FhirValue) => { if (fhirValue) { switch (fhirValue.valueType) { case FhirValueType.SampledData: return { valueName: fhirValue.valueName, valueType: fhirValue.valueType, ...fhirValue.sampledData } case FhirValueType.Quantity: return { valueName: fhirValue.valueName, valueType: fhirValue.valueType, ...fhirValue.quantity } case FhirValueType.String: default: return { valueName: fhirValue.valueName, valueType: fhirValue.valueType, }; } } return {}; } export const generateFhirTemplate = (mappings: Mapping[]) => { const fhirTemplates = { templateType: "CollectionFhir", template: [] as any } mappings.forEach(m => { const mappingTemplate = { templateType: "CodeValueFhir", template: { typeName: m.typeName, periodInterval: m.fhir?.periodInterval } } as any; if (m.fhir?.value) { mappingTemplate.template.value = generateFhirValueTemplate(m.fhir?.value); } if (m.fhir?.components) { mappingTemplate.template.components = []; m.fhir.components.forEach(c => mappingTemplate.template.components.push({ codes: c.codes, value: generateFhirValueTemplate(c.value) }) ); } if (m.fhir?.codes) { mappingTemplate.template.codes = m.fhir?.codes; } if (m.fhir?.category) { mappingTemplate.template.category = m.fhir?.category; } fhirTemplates.template.push(mappingTemplate) }) return JSON.stringify(fhirTemplates, null, 4); } export const sanitize = (text: string) => { var element = document.createElement('div'); element.innerText = text; return element.innerHTML; }
the_stack
import { AxiosRequestConfig, AxiosResponse } from 'axios'; import { Accounts } from './api/Accounts'; import { Events } from './api/Events'; import { Transactions } from './api/Transactions'; import { HttpClient, RequestParams } from './api/http-client'; import { HexString, MaybeHexString } from './hex_string'; import { sleep } from './util'; import { AptosAccount } from './aptos_account'; import { Types } from './types'; import { Tables } from './api/Tables'; import { AptosError } from './api/data-contracts'; import * as TxnBuilderTypes from './transaction_builder/aptos_types'; import { SigningMessage, TransactionBuilderEd25519 } from './transaction_builder'; export class RequestError extends Error { response?: AxiosResponse<any, Types.AptosError>; requestBody?: string; constructor(message?: string, response?: AxiosResponse<any, Types.AptosError>, requestBody?: string) { const data = JSON.stringify(response.data); const hostAndPath = [response.request?.host, response.request?.path].filter((e) => !!e).join(''); super(`${message} - ${data}${hostAndPath ? ` @ ${hostAndPath}` : ''}${requestBody ? ` : ${requestBody}` : ''}`); this.response = response; this.requestBody = requestBody; Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain } } export type AptosClientConfig = Omit<AxiosRequestConfig, 'data' | 'cancelToken' | 'method'>; export function raiseForStatus<T>( expectedStatus: number, response: AxiosResponse<T, Types.AptosError>, requestContent?: any, ) { if (response.status !== expectedStatus) { if (requestContent) { throw new RequestError(response.statusText, response, JSON.stringify(requestContent)); } throw new RequestError(response.statusText, response); } } export class AptosClient { nodeUrl: string; client: HttpClient; // These are the different routes accounts: Accounts; tables: Tables; events: Events; transactions: Transactions; constructor(nodeUrl: string, config?: AptosClientConfig) { this.nodeUrl = nodeUrl; // `withCredentials` ensures cookie handling this.client = new HttpClient<unknown>({ withCredentials: false, baseURL: nodeUrl, validateStatus: () => true, // Don't explode here on error responses; let our code handle it ...(config || {}), }); // Initialize routes this.accounts = new Accounts(this.client); this.tables = new Tables(this.client); this.events = new Events(this.client); this.transactions = new Transactions(this.client); } /** Returns the sequence number and authentication key for an account */ async getAccount(accountAddress: MaybeHexString): Promise<Types.Account> { const response = await this.accounts.getAccount(HexString.ensure(accountAddress).hex()); raiseForStatus(200, response); return response.data; } /** Returns transactions sent by the account */ async getAccountTransactions( accountAddress: MaybeHexString, query?: { start?: number; limit?: number }, ): Promise<Types.OnChainTransaction[]> { const response = await this.accounts.getAccountTransactions(HexString.ensure(accountAddress).hex(), query); raiseForStatus(200, response); return response.data; } /** Returns all modules associated with the account */ async getAccountModules( accountAddress: MaybeHexString, query?: { version?: Types.LedgerVersion }, ): Promise<Types.MoveModule[]> { const response = await this.accounts.getAccountModules(HexString.ensure(accountAddress).hex(), query); raiseForStatus(200, response); return response.data; } /** Returns the module identified by address and module name */ async getAccountModule( accountAddress: MaybeHexString, moduleName: string, query?: { version?: Types.LedgerVersion }, ): Promise<Types.MoveModule> { const response = await this.accounts.getAccountModule(HexString.ensure(accountAddress).hex(), moduleName, query); raiseForStatus(200, response); return response.data; } /** Returns all resources associated with the account */ async getAccountResources( accountAddress: MaybeHexString, query?: { version?: Types.LedgerVersion }, ): Promise<Types.AccountResource[]> { const response = await this.accounts.getAccountResources(HexString.ensure(accountAddress).hex(), query); raiseForStatus(200, response); return response.data; } /** Returns the resource by the address and resource type */ async getAccountResource( accountAddress: MaybeHexString, resourceType: string, query?: { version?: Types.LedgerVersion }, ): Promise<Types.AccountResource> { const response = await this.accounts.getAccountResource( HexString.ensure(accountAddress).hex(), resourceType, query, ); raiseForStatus(200, response); return response.data; } /** Generates a signed transaction that can be submitted to the chain for execution. */ static async generateBCSTransaction( accountFrom: AptosAccount, rawTxn: TxnBuilderTypes.RawTransaction, ): Promise<Uint8Array> { const txnBuilder = new TransactionBuilderEd25519((signingMessage: SigningMessage) => { // @ts-ignore const sigHexStr = accountFrom.signBuffer(signingMessage); return sigHexStr.toUint8Array(); }, accountFrom.pubKey().toUint8Array()); const signedTxn = await txnBuilder.sign(rawTxn); return signedTxn; } /** Generates a transaction request that can be submitted to produce a raw transaction that * can be signed, which upon being signed can be submitted to the blockchain. */ async generateTransaction( sender: MaybeHexString, payload: Types.TransactionPayload, options?: Partial<Types.UserTransactionRequest>, ): Promise<Types.UserTransactionRequest> { const senderAddress = HexString.ensure(sender); const account = await this.getAccount(senderAddress); return { sender: senderAddress.hex(), sequence_number: account.sequence_number, max_gas_amount: '1000', gas_unit_price: '1', gas_currency_code: 'XUS', // Unix timestamp, in seconds + 10 seconds expiration_timestamp_secs: (Math.floor(Date.now() / 1000) + 10).toString(), payload, ...(options || {}), }; } /** Converts a transaction request by `generate_transaction` into it's binary hex BCS representation, ready for * signing and submitting. * Generally you may want to use `signTransaction`, as it takes care of this step + signing */ async createSigningMessage(txnRequest: Types.UserTransactionRequest): Promise<Types.HexEncodedBytes> { const response = await this.transactions.createSigningMessage(txnRequest); raiseForStatus(200, response, txnRequest); const { message } = response.data; return message; } /** Converts a transaction request produced by `generate_transaction` into a properly signed * transaction, which can then be submitted to the blockchain. */ async signTransaction( accountFrom: AptosAccount, txnRequest: Types.UserTransactionRequest, ): Promise<Types.SubmitTransactionRequest> { const message = await this.createSigningMessage(txnRequest); const signatureHex = accountFrom.signHexString(message.substring(2)); const transactionSignature: Types.TransactionSignature = { type: 'ed25519_signature', public_key: accountFrom.pubKey().hex(), signature: signatureHex.hex(), }; return { signature: transactionSignature, ...txnRequest }; } async getEventsByEventKey(eventKey: Types.HexEncodedBytes): Promise<Types.Event[]> { const response = await this.events.getEventsByEventKey(eventKey); raiseForStatus(200, response, `eventKey: ${eventKey}`); return response.data; } async getEventsByEventHandle( address: MaybeHexString, eventHandleStruct: Types.MoveStructTagId, fieldName: string, query?: { start?: number; limit?: number }, ): Promise<Types.Event[]> { const response = await this.accounts.getEventsByEventHandle( HexString.ensure(address).hex(), eventHandleStruct, fieldName, query, ); raiseForStatus(200, response, { address, eventHandleStruct, fieldName }); return response.data; } /** Submits a signed transaction to the transaction endpoint that takes JSON payload. */ async submitTransaction(signedTxnRequest: Types.SubmitTransactionRequest): Promise<Types.PendingTransaction> { const response = await this.transactions.submitTransaction(signedTxnRequest); raiseForStatus(202, response, signedTxnRequest); return response.data; } /** Submits a signed transaction to the the endpoint that takes BCS payload. */ async submitSignedBCSTransaction(signedTxn: Uint8Array): Promise<Types.PendingTransaction> { // Need to construct a customized post request for transactions in BCS payload const httpClient = this.transactions.http; const response = await httpClient.request<Types.PendingTransaction, AptosError>({ path: '/transactions', method: 'POST', body: signedTxn, // @ts-ignore type: 'application/x.aptos.signed_transaction+bcs', format: 'json', }); raiseForStatus(202, response, signedTxn); return response.data; } async getTransactions(query?: { start?: number; limit?: number }): Promise<Types.OnChainTransaction[]> { const response = await this.transactions.getTransactions(query); raiseForStatus(200, response); return response.data; } async getTransaction(txnHashOrVersion: string): Promise<Types.Transaction> { const response = await this.transactions.getTransaction(txnHashOrVersion); raiseForStatus(200, response, { txnHashOrVersion }); return response.data; } async transactionPending(txnHash: Types.HexEncodedBytes): Promise<boolean> { const response = await this.transactions.getTransaction(txnHash); if (response.status === 404) { return true; } raiseForStatus(200, response, txnHash); return response.data.type === 'pending_transaction'; } /** Waits up to 10 seconds for a transaction to move past pending state */ async waitForTransaction(txnHash: Types.HexEncodedBytes) { let count = 0; // eslint-disable-next-line no-await-in-loop while (await this.transactionPending(txnHash)) { // eslint-disable-next-line no-await-in-loop await sleep(1000); count += 1; if (count >= 10) { throw new Error(`Waiting for transaction ${txnHash} timed out!`); } } } async getLedgerInfo(params: RequestParams = {}): Promise<Types.LedgerInfo> { const result = await this.client.request<Types.LedgerInfo, AptosError>({ path: '/', method: 'GET', format: 'json', ...params, }); return result.data; } async getChainId(params: RequestParams = {}): Promise<number> { const result = await this.getLedgerInfo(params); return result.chain_id; } async getTableItem(handle: string, data: Types.TableItemRequest, params?: RequestParams): Promise<any> { const tableItem = await this.tables.getTableItem(handle, data, params); return tableItem; } }
the_stack
import { Platform, PropertyExt, Utility } from "@hpcc-js/common"; import { Modal, Surface } from "@hpcc-js/layout"; import { Persist } from "@hpcc-js/other"; import { map as d3Map } from "d3-collection"; import { select as d3Select } from "d3-selection"; import { FlyoutButton } from "./FlyoutButton"; import * as HipieDDL from "./HipieDDL"; const tpl = "<!doctype html><html><head><meta charset='utf-8'>" + "<script src='http://viz.hpccsystems.com/v1.14.0-rc5/dist-amd/hpcc-viz.js'></script>" + "<script src='http://viz.hpccsystems.com/v1.14.0-rc5/dist-amd/hpcc-viz-common.js'></script>" + "</head>" + "<body style='padding:0px; margin:0px; overflow:hidden'><div id='placeholder' style='width:100%; height:100vh'></div><script>" + " require(['src/other/Persist'], function (Persist) {\n" + " Persist.create({STATE}).then(function(widget) {\n" + " widget\n" + " .target('placeholder')\n" + " .ddlUrl('{DDL}')\n" + " .databomb('{DATABOMB}')\n" + " .render()\n" + " ;\n" + " });\n" + " });" + "</script></body></html>"; export class HipieDDLMixin extends PropertyExt { _ddlDashboards; _ddlVisualizations; _ddlPopupVisualizations; _ddlLayerVisualizations; _ddlModalVisualizations; _prev_ddlUrl; _prev_databomb; _marshaller; _initialState; constructor() { super(); PropertyExt.call(this); } _gatherDashboards(marshaller, databomb) { if (databomb instanceof Object) { } else if (databomb) { databomb = JSON.parse(databomb); } this._ddlDashboards = []; this._ddlVisualizations = []; this._ddlPopupVisualizations = []; this._ddlLayerVisualizations = []; this._ddlModalVisualizations = []; const context = this; let curr = null; marshaller.accept({ visit: (item) => { if (item instanceof HipieDDL.Dashboard) { curr = { dashboard: item, visualizations: [], popupVisualizations: [], layerVisualizations: [], modalVisualizations: [] }; context._ddlDashboards.push(curr); } else if (item instanceof HipieDDL.Datasource) { if (item.databomb && databomb[item.id]) { item.comms.databomb(databomb[item.id]); } } else if (item instanceof HipieDDL.Output) { if (item.datasource.databomb) { item.datasource.comms.databombOutput(item.from, item.id); } } else if (item instanceof HipieDDL.Visualization) { if (item.widget) { if (item.properties.flyout) { curr.popupVisualizations.push(item); context._ddlPopupVisualizations.push(item); } else if (item.parentVisualization) { curr.layerVisualizations.push(item); context._ddlLayerVisualizations.push(item); } else if (item.properties.modalIfData && !context.disableModals()) { curr.modalVisualizations.push(item); context._ddlModalVisualizations.push(item); } else { curr.visualizations.push(item); context._ddlVisualizations.push(item); } } } } }); } _marshallerRender(BaseClass, callback) { if (this.ddlUrl() === "" || (this.ddlUrl() === this._prev_ddlUrl && this.databomb() === this._prev_databomb)) { if (this._marshaller) { this._marshaller .proxyMappings(this.proxyMappings()) .timeout(this.timeout()) .clearDataOnUpdate(this.clearDataOnUpdate()) .propogateClear(this.propogateClear()) .missingDataString(this.missingDataString()) ; } return BaseClass.render.call(this, function (widget) { if (callback) { callback(widget); } }); } if (this._prev_ddlUrl && this._prev_ddlUrl !== this.ddlUrl()) { // DDL has actually changed (not just a deserialization) this .clearContent() ; } this._prev_ddlUrl = this.ddlUrl(); this._prev_databomb = this.databomb(); // Gather existing widgets for reuse --- const widgetArr = []; Persist.widgetArrayWalker(this.content(), function (w) { widgetArr.push(w); }); const widgetMap = d3Map(widgetArr, function (d) { return d.id(); }); const removedMap = d3Map(widgetArr.filter(function (d) { return d.id().indexOf(d._idSeed) !== 0 && d.id().indexOf("_pe") !== 0; }), function (d) { return d.id(); }); const context = this; this._marshaller = new HipieDDL.Marshaller() .proxyMappings(this.proxyMappings()) .clearDataOnUpdate(this.clearDataOnUpdate()) .propogateClear(this.propogateClear()) .missingDataString(this.missingDataString()) .widgetMappings(widgetMap) .on("commsEvent", function (source, error) { context.commsEvent.apply(context, arguments); }) .on("vizEvent", function () { context.vizEvent.apply(context, arguments); }) ; // Parse DDL --- if (this.ddlUrl()[0] === "[" || this.ddlUrl()[0] === "{") { this._marshaller.parse(this.ddlUrl(), postParse); } else { this._marshaller.url(this.ddlUrl(), postParse); } function postParse() { context._gatherDashboards(context._marshaller, context.databomb()); // Remove existing widgets not used and prime popups --- context._ddlVisualizations.forEach(function (viz) { removedMap.remove(viz.id); if (!context._marshaller.widgetMappings().get(viz.id)) { // New widget --- viz.newWidgetSurface = null; if (viz.widget instanceof Surface || viz.widget.classID() === "composite_MegaChart") { viz.newWidgetSurface = viz.widget; } else { viz.newWidgetSurface = new Surface() .widget(viz.widget) ; } viz.newWidgetSurface.title(viz.title); viz.widget.size({ width: 0, height: 0 }); } }); context._ddlPopupVisualizations.forEach(function (viz) { removedMap.remove(viz.id); viz.widget.classed({ flyout: true }); const targetVizs = viz.events.getUpdatesVisualizations(); targetVizs.forEach(function (targetViz) { switch (targetViz.widget.classID()) { case "composite_MegaChart": if (!viz._flyoutButton) { viz._flyoutButton = new FlyoutButton() .classed({ "composite_MegaChart-flyout": true }) .title(viz.title) .widget(viz.widget) .autoClose(context.autoCloseFlyout()) ; targetViz.widget.toolbarWidgets().push(viz._flyoutButton); } else { targetViz.widget.toolbarWidgets().push(viz._flyoutButton.reference()); } break; } }); }); context._ddlModalVisualizations.forEach(function (viz) { if (viz.widget.showCSV) { viz.widget.showToolbar(true); } else if (viz.widget.showToolbar) { viz.widget.showToolbar(false); } viz._modalTarget = d3Select("body").append("div").node(); viz._modal = new Modal().target(viz._modalTarget) .overflowX("hidden") .overflowY("hidden") ; viz._modal._widget = viz.widget; const origRender = viz.widget.render; viz.widget.render = function (callback) { if (this.__inModal) { return origRender.apply(this, arguments); } if (this.data().length) { this.__inModal = true; const widgetContext = this; const modalTitle = viz.widget.title(); if (viz.widget.showToolbar()) { viz.widget.titleFontColor("transparent"); } viz._modal .title(modalTitle) .visible(true) .fixedWidth("80%") .fixedHeight("80%") .render(function (w) { if (callback) { callback(widgetContext); } setTimeout(function () { widgetContext.__inModal = false; }, 300); // Must be longer than debounce timeout... }); } else { if (callback) { callback(this); } } return this; }; }); removedMap.each(function (key, value) { context.clearContent(value); }); context.populateContent(); if (context._initialState) { context._marshaller.deserializeState(context._initialState.marshaller); delete context._initialState; BaseClass.render.call(context, callback); } else { BaseClass.render.call(context, function (widget) { context._marshaller.primeData().then(function (response) { if (callback) { callback(widget); } }); }); } } } primeData(state) { if (this._marshaller) { return this._marshaller.primeData(state); } return Promise.resolve(); } dashboards() { const retVal = {}; for (const key in this._marshaller.dashboards) { retVal[key] = {}; this._marshaller.dashboards[key].visualizations.forEach(function (ddlViz) { retVal[key][ddlViz.id] = ddlViz.widget; }, this); } return retVal; } visualizations() { return this._marshaller._visualizationArray.map(function (ddlViz) { return ddlViz.newWidgetSurface || ddlViz.widget; }); } generateTestPage() { if (this._marshaller) { const context = this; const state = Persist.serialize(context, function (widget, publishItem) { if (publishItem.id === "databomb" || publishItem.id === "ddlUrl") { return true; } return false; }); const databomb = this._marshaller.createDatabomb(); const page = tpl .replace("{VERSION}", Platform.version()) .replace("{STATE}", state) .replace("{DDL}", context._marshaller._json.replace("WUID", "databomb")) .replace("{DATABOMB}", JSON.stringify(databomb)) ; Utility.downloadString("TEXT", page, "test"); } } vizEvent(sourceWidget, eventID, row, col, selected) { } commsEvent(ddlSource, eventID, request, response) { } state(_) { if (!arguments.length) { return this.serializeState(); } this.deserializeState(_); return this; } serializeState() { return { marshaller: this._marshaller ? this._marshaller.serializeState() : {} }; } deserializeState(state) { if (this._marshaller) { this._marshaller.deserializeState(state.marshaller); } else { this._initialState = state; } return this; } serializeRequests() { let retVal = null; this._ddlPopupVisualizations.concat(this._ddlVisualizations).forEach(function (ddlViz) { if (ddlViz.hasSelection()) { if (!retVal) { retVal = {}; } retVal[ddlViz.id] = ddlViz.reverseMappedSelection(); } }); return retVal; } // HipieDDLMixin abstract methods --- content: () => this; populateContent: () => this; clearContent: (value?) => this; ddlUrl: { (): string; (_: string): HipieDDLMixin }; ddlUrl_exists: () => boolean; databomb: { (): string; (_: string): HipieDDLMixin }; databomb_exists: () => boolean; proxyMappings: { (): object; (_: object): HipieDDLMixin }; proxyMappings_exists: () => boolean; timeout: { (): number; (_: number): HipieDDLMixin }; timeout_exists: () => boolean; clearDataOnUpdate: { (): boolean; (_: boolean): HipieDDLMixin }; clearDataOnUpdate_exists: () => boolean; propogateClear: { (): boolean; (_: boolean): HipieDDLMixin }; propogateClear_exists: () => boolean; missingDataString: { (): string; (_: string): HipieDDLMixin }; missingDataString_exists: () => boolean; autoCloseFlyout: { (): boolean; (_: boolean): HipieDDLMixin }; autoCloseFlyout_exists: () => boolean; disableModals: { (): boolean; (_: boolean): HipieDDLMixin }; } HipieDDLMixin.prototype.mixin(PropertyExt); HipieDDLMixin.prototype._class += " marshaller_HipieDDLMixin"; HipieDDLMixin.prototype.publish("ddlUrl", "", "string", "DDL URL", null, { tags: ["Private"] }); HipieDDLMixin.prototype.publish("databomb", "", "string", "Data Bomb", null, { tags: ["Private"] }); HipieDDLMixin.prototype.publish("proxyMappings", {}, "object", "Proxy Mappings", null, { tags: ["Private"] }); HipieDDLMixin.prototype.publish("timeout", null, "number", "Timout (seconds)", null, { optional: true }); HipieDDLMixin.prototype.publish("clearDataOnUpdate", true, "boolean", "Clear data prior to refresh", null); HipieDDLMixin.prototype.publish("propogateClear", false, "boolean", "Propogate clear to dependent visualizations", null); HipieDDLMixin.prototype.publish("missingDataString", "***MISSING***", "string", "Missing data display string"); HipieDDLMixin.prototype.publish("autoCloseFlyout", true, "boolean", "Auto Close Flyout Filters"); HipieDDLMixin.prototype.publish("disableModals", false, "boolean", "If true, widgets with 'modalIfData' will display as standard Grid widgets");
the_stack
import { $Children } from '../component/Children' import { Moment } from '../debug/Moment' import { UnitMoment } from '../debug/UnitMoment' import { $Component } from '../interface/async/$Component' import { $Graph } from '../interface/async/$Graph' import { NOOP } from '../NOOP' import { Pod } from '../pod' import { evaluate } from '../spec/evaluate' import { ComponentClass, System } from '../system' import { pushGlobalComponent } from '../system/globalComponent' import { GraphSpec } from '../types' import { Callback } from '../types/Callback' import { Dict } from '../types/Dict' import { Unlisten } from '../types/Unlisten' import { at, insert, pull, push, remove, removeAt, unshift, } from '../util/array' import callAll from '../util/call/callAll' import { _if } from '../util/control' import { appendChild, insertBefore, prepend, removeChild, } from '../util/element' import { get, mapObjVK, set } from '../util/object' import { addListener, addListeners } from './addListener' import { componentClassFromSpecId } from './componentClassFromSpecId' import { componentFromSpecId } from './componentFromSpecId' import { component_ } from './component_' import { Context, dispatchContextEvent, dispatchCustomEvent } from './context' import { DEFAULT_FONT_SIZE, DEFAULT_OPACITY, DEFAULT_TEXT_ALIGN, } from './DEFAULT_FONT_SIZE' import { IOElement } from './IOElement' import { Listener } from './Listener' import { makeEventListener } from './makeEventListener' import { mount } from './mount' import parentElement from './platform/web/parentElement' import { unmount } from './unmount' import { addVector, NULL_VECTOR, Position, Rect } from './util/geometry' import { getFontSize } from './util/style/getFontSize' import { getOpacity } from './util/style/getOpacity' import { getPosition } from './util/style/getPosition' import { getSize } from './util/style/getSize' import { getTextAlign } from './util/style/getTextAlign' export type ComponentMap = Dict<Component> export function componentClassFromSpec(spec: GraphSpec): ComponentClass { const { id, name, units = {}, component = { defaultWidth: 120, defaultHeight: 120 }, } = spec const { children = [], subComponents = {}, slots = [] } = component class Parent extends Component<any, any> { static id = id constructor($props: {}, $system: System, $pod: Pod) { super($props, $system, $pod) const $subComponent: Dict<Component> = {} for (const unitId in subComponents) { const unitSpec = units[unitId] const { id } = unitSpec const Class = componentClassFromSpecId($system, id) const childComponent: Component = new Class({}, $system, $pod) $subComponent[unitId] = childComponent } const fillParentRoot = (unitId: string): void => { const component = $subComponent[unitId] const subComponentSpec = subComponents[unitId] const { children = [], childSlot = {} } = subComponentSpec for (const childUnitId of children) { fillParentRoot(childUnitId) const slot = childSlot[childUnitId] || 'default' const childRoot: Component = $subComponent[childUnitId] component.registerParentRoot(childRoot, slot) } } const $element = parentElement($system) this.$element = $element this.$primitive = false this.$subComponent = $subComponent let i = 0 for (const _slot of slots) { const [slot, slotSlot] = _slot const subComponent = $subComponent[slot] // AD HOC const slotName = i === 0 ? 'default' : `${i}` this.$slot[slotName] = subComponent.$slot[slotSlot] i++ } for (let child_id of children) { const rootComponent = $subComponent[child_id] fillParentRoot(child_id) this.registerRoot(rootComponent) } } } Object.defineProperty(Parent, 'name', { value: name, }) return Parent as ComponentClass } export function findRef(component: Component, name: string): Component | null { let c: Component | null = component while (c) { if (c.$ref[name]) { return c.$ref[name] } c = c.$parent } return null } export class Component< E extends IOElement = IOElement, P extends Dict<any> = {}, U extends $Component | $Graph = $Component > { static id: string public $_: string[] = [] public $element: E public $props: P public $changed: Set<string> = new Set() public $system: System public $pod: Pod public $globalId: string public $ref: Dict<Component> = {} public $context: Context public $connected: boolean = false public $unit: U public $primitive: boolean = true // AD HOC // Avoid recursively connecting "JavaScript Defined Components" public $unbundled: boolean = true public $children: Component[] = [] public $slotChildren: Dict<Component[]> = { default: [] } public $childrenSlot: string[] = [] public $slot: Dict<Component> = { default: this } public $subComponent: Dict<Component> = {} public $root: Component[] = [] public $parentRoot: Component[] = [] public $parentRootSlot: string[] = [] public $mountRoot: Component[] = [] public $mountParentRoot: Component[] = [] public $parentChildren: Component[] = [] public $parentChildrenSlot: string[] = [] public $parent: Component | null = null public $mounted: boolean = false public $listenCount: Dict<number> = {} constructor($props: P, $system: System, $pod: Pod) { this.$props = $props this.$system = $system this.$pod = $pod } getProp(name: string): any { return this.$props[name] } setProp<K extends keyof P>(prop: K, data: P[K]) { this.$props[prop] = data if (this.$mounted) { this.onPropChanged(prop, data) } else { this.$changed.add(prop) } } getSlot(slotName: string): Component { return this.$slot[slotName] } onPropChanged(prop: string, current: any) {} onConnected($unit: U) {} onDisconnected() {} onMount() {} onUnmount($context: Context) {} onDestroy() {} dispatchEvent(type: string, detail: any = {}, bubbles: boolean = true) { dispatchCustomEvent(this.$element, type, detail, bubbles) } dispatchContextEvent(type: string, data: any = {}) { if (this.$context) { dispatchContextEvent(this.$context, type, data) } } stopPropagation(event: string): void { this.$element.addEventListener( event, function (event: Event) { event.stopPropagation() }, { passive: true } ) } stopImmediatePropagation(event: string): void { this.$element.addEventListener( event, function (event: Event) { event.stopImmediatePropagation() }, { passive: true } ) } preventDefault(event: string): void { this.$element.addEventListener( event, (event: Event) => { event.preventDefault() return false }, { passive: false } ) } setPointerCapture(pointerId: number): void { // console.log(this.constructor.name, 'setPointerCapture', pointerId) try { if (this.$element instanceof Text) { return } this.$element.setPointerCapture(pointerId) } catch (err) { return } this.$system.cache.pointerCapture[pointerId] = this.$element } releasePointerCapture(pointerId: number): void { // console.log(this.constructor.name, 'releasePointerCapture', pointerId) // AD HOC try { if (this.$element instanceof Text) { return } this.$element.releasePointerCapture(pointerId) } catch (err) { // swallow return } delete this.$system.cache.pointerCapture[pointerId] } public mountDescendent(child: Component): void { child.mount(this.$context) } public unmountDescendent(child: Component): void { return child.unmount() } private _forAllDescendent(callback: Callback<Component>): void { for (const subComponent of this.$mountRoot) { callback(subComponent) } for (const subComponent of this.$mountParentRoot) { callback(subComponent) } for (const child of this.$children) { callback(child) } } mount($context: Context): void { // console.log(this.constructor.name, 'mount') if (this.$mounted) { throw new Error('Cannot mount a mounted component.') this.unmount() } this.$context = $context this.$mounted = true this.onMount() this._forAllDescendent((child) => { this.mountDescendent(child) }) const $changed = new Set(this.$changed) for (const name of $changed) { const current = this.$props[name] this.$changed.delete(name) this.onPropChanged(name, current) } if (this.$listenCount['mount']) { this.dispatchEvent('mount', {}, false) } } unmount() { // console.log(this.constructor.name, 'unmount') if (!this.$mounted) { // throw new Error('Cannot unmount unmounted component') return } const $context = this.$context this._forAllDescendent((child) => { this.unmountDescendent(child) }) this.$mounted = false this.$context = null this.onUnmount($context) if (this.$listenCount['unmount']) { this.dispatchEvent('unmount', {}, false) } } focus(options: FocusOptions | undefined = { preventScroll: true }) { if (this.$slot['default'] === this) { if (this.$element instanceof Text) { return } this.$element.focus(options) } else { this.$slot['default'].focus(options) } } blur() { if (this.$slot['default'] === this) { if (this.$element instanceof Text) { return } this.$element.blur() } else { this.$slot['default'].blur() } } deselect(): void { const { api: { selection: { removeSelection }, }, } = this.$system if (this.containsSelection()) { removeSelection() } } containsSelection(): boolean { const { api: { selection: { containsSelection }, }, } = this.$system return containsSelection(this.$element) } animate(keyframes, options): Animation { if (this.$slot['default'] === this) { if (this.$element instanceof Text) { // RETURN return } return this.$element.animate(keyframes, options) } else { return this.$slot['default'].animate(keyframes, options) } } getOffset(): Component { let slot_offset: Component = this while ( slot_offset && (!(slot_offset.$element instanceof HTMLElement) || slot_offset.$element.style.position === '' || slot_offset.$element.style.position === 'contents') && slot_offset.$element instanceof HTMLElement && slot_offset.$element.style.display !== 'flex' ) { slot_offset = slot_offset.$parent } return slot_offset } getElementPosition() { if (!this.$mounted) { throw new Error('Cannot calculate position of unmounted component') } const context_position = { x: this.$context.$x, y: this.$context.$y, } const relative_position = getPosition(this.$element, this.$context.$element) const position = addVector(context_position, relative_position) return position } getElementSize() { return getSize(this.$element) } getFontSize(): number { const fontSize = getFontSize(this.$element) if (fontSize) { return fontSize } if (this.$parent) { return this.$parent.getFontSize() } return DEFAULT_FONT_SIZE } getOpacity(): number { const opacity = getOpacity(this.$element) if (opacity) { return opacity } if (this.$parent) { return this.$parent.getOpacity() } return DEFAULT_OPACITY } getTextAlign(): string { const fontSize = getTextAlign(this.$element) if (fontSize) { return fontSize } if (this.$parent) { return this.$parent.getTextAlign() } return DEFAULT_TEXT_ALIGN } getRootPosition(rootId: string): Position { // TODO return NULL_VECTOR } getParentRootPosition( subComponentId: string, parentRootId: string ): Position { // TODO return NULL_VECTOR } getRootBase(path: string[] = []): [string[], Component][] { if (this.$primitive && this.$root.length === 0) { return [[path, this]] } let p = [] for (const subComponent of this.$root) { const subComponentId = this.getSubComponentId(subComponent) const subComponentPrim = subComponent.getRootBase([ ...path, subComponentId, ]) p = [...p, ...subComponentPrim] } return p } getBase(path: string[] = []): [string[], Component][] { if (this.$primitive && this.$root.length === 0) { return [[path, this]] } let p = [] const appendSubComponent = (subComponent: Component) => { const subComponentId = this.getSubComponentId(subComponent) const subComponentRootBase = subComponent.getRootBase([ ...path, subComponentId, ]) p = [...p, ...subComponentRootBase] for (const _subComponent of subComponent.$parentRoot) { appendSubComponent(_subComponent) } } for (const subComponent of this.$root) { appendSubComponent(subComponent) } return p } pathGetSubComponent(path: string[]): Component { if (path.length == 0) { return this } else { const [head, ...tail] = path const subComponent = this.getSubComponent(head) return subComponent.pathGetSubComponent(tail) } } getBoundingClientRect(): { x: number y: number width: number height: number } { if (this.$context) { if (this.$element instanceof Text) { // RETURN return } const { $x, $y, $sx, $sy } = this.$context const bcr: Rect = this.$element.getBoundingClientRect() const { x, y, width, height } = bcr return { x: (x - $x) / $sx, y: (y - $y) / $sy, width: width / $sx, height: height / $sy, } } else { throw new Error('component not mounted') } } public appendChild(child: Component, slotName: string = 'default'): number { // console.log('Component', 'appendChild', slotName) const at = this.$children.length this.memAppendChild(child, slotName, at) this.domAppendChild(child, slotName, at) this.postAppendChild(child, at) return at } public memAppendChild(child: Component, slotName: string, at: number): void { // console.log('Component', 'memAppendChild') this.$slotChildren[slotName] = this.$slotChildren[slotName] || [] this.$slotChildren[slotName].push(child) this.$children.push(child) this.$childrenSlot[at] = slotName } public domAppendChild(child: Component, slotName: string, at: number): void { // console.log('Component', '_domAppendChild') const slot = this.$slot[slotName] slot.$element.appendChild(child.$element) } public postAppendChild(child: Component, at: number): void { child.$parent = this if (this.$mounted) { this.mountDescendent(child) } } public domRemoveChild(child: Component, slotName: string, at: number): void { const slot = this.$slot[slotName] slot.$element.removeChild(child.$element) } public postRemoveChild(child: Component, at: number): void { child.$parent = null if (this.$mounted) { child.unmount() } } public hasChild(at: number): boolean { const has = this.$children.length > at return has } public ascendChild(child: Component, slotName: string = 'default'): void { this.removeChild(child) this.appendChild(child, slotName) } public $listener: Listener[] = [] public $unlisten: Unlisten[] = [] public $named_listener_count: Dict<number> = {} public $named_unlisten: Dict<Unlisten> = {} private _unit_unlisten: Unlisten private _addUnitEventListener = (event: string): void => { const unlisten = this.addEventListener( makeEventListener(event, (data) => { this.$unit.$refEmitter({}).$emit({ type: event, data }, NOOP) }) ) this.$named_unlisten[event] = unlisten } private _removeUnitEventListener = (event: string): void => { const unlisten = this.$named_unlisten[event] delete this.$named_unlisten[event] unlisten() } public connect($unit: U): void { if (this.$connected) { // throw new Error ('Component is already connected') console.log('Component', 'connect called unnecessarily') return } this._connect($unit) if (this.$unbundled) { for (let unitId in this.$subComponent) { const childSubComponent = this.$subComponent[unitId] const _ = component_(childSubComponent) const subUnit = (this.$unit as $Graph).$refSubComponent({ unitId, _ }) childSubComponent.connect(subUnit) } } } public _connect($unit: U): void { // console.log(this.constructor.name, 'connect') if (this.$connected) { // throw new Error ('Component is already connected') // console.log('Component', 'connect called unnecessarily') return } this.$unit = $unit const listen = (event: string): void => { this.$named_listener_count[event] = this.$named_listener_count[event] || 0 this.$named_listener_count[event]++ if (!this.$named_unlisten[event]) { this._addUnitEventListener(event) } } const unlisten = (event: string): void => { this.$named_listener_count[event]-- if (this.$named_listener_count[event] === 0) { this._removeUnitEventListener(event) } } const handler = { unit: (moment: UnitMoment) => { const { event: event_event, data: event_data } = moment // if (event_event === 'call') { // const { method, data } = event_data // this._call(method, data) // } else if (event_event === 'listen') { // const { event } = event_data // listen(event) // } else if (event_event === 'unlisten') { // const { event } = event_data // unlisten(event) // } else if (event_event === 'append_child') { const { bundle } = event_data const { unit } = bundle const { id, input = {} } = unit const props = mapObjVK(input, ({ data }) => { return evaluate(data, this.$system.specs, this.$system.classes) }) const child = componentFromSpecId(this.$system, this.$pod, id, props) const _ = component_(child) const at = this.$children.length const child_unit = this.$unit.$refChild({ at, _ }) child.connect(child_unit) const slot_name = 'default' this.appendChild(child, slot_name) } else if (event_event === 'remove_child_at') { const { at } = event_data this.removeChildAt(at) } }, } const pod_unit_listener = (moment: Moment): void => { const { type } = moment handler[type] && handler[type](moment) } this.$named_listener_count = {} $unit.$getGlobalId({}, (__global_id: string) => { this.$globalId = __global_id pushGlobalComponent(this.$system, __global_id, this) }) const all_unlisten: Unlisten[] = [] const events = [ // 'call', // 'listen', // 'unlisten', 'append_child', 'remove_child_at', ] const pod_unit_unlisten = this.$unit.$watch({ events }, pod_unit_listener) all_unlisten.push(pod_unit_unlisten) const $emitter = $unit.$refEmitter({}) $emitter.$getEventNames({}, (events: string[]) => { for (const event of events) { listen(event) } }) const unlisten_emitter = callAll([ $emitter.$addListener({ event: 'listen' }, ({ event }) => { listen(event) }), $emitter.$addListener({ event: 'unlisten' }, ({ event }) => { unlisten(event) }), $emitter.$addListener({ event: 'call' }, ({ method, data }) => { this._call(method, data) }), ]) all_unlisten.push(unlisten_emitter) this._unit_unlisten = callAll(all_unlisten) $unit.$children({}, (children: $Children) => { if (children.length > 0) { const _children = children.map(({ id }, at) => { const component = componentFromSpecId(this.$system, this.$pod, id, {}) const _ = component_(component) const unit = $unit.$refChild({ at, _ }) component.connect(unit) return component }) this.setChildren(_children) } }) this.$connected = true this.onConnected($unit) } public disconnect(): void { this._disconnect() if (this.$unbundled) { for (let subUnitId in this.$subComponent) { const childSubComponent = this.$subComponent[subUnitId] childSubComponent.disconnect() } } } public _disconnect(): void { // console.log(this.constructor.name, 'disconnect') if (!this.$connected) { // throw new Error ('Component is not already disconnected') console.log('Component', 'disconnect called unnecessarily') return } this._unit_unlisten() for (const child of this.$children) { child.disconnect() } this.$connected = false this.onDisconnected() } public prependChild(child: Component, slotName: string = 'default') { const slot = this.$slot[slotName] this.$slotChildren[slotName] = this.$slotChildren[slotName] || [] this.$slotChildren[slotName].unshift(child) child.$parent = this if (slot.$element instanceof Text) { // } else { slot.$element.prepend(child.$element) } if (this.$mounted) { this.mountDescendent(child) } } public insertAt( child: Component, at: number, slotName: string = 'default' ): void { const slot = this.$slot[slotName] this.$slotChildren[slotName] = this.$slotChildren[slotName] || [] if (at >= this.$slotChildren[slotName].length - 1) { this.appendChild(child, slotName) } else { child.$parent = this slot.$element.insertBefore( child.$element, this.$slotChildren[slotName][at].$element ) this.$slotChildren[slotName].splice(at, 0, child) if (this.$mounted) { this.mountDescendent(child) } } } public setChildren( children: Component[] = [], slotNames: string[] = [] ): void { const oldChildren = [...this.$children] for (const oldChild of oldChildren) { this.removeChild(oldChild) } for (let i = 0; i < children.length; i++) { const child = children[i] const slotName = slotNames[i] this.appendChild(child, slotName) } } public memRemoveChildAt( child: Component, slotName: string, at: number ): void { remove(this.$slotChildren[slotName], child) removeAt(this.$children, at) removeAt(this.$childrenSlot, at) } public removeChildAt(at: number): number { const child = this.$children[at] const slotName = this.$childrenSlot[at] this.memRemoveChildAt(child, slotName, at) this.domRemoveChild(child, slotName, at) this.postRemoveChild(child, at) return at } public removeChild(child: Component): number { // console.log('Component', 'removeChild') const at = this.$children.indexOf(child) if (at > -1) { return this.removeChildAt(at) } else { throw new Error('child component not found') } } public removeChildren(): void { const children = [...this.$children] for (const child of children) { this.removeChild(child) } } public hasRoot(component: Component): boolean { return this.$root.includes(component) } public pushRoot(component: Component): void { set(component, '$parent', this) this.$root.push(component) } public pullRoot(component: Component): void { const index = this.$root.indexOf(component) if (index > -1) { set(component, '$parent', null) this.$root.splice(index, 1) } else { throw new Error('Cannot pull; not root component') } } public fitRoot(component: Component, at: number): void { this.$root.splice(at, 0, component) } public prependRoot(component: Component): void { unshift(this.$root, component) prepend(this.$element, component.$element) _if(this.$mounted, mount, component, this.$context) } public registerRoot(component: Component): void { this.pushRoot(component) this.appendRoot(component) } public registerRootAt(component: Component, at: number): void { insert(this.$root, component, at) this.insertRootAt(component, at) } public unregisterRoot(component: Component): void { this.pullRoot(component) this.removeRoot(component) } public memAppendRoot(component: Component): void { push(this.$mountRoot, component) } public postAppendRoot(component: Component): void { set(component, '$parent', this) _if(this.$mounted, mount, component, this.$context) } public domAppendRoot(component: Component): void { appendChild(this.$element, component.$element) } public appendRoot(component: Component): void { const at = this.$mountRoot.length this.memAppendRoot(component) this.domAppendRoot(component) this.postAppendRoot(component) } public insertRootAt(component: Component, _at: number): void { insert(this.$mountRoot, component, _at) const nextRoot = at(this.$root, _at + 1) insertBefore(this.$element, component.$element, nextRoot.$element) set(component, '$parent', this) this.$mounted && this.mountDescendent(component) } public removeRoot(component: Component): void { pull(this.$mountRoot, component) removeChild(this.$element, component.$element) _if(this.$mounted, unmount, component) } public compose(): void { for (const component of this.$root) { component.collapse() this.appendRoot(component) } } public decompose(): void { for (const component of this.$root) { component.uncollapse() this.removeRoot(component) } } public hasParentRoot(component: Component): boolean { return this.$parentRoot.includes(component) } public pushParentRoot(component: Component, slotName: string): void { push(this.$parentRoot, component) push(this.$parentRootSlot, slotName) } public insertParentRoot( component: Component, at: number, slotName: string ): void { insert(this.$parentRoot, component, at) insert(this.$parentRootSlot, slotName, at) } public unshiftParentRoot(component: Component, slotName: string): void { unshift(this.$parentRoot, component) unshift(this.$parentRootSlot, slotName) } public pullParentRoot(component: Component): void { const i = this.$parentRoot.indexOf(component) if (i > -1) { removeAt(this.$parentRoot, i) removeAt(this.$parentRootSlot, i) } else { throw new Error('Parent Root not found') } } public registerParentRoot( component: Component, slotName: string = 'default' ): void { this.pushParentRoot(component, slotName) this.appendParentRoot(component, slotName) } public unregisterParentRoot(component: Component): void { // console.log('unregisgerParentRoot') this.removeParentRoot(component) this.pullParentRoot(component) } public collapse(): void { let i = 0 for (const component of this.$parentRoot) { const slotName = this.$parentRootSlot[i] component.collapse() this.appendParentRoot(component, slotName) i++ } } public uncollapse(): void { for (const component of this.$parentRoot) { this.removeParentRoot(component) component.uncollapse() } } public appendParentRoot( component: Component, slotName: string = 'default' ): void { // console.log( // this.constructor.name, // 'appendParentRoot', // component.constructor.name // ) const at = this.$parentRoot.indexOf(component) this.memAppendParentRoot(component, slotName, at) this.domAppendParentRoot(component, slotName, at) this.postAppendParentRoot(component, slotName, at) } public memAppendParentRoot( component: Component, slotName: string, at: number ): void { push(this.$mountParentRoot, component) const slot = get(this.$slot, slotName) slot.memAppendParentChild(component, 'default', at, at) } public domAppendParentRoot( component: Component, slotName: string, at: number ): void { const slot = get(this.$slot, slotName) slot.domAppendParentChildAt(component, 'default', at, at) } public postAppendParentRoot( component: Component, slotName: string, at: number ): void { const slot = get(this.$slot, slotName) slot.postAppendParentChild(component, slotName, at) set(component, '$parent', this) // _if(this.$mounted, mount, component, this.$context) } public memAppendParentChild( component: Component, slotName: string, at: number, _at: number ): void { push(this.$parentChildren, component) push(this.$parentChildrenSlot, slotName) } public domAppendParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { appendChild(this.$element, component.$element) } public postAppendParentChild( component: Component, slotName: string, at: number ): void { if (this.$mounted) { this.mountDescendent(component) } } public insertParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { const slot = this.$slot[slotName] if (this === slot) { this.memInsertParentChildAt(component, slotName, at, _at) this.domInsertParentChildAt(component, slotName, at, _at) } else { slot.insertParentChildAt(component, 'default', at, _at) } } public memInsertParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { insert(this.$parentChildren, component, _at) insert(this.$parentChildrenSlot, slotName, _at) } public domInsertParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { const slot = this.$slot[slotName] const nextElement = slot.$element.childNodes[_at] insertBefore(slot.$element, component.$element, nextElement) } public removeParentChild( component: Component, slotName: string = 'default', at: number ): void { const slot = this.$slot[slotName] if (slot === this) { const _at = this.$parentChildren.indexOf(component) this.domRemoveParentChildAt(component, slotName, at, _at) this.memRemoveParentChildAt(component, slotName, at, _at) } else { slot.removeParentChild(component, 'default', at) } } public memRemoveParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { removeAt(this.$parentChildren, _at) removeAt(this.$parentChildrenSlot, _at) } public domRemoveParentChildAt( component: Component, slotName: string, at: number, _at: number ): void { removeChild(this.$element, component.$element) } public insertParentRootAt( component: Component, at: number, slotName: string ): void { this.memInsertParentRootAt(component, at, slotName) this.domInsertParentRootAt(component, at, slotName) this.postInsertParentRootAt(component, at, slotName) } public memInsertParentRootAt( component: Component, at: number, slotName: string ): void { insert(this.$mountParentRoot, component, at) } public domInsertParentRootAt( component: Component, _at: number, slotName: string ): void { const slot = get(this.$slot, slotName) const at = this.$parentRoot.indexOf(component) slot.insertParentChildAt(component, slotName, at, _at) } public postInsertParentRootAt( component: Component, at: number, slotName: string ): void { set(component, '$parent', this) _if(this.$mounted, mount, component, this.$context) } public prependParentRoot(component: Component, slotName: string): void { this.insertParentRootAt(component, 0, slotName) } public removeParentRoot(component: Component): void { const at = this.$parentRoot.indexOf(component) const _at = this.$mountParentRoot.indexOf(component) const slotName = this.$parentRootSlot[at] this.postRemoveParentRootAt(component, slotName, at, _at) this.domRemoveParentRootAt(component, slotName, at, _at) this.memRemoveParentRootAt(component, slotName, at, _at) } public memRemoveParentRootAt( component: Component, slotName: string, at: number, _at: number ): void { pull(this.$mountParentRoot, component) const slot = this.$slot[slotName] slot.memRemoveParentChildAt(component, 'default', at, _at) } public domRemoveParentRootAt( component: Component, slotName: string, at: number, _at: number ): void { const slot = this.$slot[slotName] slot.domRemoveParentChildAt(component, 'default', at, _at) } public postRemoveParentRootAt( component: Component, slotName: string, at: number, _at: number ): void { component.$parent = null if (this.$mounted) { component.unmount() } } public getSubComponent(id: string): Component { return this.$subComponent[id] } public setSubComponent(id: string, component: Component): void { this.$subComponent[id] = component } public removeSubComponent(id: string): Component { const component = this.$subComponent[id] delete this.$subComponent[id] return component } public getSubComponentParentId(id: string): string | null { const subComponent = this.getSubComponent(id) for (const parentSubComponentId in this.$subComponent) { const parentSubComponent = this.$subComponent[parentSubComponentId] if (parentSubComponent.$parentRoot.includes(subComponent)) { return parentSubComponentId } } return null } public getSlotSubComponentId(slotName: string): string { const slot = this.$slot[slotName] || this if (slot === this) { return null } else { return this.getSubComponentId(slot) } } public getSubComponentId(subComponent: Component): string | null { for (const subComponentId in this.$subComponent) { const _subComponent = this.$subComponent[subComponentId] if (subComponent === _subComponent) { return subComponentId } } return null } public getParentChildSlotId(subComponent: Component): string { const i = this.$parentRoot.indexOf(subComponent) if (i > -1) { const slotName = this.$parentRootSlot[i] return slotName } else { throw new Error('Parent Child Not Found') } } public addEventListener = (listener: Listener): Unlisten => { return addListener(this, listener) } public addEventListeners = (listeners: Listener[]): Unlisten => { return addListeners(this, listeners) } private _call(method: string, data: any[] = []): void { if (this[method]) { this[method](...data) } else { throw 'method not implemented' } } public destroy() { this.onDestroy() } }
the_stack
import { AppUserConfigs } from '@logseq/libs/dist/LSPlugin.user'; import { ISchedule } from 'tui-calendar' import { flattenDeep, get, has } from 'lodash' import { endOfDay, formatISO, parse } from 'date-fns' import dayjs, { Dayjs } from 'dayjs' import { getInitalSettings } from './baseInfo' import { ICategory, IQueryWithCalendar, ISettingsForm } from './type' import { DEFAULT_BLOCK_DEADLINE_DATE_FORMAT, DEFAULT_JOURNAL_FORMAT, MARKDOWN_PROJECT_TIME_REG, ORG_PROJECT_TIME_REG, TIME_REG } from './constants' import { getBlockData, getPageData, pureTaskBlockContent } from './logseq' import { BlockEntity } from '@logseq/libs/dist/LSPlugin' import { parseUrlParams } from './util' export const getSchedules = async () => { const agendaCalendars = await getAgendaCalendars() const agendaCalendarIds = agendaCalendars.map(calendar => calendar.id) // console.log('[faiz:] === getSchedules start ===', logseq.settings, getInitalSettings()) let calendarSchedules:ISchedule[] = [] // get calendar configs const settings = getInitalSettings() console.log('[faiz:] === settings', settings) const { calendarList: calendarConfigs = [], logKey, journal, defaultDuration, projectList } = settings const customCalendarConfigs = calendarConfigs.concat(journal!).filter(config => config?.enabled) let scheduleQueryList: IQueryWithCalendar[] = [] scheduleQueryList = customCalendarConfigs.map((calendar) => { return calendar?.query ?.filter(item => item?.script?.length) ?.map(item => ({ calendarConfig: calendar, query: item, })) }).filter(Boolean).flat() const queryPromiseList = scheduleQueryList.map(async queryWithCalendar => { const { calendarConfig, query } = queryWithCalendar const { script = '', scheduleStart = '', scheduleEnd = '', dateFormatter, isMilestone, queryType } = query let blocks: any[] = [] if (queryType === 'simple') { blocks = await logseq.DB.q(script) || [] } else { blocks = await logseq.DB.datascriptQuery(script) } // console.log('[faiz:] === search blocks by query: ', script, blocks) const buildSchedulePromiseList = flattenDeep(blocks).map((block) => convertBlockToSchedule({ block, queryWithCalendar, agendaCalendarIds, settings })) return Promise.all(buildSchedulePromiseList) }) const scheduleRes = await Promise.allSettled(queryPromiseList) const scheduleResFulfilled:ISchedule[] = [] scheduleRes.forEach((res, index) => { if (res.status === 'fulfilled') { scheduleResFulfilled.push(res.value) } else { console.error('[faiz:] === scheduleRes error: ', scheduleQueryList[index], res) const { calendarConfig, query } = scheduleQueryList[index] const msg = `Query Exec Error: calendar: ${calendarConfig.id} query: ${query.script} message: ${res.reason.message}` logseq.App.showMsg(msg, 'error') } }) calendarSchedules = flattenDeep(calendarSchedules.concat(scheduleResFulfilled)) // Projects const validProjectList = projectList?.filter(project => Boolean(project?.id)) if (validProjectList && validProjectList.length > 0) { const promiseList = validProjectList.map(async project => { const tasks = await logseq.DB.q(`(and (task todo doing now later done) [[${project.id}]])`) const milestones = await logseq.DB.q(`(and (page "${project.id}") [[milestone]])`) function blockToSchedule(list: BlockEntity[], isMilestone = false) { return Promise.all(list.map(async (block: BlockEntity) => { const timeInfo = getProjectTaskTime(block.content) if (!timeInfo) return null const {start, end, allDay} = timeInfo let _category: ICategory = allDay === 'false' ? 'time' : 'allday' if (isMilestone) _category = 'milestone' const rawCategory = _category const _isOverdue = isOverdue(block, end || start, allDay !== 'false') if (!isMilestone && _isOverdue) _category = 'task' const schedule = await genSchedule({ id: block.uuid, blockData: { ...block, // 避免 overdue 的 block 丢失真实 category 信息 category: rawCategory, rawStart: start, rawEnd: end, rawAllDay: allDay !== 'false', rawOverdue: _isOverdue, }, category: _category, start, end, calendarConfig: project, defaultDuration, isAllDay: !isMilestone && allDay !== 'false' && !_isOverdue, isReadOnly: false, }) // show overdue tasks in today return _isOverdue ? [ schedule, { ...schedule, id: `overdue-${schedule.id}`, start: dayjs().startOf('day').toISOString(), end: dayjs().endOf('day').toISOString(), isAllDay: false, }, ] : schedule })) } const taskSchedules = (tasks && tasks.length > 0) ? await blockToSchedule(tasks) : [] const milestoneSchedules = (milestones && milestones.length > 0) ? await blockToSchedule(milestones, true) : [] return taskSchedules.concat(milestoneSchedules)?.flat().filter(Boolean) }) const projectSchedules = await Promise.all(promiseList) console.log('[faiz:] === projectSchedules', projectSchedules) // @ts-ignore calendarSchedules = flattenDeep(calendarSchedules.concat(projectSchedules)) } // Daily Logs if (logKey?.enabled) { const logs = await logseq.DB.q(`[[${logKey.id}]]`) // console.log('[faiz:] === search logs', logs) const _logs = logs ?.filter(block => { if (block.headingLevel && block.format === 'markdown') { block.content = block.content.replace(new RegExp(`^#{${block.headingLevel}} `), '') } return block.content?.trim() === `[[${logKey.id}]]` }) ?.map(block => Array.isArray(block.parent) ? block.parent : []) ?.flat() ?.filter(block => { const _content = block.content?.trim() return _content.length > 0 && block?.page?.journalDay && !block.marker && !block.scheduled && !block.deadline }) || [] const _logSchedulePromises = _logs?.map(async block => { const date = block?.page?.journalDay const { start: _startTime, end: _endTime } = getTimeInfo(block?.content.replace(new RegExp(`^${block.marker} `), '')) const hasTime = _startTime || _endTime return await genSchedule({ blockData: block, category: hasTime ? 'time' : 'allday', start: _startTime ? formatISO(parse(date + ' ' + _startTime, 'yyyyMMdd HH:mm', new Date())) : genCalendarDate(date), end: _endTime ? formatISO(parse(date + ' ' + _endTime, 'yyyyMMdd HH:mm', new Date())) : undefined, calendarConfig: logKey, defaultDuration, isAllDay: !hasTime, isReadOnly: true, }) }) const _logSchedules = await Promise.all(_logSchedulePromises) calendarSchedules = calendarSchedules.concat(_logSchedules) } return calendarSchedules } export const convertBlockToSchedule = async ({ block, queryWithCalendar, agendaCalendarIds, settings }: { block: any; queryWithCalendar: IQueryWithCalendar, agendaCalendarIds: string[], settings: ISettingsForm }) => { const { calendarConfig, query } = queryWithCalendar const { script = '', scheduleStart = '', scheduleEnd = '', dateFormatter, isMilestone, queryType } = query const { defaultDuration } = settings const _dateFormatter = ['scheduled', 'deadline'].includes(scheduleStart || scheduleEnd) ? DEFAULT_BLOCK_DEADLINE_DATE_FORMAT : dateFormatter || DEFAULT_JOURNAL_FORMAT const start = get(block, scheduleStart, undefined) const end = get(block, scheduleEnd, undefined) let hasTime = /[Hhm]+/.test(_dateFormatter || '') let _start let _end try { _start = start && genCalendarDate(start, _dateFormatter) _end = end && (hasTime ? genCalendarDate(end, _dateFormatter) : formatISO(endOfDay(parse(end, _dateFormatter, new Date())))) } catch (err) { console.warn('[faiz:] === parse calendar date error: ', err, block, query) return [] } if (block?.page?.['journal-day']) { const { start: _startTime, end: _endTime } = getTimeInfo(block?.content.replace(new RegExp(`^${block.marker} `), '')) if (_startTime || _endTime) { const date = block?.page?.['journal-day'] _start = _startTime ? formatISO(parse(date + ' ' + _startTime, 'yyyyMMdd HH:mm', new Date())) : genCalendarDate(date), _end = _endTime ? formatISO(parse(date + ' ' + _endTime, 'yyyyMMdd HH:mm', new Date())) : undefined, hasTime = true } } if (start && ['scheduled', 'deadline'].includes(scheduleStart)) { const dateString = block.content?.split('\n')?.find(l => l.startsWith(`${scheduleStart.toUpperCase()}:`))?.trim() const time = / (\d{2}:\d{2})[ >]/.exec(dateString)?.[1] || '' if (time) { _start = formatISO(parse(`${start} ${time}`, 'yyyyMMdd HH:mm', new Date())) hasTime = true } } if (end && ['scheduled', 'deadline'].includes(scheduleEnd)) { const dateString = block.content?.split('\n')?.find(l => l.startsWith(`${scheduleEnd.toUpperCase()}:`))?.trim() const time = / (\d{2}:\d{2})[ >]/.exec(dateString)?.[1] || '' if (time) { _end = formatISO(parse(`${end} ${time}`, 'yyyyMMdd HH:mm', new Date())) hasTime = true } } let _category: ICategory = hasTime ? 'time' : 'allday' if (isMilestone) _category = 'milestone' const rawCategory = _category const _isOverdue = isOverdue(block, _end || _start, !hasTime) if (!isMilestone && _isOverdue) _category = 'task' const schedule = await genSchedule({ blockData: { ...block, // 避免 overdue 的 block 丢失真实 category 信息 category: rawCategory, type: 'project', rawStart: _start, rawEnd: _end, rawAllDay: !hasTime, rawOverdue: _isOverdue, }, category: _category, start: _start, end: _end, calendarConfig, defaultDuration, isAllDay: !isMilestone && !hasTime && !_isOverdue, isReadOnly: !supportEdit(block, calendarConfig.id, agendaCalendarIds), }) // show overdue tasks in today return _isOverdue ? [ schedule, { ...schedule, id: `overdue-${schedule.id}`, start: dayjs().startOf('day').toISOString(), end: dayjs().endOf('day').toISOString(), isAllDay: false, }, ] : schedule } /** * 判断是否过期 */ export const isOverdue = (block: any, date: string, allDay: boolean) => { if (block.marker && block.marker !== 'DONE') { // return isAfter(startOfDay(new Date()), parseISO(date)) if (allDay) { return dayjs().isAfter(dayjs(date), 'day') } return dayjs().isAfter(dayjs(date), 'minute') } // 非 todo 及 done 的 block 不过期 return false } /** * 提取时间信息 * eg: '12:00 foo' => { start: '12:00', end: undefined } * eg: '12:00-13:00 foo' => { start: '12:00', end: '13:00' } * eg: 'foo' => { start: undefined, end: undefined } */ export const getTimeInfo = (content: string) => { const res = content.match(TIME_REG) if (res) return { start: res[1], end: res[2]?.slice(1) } return { start: undefined, end: undefined } } /** * 修改时间信息 */ export const modifyTimeInfo = (content: string, start: string, end: string) => { const timeInfo = `${start}${end ? '-' + end : ''}` const res = content.match(TIME_REG) if (res) return content.replace(TIME_REG, timeInfo) return timeInfo + ' ' + content } /** * 移除时间信息 */ export const removeTimeInfo = (content: string) => { return content.replace(TIME_REG, '') } /** * 填充 block reference 内容 */ export const fillBlockReference = async (blockContent: string) => { const BLOCK_REFERENCE_REG = /\(\([0-9a-z\-]{30,}\)\)/ if (BLOCK_REFERENCE_REG.test(blockContent)) { const uuid = BLOCK_REFERENCE_REG.exec(blockContent)?.[0]?.replace('((', '')?.replace('))', '') if (uuid) { const referenceData = await getBlockData({ uuid }, true) return blockContent.replace(BLOCK_REFERENCE_REG, referenceData?.content || '') } } return blockContent } export async function genSchedule(params: { id?: string blockData: any category: ICategory start?: string end?:string calendarConfig: Omit<ISettingsForm['calendarList'][number], 'query'> isAllDay?: boolean isReadOnly?: boolean defaultDuration?: ISettingsForm['defaultDuration'] }) { const { id, blockData, category = 'time', start, end, calendarConfig, isAllDay, defaultDuration, isReadOnly } = params if (!blockData?.id) { // 单个耗时在5-7秒,整体耗时8秒 const block = await getBlockData({ uuid: blockData.uuid?.$uuid$ }, true) if (block) blockData.id = block.id } let page = blockData?.page if (has(page, 'id') && has(page, 'name') && has(page, 'original-name')) { page = { id: page.id, journalDay: page['journal-day'], journal: page['journal?'], name: page['name'], originalName: page['original-name'], } } // else { // // 耗时1s左右 // page = await getPageData({ id: blockData?.page?.id }) // } blockData.page = page // 单个耗时在5-7秒,整体耗时11秒 blockData.fullContent = await fillBlockReference(blockData.content) const projectTimeReg = (window.logseqAppUserConfigs as AppUserConfigs)?.preferredFormat === 'org' ? ORG_PROJECT_TIME_REG : MARKDOWN_PROJECT_TIME_REG const title = blockData.fullContent .split('\n')[0] ?.replace(new RegExp(`^${blockData.marker} `), '') ?.replace(TIME_REG, '') ?.replace(projectTimeReg, '') ?.replace(' #milestone', '') ?.trim?.() const isDone = blockData.marker === 'DONE' function supportEdit() { if (blockData.page?.properties?.agenda === true) return true if (blockData?.page?.['journal-day'] && !blockData?.scheduled && !blockData?.deadline) return true return false } const isSupportEdit = isReadOnly === undefined ? supportEdit() : !isReadOnly const _defaultDuration = defaultDuration || getInitalSettings()?.defaultDuration let _end = end if ((category === 'time' || blockData?.category === 'time') && !end && start && _defaultDuration) { _end = dayjs(start).add(_defaultDuration.value, _defaultDuration.unit).toISOString() } if (blockData?.category !== 'time' && !end) { _end = start } const uuid = typeof blockData?.uuid === 'string' ? blockData?.uuid : blockData?.uuid?.['$uuid$'] blockData.uuid = uuid return { id: id || uuid, calendarId: calendarConfig.id, // title: isDone ? `✅ ${title}` : title, title, body: blockData.fullContent, category, dueDateClass: '', start, end: _end, raw: blockData, color: calendarConfig?.textColor, bgColor: calendarConfig?.bgColor, borderColor: calendarConfig?.borderColor, isAllDay, customStyle: isDone ? 'opacity: 0.6;' : '', isReadOnly: !isSupportEdit, } } export const genCalendarDate = (date: number | string, format = DEFAULT_BLOCK_DEADLINE_DATE_FORMAT) => { return formatISO(parse('' + date, format, new Date())) } export const genScheduleWithCalendarMap = (schedules: ISchedule[]) => { let res = new Map<string, ISchedule[]>() schedules.forEach(schedule => { const key = schedule.calendarId || '' if (!res.has(key)) res.set(key, []) res.get(key)?.push(schedule) }) return res } export const getAgendaCalendars = async () => { const { calendarList } = logseq.settings as unknown as ISettingsForm const calendarPagePromises = calendarList.map(calendar => getPageData({ originalName: calendar.id })) const res = await Promise.all(calendarPagePromises) return res.map((page, index) => { if (!page) return null if ((page as any)?.properties?.agenda !== true) return null return calendarList[index] }) .filter(function<T>(item: T | null): item is T { return Boolean(item) }) } export const supportEdit = (blockData, calendarId, agendaCalendarIds) => { if (agendaCalendarIds.includes(calendarId)) return true if (blockData?.page?.['journal-day'] && !blockData?.scheduled && !blockData?.deadline) return true return false } export const catrgorizeTask = (schedules: ISchedule[]) => { const DOING_CATEGORY = ['DOING', 'NOW'] const TODO_CATEGORY = ['TODO', 'LATER'] const DONE_CATEGORY = ['DONE'] const CANCELED_CATEGORY = ['CANCELED'] return { doing: schedules.filter(schedule => DOING_CATEGORY.includes(schedule?.raw?.marker as string)), todo: schedules.filter(schedule => TODO_CATEGORY.includes(schedule?.raw?.marker as string)), done: schedules.filter(schedule => DONE_CATEGORY.includes(schedule?.raw?.marker as string)), canceled: schedules.filter(schedule => CANCELED_CATEGORY.includes(schedule?.raw?.marker as string)), } } // 以开始时间为为key,转为map export const scheduleStartDayMap = (schedules: ISchedule[]) => { const res = new Map<string, ISchedule[]>() schedules.forEach(schedule => { const key = dayjs(schedule.start as string).startOf('day').toISOString() if (!res.has(key)) res.set(key, []) res.get(key)?.push(schedule) }) return res } export const genProjectTaskTime = ({ start, end, allDay }: { start: Dayjs, end: Dayjs, allDay?: boolean }) => { const url = new URL('agenda://') url.searchParams.append('start', start.toISOString()) url.searchParams.append('end', end.toISOString()) if (allDay === false) url.searchParams.append('allDay', 'false') const startText = allDay ? start.format('YYYY-MM-DD') : start.format('YYYY-MM-DD HH:mm') let endText = allDay ? end.format('YYYY-MM-DD') : end.format('YYYY-MM-DD HH:mm') const isSameDay = start.isSame(end, 'day') if (isSameDay && allDay) endText = '' if (isSameDay && !allDay) endText = end.format('HH:mm') const showText = startText + (endText ? ` - ${endText}` : '') const time = (window.logseqAppUserConfigs as AppUserConfigs)?.preferredFormat === 'org' ? `>[[#${url.toString()}][${showText}]]` : `>[${showText}](#${url.toString()})` return time } export const getProjectTaskTime = (blockContent: string) => { const projectTimeReg = (window.logseqAppUserConfigs as AppUserConfigs)?.preferredFormat === 'org' ? ORG_PROJECT_TIME_REG : MARKDOWN_PROJECT_TIME_REG const res = blockContent.match(projectTimeReg) if (!res || !res?.[1]) return null return parseUrlParams(res[1]) } export const deleteProjectTaskTime = (blockContent: string) => { const projectTimeReg = (window.logseqAppUserConfigs as AppUserConfigs)?.preferredFormat === 'org' ? ORG_PROJECT_TIME_REG : MARKDOWN_PROJECT_TIME_REG return blockContent.replace(projectTimeReg, '') } export const updateProjectTaskTime = (blockContent: string, timeInfo: { start: Dayjs, end: Dayjs, allDay?: boolean }) => { const projectTimeReg = (window.logseqAppUserConfigs as AppUserConfigs)?.preferredFormat === 'org' ? ORG_PROJECT_TIME_REG : MARKDOWN_PROJECT_TIME_REG const time = genProjectTaskTime(timeInfo) const newContent = removeTimeInfo(blockContent)?.trim() if (projectTimeReg.test(newContent)) { return newContent.replace(projectTimeReg, time) } return newContent?.split('\n').map((txt, index) => index === 0 ? txt + ' ' + time : txt).join('\n') } export function categorizeTasks (tasks: ISchedule[]) { let overdueTasks: ISchedule[] = [] let allDayTasks: ISchedule[] = [] let timeTasks: ISchedule[] = [] tasks.forEach(task => { if (task.raw?.rawOverdue) { overdueTasks.push(task) } else if (task.isAllDay) { allDayTasks.push(task) } else { timeTasks.push(task) } }) return { overdueTasks, allDayTasks, timeTasks } }
the_stack
import {browser, element, by, protractor, ElementArrayFinder} from 'protractor'; import * as moment from 'moment/moment'; import { waitForElementVisibility, waitForElementPresence, waitForElementInVisibility, waitForText, waitForCssClass, waitForCssClassNotToBePresent, waitForTextChange, waitForStalenessOf, reduce_for_get_all, waitForElementCountGreaterThan, scrollIntoView, waitForNonEmptyText, catchNoSuchElementError } from '../utils/e2e_util'; export class MetronAlertsPage { private EC = protractor.ExpectedConditions; navigateTo() { return browser.waitForAngularEnabled(false) .then(() => browser.get('/alerts-list')); } clearLocalStorage() { return browser.executeScript('window.localStorage.clear();'); } isMetronLogoPresent() { return element(by.css('img[src="../assets/images/logo.png"]')).isPresent(); } isSavedSearchButtonPresent() { return element(by.buttonText('Searches')).isPresent(); } isClearSearchPresent() { return element(by.css('.btn-search-clear')).isPresent(); } isSearchButtonPresent() { return element(by.css('.btn-search-clear')).isPresent(); } isSaveSearchButtonPresent() { return element(by.css('.save-button')).isPresent(); } isTableSettingsButtonPresent() { return element(by.css('.btn.settings')).isPresent(); } isPausePlayRefreshButtonPresent() { return element(by.css('.btn.pause-play')).isPresent(); } isActionsButtonPresent() { return element.all(by.buttonText('ACTIONS')).isPresent(); } isConfigureTableColumnsPresent() { return element(by.css('.fa.fa-cog.configure-table-icon')).isPresent(); } getAlertTableTitle() { return element(by.css('.col-form-label-lg')).getText(); } clickActionDropdown() { let actionsDropDown = element(by.buttonText('ACTIONS')); return scrollIntoView(actionsDropDown, true) .then(() => actionsDropDown.click()); } clickActionDropdownOption(option: string) { return this.clickActionDropdown() .then(() => element(by.cssContainingText('.dropdown-menu span', option)).click()) .then(() => waitForCssClassNotToBePresent(element(by.css('#table-actions')), 'show')); } getActionDropdownItems() { return this.clickActionDropdown() .then(() => element.all(by.css('.dropdown-menu .dropdown-item.disabled')).reduce(reduce_for_get_all(), [])); } getTableColumnNames() { return element.all(by.css('app-alerts-list .table th')).reduce(reduce_for_get_all(), []); } getChangedPaginationText(previousText: string) { let paginationElement = element(by.css('metron-table-pagination span')); return waitForTextChange(paginationElement, previousText) .then(() => paginationElement.getText()); } getPaginationText() { return element(by.css('metron-table-pagination span')).getText(); } isChevronLeftEnabled() { return element(by.css('metron-table-pagination .fa.fa-chevron-left')).getAttribute('class').then((classes) => { return classes.split(' ').indexOf('disabled') === -1; }); } isChevronRightEnabled() { return element(by.css('metron-table-pagination .fa.fa-chevron-right')).getAttribute('class').then((classes) => { return classes.split(' ').indexOf('disabled') === -1; }); } clickChevronRight() { let paginationEle = element(by.css('metron-table-pagination .fa.fa-chevron-right')); return waitForElementVisibility(paginationEle) .then(() => browser.actions().mouseMove(paginationEle).perform()) .then(() => paginationEle.click()) } clickChevronLeft(times = 1) { let paginationEle = element(by.css('metron-table-pagination .fa.fa-chevron-left')); return waitForElementVisibility(paginationEle) .then(() => browser.actions().mouseMove(paginationEle).perform()) .then(() => paginationEle.click()); } clickSettings() { let settingsIcon = element(by.css('.btn.settings')); return waitForElementVisibility(settingsIcon).then(() => settingsIcon.click()); } getSettingsLabels() { return element.all(by.css('app-configure-rows form label:not(.switch)')).reduce(reduce_for_get_all() ,[]); } getRefreshRateOptions() { return element.all(by.css('.preset-row.refresh-interval .preset-cell')).reduce(reduce_for_get_all() ,[]); } getRefreshRateSelectedOption() { return element.all(by.css('.preset-row.refresh-interval .preset-cell.is-active')).reduce(reduce_for_get_all() ,[]); } getPageSizeOptions() { return element.all(by.css('.preset-row.page-size .preset-cell')).reduce(reduce_for_get_all() ,[]); } getPageSizeSelectedOption() { return element.all(by.css('.preset-row.page-size .preset-cell.is-active')).reduce(reduce_for_get_all() ,[]); } clickRefreshInterval(intervalText: string) { return element(by.cssContainingText('.refresh-interval .preset-cell', intervalText)).click(); } clickPageSize(pageSizeText: string) { return element.all(by.cssContainingText('.page-size .preset-cell', pageSizeText)).first().click(); } clickConfigureTable() { let gearIcon = element(by.css('app-alerts-list .fa.fa-cog.configure-table-icon')); return waitForElementVisibility(gearIcon) .then(() => scrollIntoView(gearIcon, true)) .then(() => gearIcon.click()) .then(() => waitForElementCountGreaterThan('app-configure-table tr', 282)); } clickCloseSavedSearch() { return element(by.css('app-saved-searches .close-button')).click() .then(() => waitForStalenessOf(element(by.css('app-saved-searches')))); } clickSavedSearch() { return element(by.buttonText('Searches')).click() .then(() => waitForElementVisibility(element(by.css('app-saved-searches')))) .then(() => browser.sleep(1000)); } clickPlayPause(waitForPreviousClass: string) { let playPauseButton = element(by.css('.btn.pause-play')); return browser.actions().mouseMove(playPauseButton).perform() .then(() => playPauseButton.click()) .then(() => waitForCssClass(element(by.css('.btn.pause-play i')), waitForPreviousClass)); } clickTableTextAndGetSearchText(name: string, textToWaitFor: string) { browser.sleep(500); return waitForElementVisibility(element.all(by.cssContainingText('table tr td a', name)).get(0)) .then(() => element.all(by.cssContainingText('table tr td a', name)).get(0).click()) .then(() => waitForText('.ace_line', textToWaitFor)) .then(() => element(by.css('.ace_line')).getText()); } private clickTableText(name: string) { waitForElementVisibility(element.all(by.linkText(name))).then(() => element.all(by.linkText(name)).get(0).click()); } clickClearSearch(alertCount = '169') { return element(by.css('.btn-search-clear')).click() .then(() => waitForText('.ace_line', '*')) .then(() => waitForText('.col-form-label-lg', `Alerts (${alertCount})`)); } getSavedSearchTitle() { return element(by.css('app-saved-searches .form-title')).getText(); } getPlayPauseState() { return element(by.css('.btn.pause-play i')).getAttribute('class'); } getSearchText() { return element(by.css('.ace_line')).getText(); } isCommentIconPresentInTable() { return element.all(by.css('app-table-view .fa.fa-comments-o')).count(); } getRecentSearchOptions() { return element.all(by.css('[data-name="recent-searches"] li')).getText(); } getDefaultRecentSearchValue() { return element.all(by.css('[data-name="recent-searches"] i')).getText(); } getSavedSearchOptions() { return element.all(by.css('[data-name="saved-searches"] li')).getText(); } getDefaultSavedSearchValue() { return element.all(by.css('[data-name="saved-searches"] i')).getText(); } getSelectedColumnNames() { return element.all(by.css('app-configure-table input[type="checkbox"]:checked')).reduce((acc, ele) => { return ele.getAttribute('id').then(id => { acc.push(id.replace(/select-deselect-/, '')); return acc; }) }, []); } toggleSelectCol(name: string) { const selector = `app-configure-table label[for=\"select-deselect-${name}\"]`; const ele = element(by.css(selector)); return waitForElementVisibility(ele) .then(() => scrollIntoView(ele, true)) .then(() => (element(by.css(selector)).click())) .catch(err => console.log(err)); } saveSearch(name: string) { return element(by.css('.save-button')).click().then(() => element(by.css('app-save-search #name')).sendKeys(name)) .then(() => element(by.css('app-save-search button[type="submit"]')).click()); } saveConfigureColumns() { return element(by.css('app-configure-table')).element(by.buttonText('SAVE')).click(); } clickRemoveSearchChipAndGetSearchText(expectedSearchText: string) { return this.clickRemoveSearchChip() .then(() => waitForText('.ace_line', expectedSearchText)) .then(() => element(by.css('.ace_line')).getText()) } private clickRemoveSearchChip(): any { let aceLine = element.all(by.css('.ace_keyword')).get(0); /* - Focus on the search text box by sending a empty string - move the mouse to the text in search bos so that delete buttons become visible - wait for delete buttons become visible - click on delete button */ return element(by.css('app-alerts-list .ace_text-input')).sendKeys('') .then(() => browser.actions().mouseMove(aceLine).perform()) .then(() => this.waitForElementPresence(element(by.css('.ace_value i')))) .then(() => element.all(by.css('.ace_value i')).get(0).click()); } setSearchText(search: string, alertCount = '169') { // It is required to click on a visible element of Ace editor in order to // bring focus to the input: https://stackoverflow.com/questions/37809915/element-not-visible-error-not-able-to-click-an-element let EC = protractor.ExpectedConditions; let aceInput = element(by.css('app-alerts-list .ace_text-input')); let aceScroller = element(by.css('app-alerts-list .ace_scroller')); return this.clickClearSearch(alertCount) .then(() => browser.wait(EC.presenceOf(aceScroller))) .then(() => aceScroller.click()) .then(() => aceInput.sendKeys(protractor.Key.BACK_SPACE)) .then(() => aceInput.sendKeys(search)) .then(() => aceInput.sendKeys(protractor.Key.ENTER)) .then(() => browser.sleep(10000)); } waitForElementPresence (element ) { let EC = protractor.ExpectedConditions; return browser.wait(EC.presenceOf(element)); } waitForTextChange(element, previousText) { let EC = protractor.ExpectedConditions; return browser.wait(EC.not(EC.textToBePresentInElement(element, previousText))); } toggleAlertInList(index: number) { let selector = by.css('app-alerts-list tbody tr label'); let checkbox = element.all(selector).get(index); return this.waitForElementPresence(checkbox) .then(() => scrollIntoView(checkbox, true)) .then(() => checkbox.click()); } getAlertStatus(rowIndex: number, previousText: string, colIndex = 8) { let row = element.all(by.css('app-alerts-list tbody tr')).get(rowIndex); let column = row.all(by.css('td a')).get(colIndex); return this.waitForTextChange(column, previousText).then(() => column.getText()); } waitForMetaAlert(expectedCount) { let title = element(by.css('.col-form-label-lg')); function waitForMetaAlert$() { return function () { return browser.sleep(2000) .then(() => element(by.css('button[data-name="search"]')).click()) .then(() => waitForTextChange(title, `Alerts (169)`)) .then(() => title.getText()) .then((text) => text === `Alerts (${expectedCount})`) .catch(catchNoSuchElementError()) } } return browser.wait(waitForMetaAlert$()).catch(catchNoSuchElementError()); } isDateSeettingDisabled() { return element.all(by.css('app-time-range button.btn.btn-search[disabled=""]')).count().then((count) => { return (count === 1); }); } clickDateSettings() { return scrollIntoView(element(by.css('app-time-range button.btn-search')), true) .then(() => element(by.css('app-time-range button.btn-search')).click()) .then(() => waitForCssClass(element(by.css('app-time-range #time-range')), 'show')); } hideDateSettings() { return element(by.css('app-time-range button.btn-search')).click() .then(() => waitForCssClassNotToBePresent(element(by.css('app-time-range #time-range')), 'show')) .then(() => waitForElementInVisibility(element(by.css('app-time-range #time-range')))); } getTimeRangeTitles() { return element.all(by.css('app-time-range .title')).reduce(reduce_for_get_all(), []); } getQuickTimeRanges() { return element.all(by.css('app-time-range .quick-ranges span')).reduce(reduce_for_get_all(), []); } getValueForManualTimeRange() { return element.all(by.css('app-time-range input.form-control')).reduce((acc, ele) => { return ele.getAttribute('value').then(value => { acc.push(value); return acc; }); }, []); } isManulaTimeRangeApplyButtonPresent() { return element.all(by.css('app-time-range')).all(by.buttonText('APPLY')).count().then(count => count === 1); } waitForTextAndSubTextInTimeRange(currentTimeRangeVal) { return waitForTextChange(element(by.css('app-time-range .time-range-value')), currentTimeRangeVal[1]) .then(() => waitForTextChange(element(by.css('app-time-range .time-range-text')), currentTimeRangeVal[0])) } async selectQuickTimeRangeAndGetTimeRangeAndTimeText(quickRange: string) { let currentTimeRangeVal: any = []; let timeRangeVal = '', timeRangeText = ''; await element(by.css('app-time-range .time-range-value')).getText().then(text => timeRangeVal = text.trim()); await element(by.css('app-time-range .time-range-text')).getText().then(text => timeRangeText = text.trim()); await this.selectQuickTimeRange(quickRange); await waitForCssClassNotToBePresent(element(by.css('app-time-range #time-range')), 'show'); await waitForTextChange(element(by.css('app-time-range .time-range-value')), timeRangeVal); await waitForTextChange(element(by.css('app-time-range .time-range-text')), timeRangeText); return this.getTimeRangeButtonAndSubText(); } selectQuickTimeRangeAndGetTimeRangeText(quickRange: string) { return this.selectQuickTimeRange(quickRange) .then(() => waitForElementInVisibility(element(by.css('#time-range')))) .then(() => browser.wait(this.EC.textToBePresentInElement(element(by.css('app-time-range .time-range-text')), quickRange))) .then(() => element.all(by.css('app-time-range button span')).get(0).getText()); } selectQuickTimeRange(quickRange: string) { return element(by.id(quickRange.toLowerCase().replace(/ /g,'-'))).click(); } getTimeRangeButtonText() { return element(by.css('app-time-range .time-range-text')).getText(); } setDate(index: number, year: string, month: string, day: string, hour: string, min: string, sec: string) { return element.all(by.css('app-time-range .calendar')).get(index).click() .then(() => element.all(by.css('.pika-select.pika-select-hour')).get(index).click()) .then(() => element.all(by.css('.pika-select.pika-select-hour')).get(index).element(by.cssContainingText('option', hour)).click()) .then(() => element.all(by.css('.pika-select.pika-select-minute')).get(index).click()) .then(() => element.all(by.css('.pika-select.pika-select-minute')).get(index).element(by.cssContainingText('option', min)).click()) .then(() => element.all(by.css('.pika-select.pika-select-second')).get(index).click()) .then(() => element.all(by.css('.pika-select.pika-select-second')).get(index).element(by.cssContainingText('option', sec)).click()) .then(() => element.all(by.css('.pika-select.pika-select-year')).get(index).click()) .then(() => element.all(by.css('.pika-select.pika-select-year')).get(index).element(by.cssContainingText('option', year)).click()) .then(() => element.all(by.css('.pika-select.pika-select-month')).get(index).click()) .then(() => element.all(by.css('.pika-select.pika-select-month')).get(index).element(by.cssContainingText('option', month)).click()) .then(() => element.all(by.css('.pika-table')).get(index).element(by.buttonText(day)).click()) .then(() => waitForElementInVisibility(element.all(by.css('.pika-single')).get(index))); } selectTimeRangeApplyButton() { return element(by.css('app-time-range')).element(by.buttonText('APPLY')).click(); } getChangesAlertTableTitle(previousText: string) { let title = element(by.css('.col-form-label-lg')); return waitForTextChange(title, previousText) .then(() => title.getText()); } getAlertStatusById(id: string) { return element(by.css('a[title="' + id + '"]')) .element(by.xpath('../..')).all(by.css('td a')).get(8).getText(); } getCellValue(rowIndex: number, colIndex: number, previousText: string) { let cellElement = element.all(by.css('table tbody tr')).get(rowIndex).all(by.css('td')).get(colIndex); return this.waitForTextChange(cellElement, previousText).then(() => cellElement.getText()); } expandMetaAlert(rowIndex: number) { return element.all(by.css('table tbody tr')).get(rowIndex).element(by.css('.icon-cell.dropdown-cell')).click(); } getHiddenRowCount() { return element.all(by.css('table tbody tr.d-none')).count(); } getNonHiddenRowCount() { return element.all(by.css('table tbody tr:not(.d-none)')).count(); } getAllRowsCount() { return element.all(by.css('table tbody tr')).count(); } clickOnMetaAlertRow(rowIndex: number) { return element.all(by.css('table tbody tr')).get(rowIndex).all(by.css('td')).get(5).click() .then(() => browser.sleep(2000)); } removeAlert(rowIndex: number) { return element.all(by.css('app-table-view .fa-chain-broken')).get(rowIndex).click(); } loadSavedSearch(name: string) { return element.all(by.css('app-saved-searches metron-collapse')).get(1).element(by.css('li[title="'+ name +'"]')).click(); } loadRecentSearch(name: string) { return element.all(by.css('app-saved-searches metron-collapse')).get(0).all(by.css('li')).get(2).click(); } getTimeRangeButtonTextForNow() { return element.all(by.css('app-time-range button span')).reduce(reduce_for_get_all(), []); } async getTimeRangeButtonAndSubText() { let timeRangetext = '', timeRangeValue = ''; await element(by.css('app-time-range .time-range-text')).getText().then(text => timeRangetext = text); await element(by.css('app-time-range .time-range-value')).getText().then(text => timeRangeValue = text); let retArr = [timeRangetext]; let dateStr = timeRangeValue.split(' to '); let fromTime = moment.utc(dateStr[0], 'YYYY-MM-DD HH:mm:ss Z').unix() * 1000; let toTime = moment.utc(dateStr[1], 'YYYY-MM-DD HH:mm:ss Z').unix() * 1000; retArr.push((toTime - fromTime) + ''); return retArr; } renameColumn(name: string, value: string) { return element(by.cssContainingText('app-configure-table span', name)) .element(by.xpath('../..')) .element(by.css('.input')).sendKeys(value); } getTableCellValues(cellIndex: number, startRowIndex: number, endRowIndex: number): any { return element.all(by.css('table tbody tr td:nth-child(' + cellIndex + ')')).reduce(reduce_for_get_all(), []) } }
the_stack
import * as fs from 'fs'; import * as nodePath from 'path'; import * as fastGlob from 'fast-glob'; import { ts } from 'ts-morph'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { Logger } from '../common/logging/logger'; import { UriUtils } from '../common/view/uri-utils'; import { DocumentSettings, ExtensionSettings, IAureliaProjectSetting, } from '../feature/configuration/DocumentSettings'; import { AureliaProgram } from './viewModel/AureliaProgram'; const logger = new Logger('AureliaProject'); const compilerObjectMap = new Map<string, ts.Program | undefined>(); export interface IAureliaProject { tsConfigPath: string; aureliaProgram: AureliaProgram | null; } export class AureliaProjects { private aureliaProjects: IAureliaProject[] = []; constructor(public readonly documentSettings: DocumentSettings) {} public async initAndVerify(extensionSettings: ExtensionSettings) { const packageJsonPaths = getPackageJsonPaths(extensionSettings); await this.initAndSet(packageJsonPaths); const projects = this.getAll(); const hasAureliaProject = projects.length > 0; if (!hasAureliaProject) { logHasNoAureliaProject(); return false; } logFoundAureliaProjects(projects); return true; } public getAll(): IAureliaProject[] { return this.aureliaProjects; } public getBy(tsConfigPath: string): IAureliaProject | undefined { const target = this.getAll().find( (projects) => projects.tsConfigPath === tsConfigPath ); return target; } public getFromPath(documentPath: string): IAureliaProject | undefined { const target = this.getAll().find((project) => { const included = documentPath.includes(project.tsConfigPath); return included; }); return target; } public getFromUri(uri: string): IAureliaProject | undefined { const path = UriUtils.toSysPath(uri); return this.getFromPath(path); } /** * [PERF]: 2.5s */ public async hydrate( documents: TextDocument[], forceReinit: boolean = false ): Promise<boolean> { /* prettier-ignore */ logger.log('Parsing Aurelia related data...', { logLevel: 'INFO' }); const documentsPaths = documents.map((document) => { const result = UriUtils.toSysPath(document.uri); return result; }); if (documentsPaths.length === 0) { /* prettier-ignore */ logger.log('(!) Extension not activated.', { logLevel: 'INFO' }); /* prettier-ignore */ logger.log('(!) Waiting until .html, .js, or .ts file focused.', { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(' (For performance reasons)', { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(' (Execute command "Aurelia: Reload Extension", if nothing happens.)', { logLevel: 'INFO' }); return false; } const settings = this.documentSettings.getSettings(); const aureliaProjectSettings = settings?.aureliaProject; // 1. To each map assign a separate program await this.addAureliaProgramToEachProject( documentsPaths, aureliaProjectSettings, forceReinit ); return true; } /** * Prevent when * 1. Project already includes document * 2. Document was just opened */ public preventHydration(document: TextDocument): boolean { // 1. if (!this.isDocumentIncluded(document)) { return false; } // 2. if (hasDocumentChanged(document)) { return false; } // update: then extension should correctly(!) not active // logger.culogger.todo( // `What should happen to document, that is not included?: ${document.uri}` // ); logger.log(`Not updating document: ${nodePath.basename(document.uri)}`); return true; } public isHydrated(): boolean { const projects = this.getAll(); const hydrated = projects.every( (project) => project.aureliaProgram !== null ); return hydrated; } public updateManyViewModel(documents: TextDocument[]) { documents.forEach((document) => { const targetProject = this.getAll().find((project) => document.uri.includes(project.tsConfigPath) ); const aureliaProgram = targetProject?.aureliaProgram; if (!aureliaProgram) return; aureliaProgram.aureliaComponents.updateOne( aureliaProgram.tsMorphProject.get(), document ); }); } public updateManyView(documents: TextDocument[]) { documents.forEach((document) => { const targetProject = this.getAll().find((project) => document.uri.includes(project.tsConfigPath) ); const aureliaProgram = targetProject?.aureliaProgram; if (!aureliaProgram) return; aureliaProgram.aureliaComponents.updateOneView(document); }); } private async initAndSet(packageJsonPaths: string[]) { this.resetAureliaProjects(); const aureliaProjectPaths = getAureliaProjectPaths(packageJsonPaths); aureliaProjectPaths.forEach((aureliaProjectPath) => { const alreadyHasProject = this.aureliaProjects.find( (project) => project.tsConfigPath === aureliaProjectPath ); if (alreadyHasProject) { return; } this.aureliaProjects.push({ tsConfigPath: UriUtils.toSysPath(aureliaProjectPath), aureliaProgram: null, }); }); } private async addAureliaProgramToEachProject( documentsPaths: string[], aureliaProjectSettings: IAureliaProjectSetting | undefined, forceReinit: boolean = false ) { const aureliaProjects = this.getAll(); /** TODO rename: tsConfigPath -> projectPath (or sth else) */ aureliaProjects.every(async ({ tsConfigPath, aureliaProgram }) => { const shouldActivate = getShouldActivate(documentsPaths, tsConfigPath); if (!shouldActivate) return; const shouldHydration = aureliaProgram === null || forceReinit; if (shouldHydration) { const extensionSettings = this.documentSettings.getSettings().aureliaProject; this.documentSettings.setSettings({ ...extensionSettings, aureliaProject: { projectDirectory: tsConfigPath, }, }); aureliaProgram = new AureliaProgram(this.documentSettings); const tsMorphProject = aureliaProgram.tsMorphProject.create(); let compilerObject = compilerObjectMap.get(tsConfigPath); if (compilerObject == null || forceReinit) { const program = tsMorphProject.getProgram(); // [PERF]: 1.87967675s compilerObject = program.compilerObject; compilerObjectMap.set(tsConfigPath, compilerObject); } if (compilerObject != null) { aureliaProgram.setProgram(compilerObject); } } const projectOptions: IAureliaProjectSetting = { ...aureliaProjectSettings, rootDirectory: tsConfigPath, }; // [PERF]: 0.67967675s if (aureliaProgram == null) return; aureliaProgram.initAureliaComponents(projectOptions); const targetAureliaProject = aureliaProjects.find( (auP) => auP.tsConfigPath === tsConfigPath ); if (!targetAureliaProject) return; targetAureliaProject.aureliaProgram = aureliaProgram; }); } /** * Check whether a textDocument (via its uri), if it is already included * in the Aurelia project. */ private isDocumentIncluded({ uri }: TextDocument): boolean { const isIncluded = this.aureliaProjects.some(({ tsConfigPath }) => { return uri.includes(tsConfigPath); }); return isIncluded; } private resetAureliaProjects(): void { this.aureliaProjects = []; } } function getShouldActivate(documentsPaths: string[], tsConfigPath: string) { return documentsPaths.some((docPath) => { const result = docPath.includes(tsConfigPath); return result; }); } function isAureliaProjectBasedOnPackageJson(packageJsonPath: string): boolean { const packageJson = JSON.parse( fs.readFileSync(packageJsonPath, 'utf-8') ) as Record<string, Record<string, string>>; const dep = packageJson['dependencies']; let hasAuInDep = false; if (dep != null) { const isAuV1App = dep['aurelia-framework'] !== undefined; const isAuV1Plugin = dep['aurelia-binding'] !== undefined; const isAuV1Cli = dep['aurelia-cli'] !== undefined; const isAuV2App = dep['aurelia'] !== undefined; const isAuV2Plugin = dep['@aurelia/runtime'] !== undefined; const isAuApp = isAuV1App || isAuV1Cli || isAuV2App; const isAuPlugin = isAuV1Plugin || isAuV2Plugin; hasAuInDep = isAuApp || isAuPlugin; } let hasAuInDevDep = false; const devDep = packageJson['devDependencies']; if (devDep != null) { const isAuV1AppDev = devDep['aurelia-framework'] !== undefined; const isAuV1PluginDev = devDep['aurelia-binding'] !== undefined; const isAuV1CliDev = devDep['aurelia-cli'] !== undefined; const isAuV2AppDev = devDep['aurelia'] !== undefined; const isAuV2PluginDev = devDep['@aurelia/runtime'] !== undefined; const isAuApp = isAuV1AppDev || isAuV1CliDev || isAuV2AppDev; const isAuPlugin = isAuV1PluginDev || isAuV2PluginDev; hasAuInDevDep = isAuApp || isAuPlugin; } const isAu = hasAuInDep || hasAuInDevDep; return isAu; } /** * @param packageJsonPaths - All paths, that have a package.json file * @param activeDocuments - Current active documents (eg. on open of Editor) * @returns All project paths, that are an Aurelia project * * 1. Save paths to Aurelia project only. * 1.1 Based on package.json * 1.2 Detect if is Aurelia project */ function getAureliaProjectPaths(packageJsonPaths: string[]): string[] { const aureliaProjectsRaw = packageJsonPaths.filter((packageJsonPath) => { const isAu = isAureliaProjectBasedOnPackageJson(packageJsonPath); return isAu; }); const aureliaProjectPaths = aureliaProjectsRaw.map((aureliaProject) => { const dirName = nodePath.dirname(UriUtils.toSysPath(aureliaProject)); return dirName; }); return aureliaProjectPaths; } function getPackageJsonPaths(extensionSettings: ExtensionSettings) { const aureliaProject = extensionSettings.aureliaProject; const workspaceRootUri = aureliaProject?.rootDirectory?.trim() ?? ''; const cwd = UriUtils.toSysPath(workspaceRootUri); /* prettier-ignore */ logger.log(`Get package.json based on: ${cwd}`,{env:'test'}); const ignore: string[] = []; const exclude = aureliaProject?.exclude; if (exclude != null) { ignore.push(...exclude); } const packageJsonInclude = aureliaProject?.packageJsonInclude; let globIncludePattern: string[] = []; if (packageJsonInclude != null && packageJsonInclude.length > 0) { /* prettier-ignore */ logger.log('Using setting `aureliaProject.packageJsonInclude`.', { logLevel: 'INFO' }); const packageJsonIncludes = packageJsonInclude.map( (path) => `**/${path}/**/package.json` ); globIncludePattern.push(...packageJsonIncludes); } else { globIncludePattern = ['**/package.json']; } try { const packageJsonPaths = fastGlob.sync(globIncludePattern, { // const packageJsonPaths = fastGlob.sync('**/package.json', { absolute: true, ignore, cwd, }); logPackageJsonInfo(packageJsonPaths, globIncludePattern, ignore); return packageJsonPaths; } catch (error) { /* prettier-ignore */ console.log('TCL: getPackageJsonPaths -> error', error) return []; } } function logFoundAureliaProjects(aureliaProjects: IAureliaProject[]) { /* prettier-ignore */ logger.log(`Found ${aureliaProjects.length} Aurelia project(s) in: `, { logLevel: 'INFO' }); aureliaProjects.forEach(({ tsConfigPath }) => { /* prettier-ignore */ logger.log(` ${tsConfigPath}`, { logLevel: 'INFO' }); }); } function logHasNoAureliaProject() { /* prettier-ignore */ logger.log('No active Aurelia project found.', { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(' Extension will activate, as soon as a file inside an Aurelia project is opened.', { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(' Or execute command "Aurelia: Reload Extension", if nothing happens.', { logLevel: 'INFO' }); } function logPackageJsonInfo( packageJsonPaths: string[], globIncludePattern: string[], ignore: string[] ) { if (globIncludePattern.length === 0) { /* prettier-ignore */ logger.log(`Did not found a package.json file. Searched in: ${globIncludePattern.join(', ')} `, { logLevel: 'INFO' }); } else { /* prettier-ignore */ logger.log(`Found ${packageJsonPaths.length} package.json file(s):`, { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(` ${packageJsonPaths.join(', ')}`, { logLevel: 'INFO' }); /* prettier-ignore */ logger.log(` Searched in: ${globIncludePattern.join(', ')}`, { logLevel: 'INFO' }); } /* prettier-ignore */ logger.log(` Excluded: ${ignore.join(', ')}`, { logLevel: 'INFO' }); } /** * Document changes -> version > 1. */ function hasDocumentChanged({ version }: TextDocument): boolean { return version > 1; }
the_stack
import { AST_TOKEN_TYPES, createEntity, DataType, GLSLContext, IComputeModel, STORAGE_CLASS, } from '@antv/g-webgpu-core'; import { isTypedArray } from 'lodash'; import regl from 'regl'; import quadVert from './shaders/quad.vert.glsl'; interface DataTextureDescriptor { id: number; data: | number | number[] | Float32Array | Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | undefined; textureWidth: number; texture: regl.Texture2D; texelCount: number; originalDataLength: number; elementsPerTexel: number; typedArrayConstructor?: Function; isOutput: boolean; } let textureId = 0; const debug = false; /** * adaptor for regl.DrawCommand */ export default class ReglComputeModel implements IComputeModel { private entity = createEntity(); private texFBO: regl.Framebuffer2D; private computeCommand: regl.DrawCommand; private textureCache: { [textureName: string]: DataTextureDescriptor; } = {}; private outputTextureName: string; private swapOutputTextureName: string; private compiledPingpong: boolean; private dynamicPingpong: boolean; constructor(private reGl: regl.Regl, private context: GLSLContext) { const uniforms: Record<string, any> = {}; this.context.uniforms.forEach((uniform) => { const { name, type, data, isReferer, storageClass } = uniform; // store data with a 2D texture if (storageClass === STORAGE_CLASS.StorageBuffer) { if (!isReferer) { this.textureCache[name] = this.calcDataTexture(name, type, data!); const { textureWidth: width, isOutput } = this.textureCache[name]; uniforms[`${name}Size`] = [width, width]; if (isOutput) { this.outputTextureName = name; if (this.context.needPingpong) { this.outputTextureName = `${name}Output`; this.textureCache[this.outputTextureName] = this.calcDataTexture( name, type, data!, ); } } } else { this.textureCache[name] = { data: undefined, }; // refer to another kernel's output, // the referred kernel may not have been initialized, so we use dynamic way here uniforms[`${name}Size`] = () => // @ts-ignore data.compiledBundle.context.output.textureSize; } uniforms[name] = () => { if (debug) { console.log( `[${this.entity}]: ${name} ${this.textureCache[name].id}`, ); } return this.textureCache[name].texture; }; } else if (storageClass === STORAGE_CLASS.Uniform) { if ( data && (Array.isArray(data) || isTypedArray(data)) && (data as ArrayLike<number>).length > 16 ) { // up to mat4 which includes 16 elements throw new Error(`invalid data type ${type}`); } // get uniform dynamically uniforms[name] = () => uniform.data; } }); const { textureWidth, texelCount } = this.getOuputDataTexture(); // 传入 output 纹理尺寸和数据长度,便于多余的 texel 提前退出 uniforms.u_OutputTextureSize = [textureWidth, textureWidth]; uniforms.u_OutputTexelCount = texelCount; // 保存在 Kernel 的上下文中,供其他 Kernel 引用 this.context.output.textureSize = [textureWidth!, textureWidth!]; const drawParams: regl.DrawConfig = { attributes: { a_Position: [ [-1, 1, 0], [-1, -1, 0], [1, 1, 0], [1, -1, 0], ], a_TexCoord: [ [0, 1], [0, 0], [1, 1], [1, 0], ], }, frag: `#ifdef GL_FRAGMENT_PRECISION_HIGH precision highp float; #else precision mediump float; #endif ${this.context.shader}`, uniforms, vert: quadVert, // TODO: use a fullscreen triangle instead. primitive: 'triangle strip', count: 4, }; this.computeCommand = this.reGl(drawParams); } public run() { if (this.context.maxIteration > 1 && this.context.needPingpong) { this.compiledPingpong = true; } // need pingpong when (@in@out and execute(10)) or use `setBinding('out', self)` // this.needPingpong = // !!(this.context.maxIteration > 1 && this.context.needPingpong); // if (this.relativeOutputTextureNames.length) { // const { id, texture } = this.getOuputDataTexture(); // this.relativeOutputTextureNames.forEach((name) => { // this.textureCache[name].id = id; // this.textureCache[name].texture = texture; // }); // this.swap(); // } if (this.compiledPingpong || this.dynamicPingpong) { this.swap(); } this.texFBO = this.reGl.framebuffer({ color: this.getOuputDataTexture().texture, }); this.texFBO.use(() => { this.computeCommand(); }); if (debug) { console.log(`[${this.entity}]: output ${this.getOuputDataTexture().id}`); } } public async readData() { let pixels: Uint8Array | Float32Array; this.reGl({ framebuffer: this.texFBO, })(() => { pixels = this.reGl.read(); }); // @ts-ignore if (pixels) { const { originalDataLength, elementsPerTexel, typedArrayConstructor = Float32Array, } = this.getOuputDataTexture(); let formattedPixels = []; if (elementsPerTexel !== 4) { for (let i = 0; i < pixels.length; i += 4) { if (elementsPerTexel === 1) { formattedPixels.push(pixels[i]); } else if (elementsPerTexel === 2) { formattedPixels.push(pixels[i], pixels[i + 1]); } else { formattedPixels.push(pixels[i], pixels[i + 1], pixels[i + 2]); } } } else { // @ts-ignore formattedPixels = pixels; } // 截取多余的部分 // @ts-ignore return new typedArrayConstructor( formattedPixels.slice(0, originalDataLength), ); } return new Float32Array(); } public confirmInput(model: IComputeModel, inputName: string) { let inputModel: ReglComputeModel; // refer to self, same as pingpong if (this.entity === (model as ReglComputeModel).entity) { this.dynamicPingpong = true; inputModel = this; } else { inputModel = model as ReglComputeModel; } this.textureCache[inputName].id = inputModel.getOuputDataTexture().id; this.textureCache[ inputName ].texture = inputModel.getOuputDataTexture().texture; if (debug) { console.log( `[${this.entity}]: confirm input ${inputName} from model ${ inputModel.entity }, ${(inputModel as ReglComputeModel).getOuputDataTexture().id}`, ); } } public updateUniform() { // already get uniform's data dynamically when created, do nothing here } public updateBuffer( bufferName: string, data: | number[] | Float32Array | Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array, offset: number = 0, ) { // regenerate data texture const buffer = this.context.uniforms.find( ({ name }) => name === bufferName, ); if (buffer) { const { texture, data: paddingData } = this.calcDataTexture( bufferName, buffer.type, data, ); // TODO: destroy outdated texture this.textureCache[bufferName].data = paddingData; this.textureCache[bufferName].texture = texture; } } public destroy() { // regl will destroy all resources } private swap() { if (!this.swapOutputTextureName) { this.createSwapOutputDataTexture(); } if (this.compiledPingpong) { const outputTextureUniformName = this.context.output.name; this.textureCache[ outputTextureUniformName ].id = this.getOuputDataTexture().id; this.textureCache[ outputTextureUniformName ].texture = this.getOuputDataTexture().texture; } const tmp = this.outputTextureName; this.outputTextureName = this.swapOutputTextureName; this.swapOutputTextureName = tmp; if (debug) { console.log( `[${this.entity}]: after swap, output ${this.getOuputDataTexture().id}`, ); } } private getOuputDataTexture() { return this.textureCache[this.outputTextureName]; } private createSwapOutputDataTexture() { const texture = this.cloneDataTexture(this.getOuputDataTexture()); this.swapOutputTextureName = `${this.entity}-swap`; this.textureCache[this.swapOutputTextureName] = texture; } private cloneDataTexture(texture: DataTextureDescriptor) { const { data, textureWidth } = texture; return { ...texture, id: textureId++, // @ts-ignore texture: this.reGl.texture({ width: textureWidth, height: textureWidth, data, type: 'float', }), }; } private calcDataTexture( name: string, type: DataType, data: | number | number[] | Float32Array | Uint8Array | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array, ) { let elementsPerTexel = 1; if (type === AST_TOKEN_TYPES.Vector4FloatArray) { elementsPerTexel = 4; } // 用 0 补全不足 vec4 的部分 const paddingData: number[] = []; for (let i = 0; i < (data as number[]).length; i += elementsPerTexel) { if (elementsPerTexel === 1) { paddingData.push((data as number[])[i], 0, 0, 0); } else if (elementsPerTexel === 2) { paddingData.push( (data as number[])[i], (data as number[])[i + 1], 0, 0, ); } else if (elementsPerTexel === 3) { paddingData.push( (data as number[])[i], (data as number[])[i + 1], (data as number[])[i + 2], 0, ); } else if (elementsPerTexel === 4) { paddingData.push( (data as number[])[i], (data as number[])[i + 1], (data as number[])[i + 2], (data as number[])[i + 3], ); } } // 使用纹理存储,例如 Array(8) 使用 3 * 3 纹理,末尾空白使用 0 填充 const originalDataLength = (data as ArrayLike<number>).length; const texelCount = Math.ceil(originalDataLength / elementsPerTexel); const width = Math.ceil(Math.sqrt(texelCount)); const paddingTexelCount = width * width; if (texelCount < paddingTexelCount) { paddingData.push( ...new Array((paddingTexelCount - texelCount) * 4).fill(0), ); } const texture = this.reGl.texture({ width, height: width, data: paddingData, type: 'float', }); return { id: textureId++, data: paddingData, originalDataLength, typedArrayConstructor: isTypedArray(data) ? data!.constructor : undefined, textureWidth: width, texture, texelCount, elementsPerTexel, isOutput: name === this.context.output.name, }; } }
the_stack
import { $, append, createStyleSheet, EventHelper, EventLike, getElementsByTagName } from 'vs/base/browser/dom'; import { DomEmitter } from 'vs/base/browser/event'; import { EventType, Gesture, GestureEvent } from 'vs/base/browser/touch'; import { Delayer } from 'vs/base/common/async'; import { memoize } from 'vs/base/common/decorators'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle'; import { isMacintosh } from 'vs/base/common/platform'; import 'vs/css!./sash'; /** * Allow the sashes to be visible at runtime. * @remark Use for development purposes only. */ let DEBUG = false; // DEBUG = Boolean("true"); // done "weirdly" so that a lint warning prevents you from pushing this /** * A vertical sash layout provider provides position and height for a sash. */ export interface IVerticalSashLayoutProvider { getVerticalSashLeft(sash: Sash): number; getVerticalSashTop?(sash: Sash): number; getVerticalSashHeight?(sash: Sash): number; } /** * A vertical sash layout provider provides position and width for a sash. */ export interface IHorizontalSashLayoutProvider { getHorizontalSashTop(sash: Sash): number; getHorizontalSashLeft?(sash: Sash): number; getHorizontalSashWidth?(sash: Sash): number; } type ISashLayoutProvider = IVerticalSashLayoutProvider | IHorizontalSashLayoutProvider; export interface ISashEvent { readonly startX: number; readonly currentX: number; readonly startY: number; readonly currentY: number; readonly altKey: boolean; } export enum OrthogonalEdge { North = 'north', South = 'south', East = 'east', West = 'west' } export interface ISashOptions { /** * Whether a sash is horizontal or vertical. */ readonly orientation: Orientation; /** * The width or height of a vertical or horizontal sash, respectively. */ readonly size?: number; /** * A reference to another sash, perpendicular to this one, which * aligns at the start of this one. A corner sash will be created * automatically at that location. * * The start of a horizontal sash is its left-most position. * The start of a vertical sash is its top-most position. */ readonly orthogonalStartSash?: Sash; /** * A reference to another sash, perpendicular to this one, which * aligns at the end of this one. A corner sash will be created * automatically at that location. * * The end of a horizontal sash is its right-most position. * The end of a vertical sash is its bottom-most position. */ readonly orthogonalEndSash?: Sash; /** * Provides a hint as to what mouse cursor to use whenever the user * hovers over a corner sash provided by this and an orthogonal sash. */ readonly orthogonalEdge?: OrthogonalEdge; } export interface IVerticalSashOptions extends ISashOptions { readonly orientation: Orientation.VERTICAL; } export interface IHorizontalSashOptions extends ISashOptions { readonly orientation: Orientation.HORIZONTAL; } export const enum Orientation { VERTICAL, HORIZONTAL } export const enum SashState { /** * Disable any UI interaction. */ Disabled, /** * Allow dragging down or to the right, depending on the sash orientation. * * Some OSs allow customizing the mouse cursor differently whenever * some resizable component can't be any smaller, but can be larger. */ AtMinimum, /** * Allow dragging up or to the left, depending on the sash orientation. * * Some OSs allow customizing the mouse cursor differently whenever * some resizable component can't be any larger, but can be smaller. */ AtMaximum, /** * Enable dragging. */ Enabled } let globalSize = 4; const onDidChangeGlobalSize = new Emitter<number>(); export function setGlobalSashSize(size: number): void { globalSize = size; onDidChangeGlobalSize.fire(size); } let globalHoverDelay = 300; const onDidChangeHoverDelay = new Emitter<number>(); export function setGlobalHoverDelay(size: number): void { globalHoverDelay = size; onDidChangeHoverDelay.fire(size); } interface PointerEvent extends EventLike { readonly pageX: number; readonly pageY: number; readonly altKey: boolean; readonly target: EventTarget | null; } interface IPointerEventFactory { readonly onPointerMove: Event<PointerEvent>; readonly onPointerUp: Event<PointerEvent>; dispose(): void; } class MouseEventFactory implements IPointerEventFactory { private disposables = new DisposableStore(); @memoize get onPointerMove(): Event<PointerEvent> { return this.disposables.add(new DomEmitter(window, 'mousemove')).event; } @memoize get onPointerUp(): Event<PointerEvent> { return this.disposables.add(new DomEmitter(window, 'mouseup')).event; } dispose(): void { this.disposables.dispose(); } } class GestureEventFactory implements IPointerEventFactory { private disposables = new DisposableStore(); @memoize get onPointerMove(): Event<PointerEvent> { return this.disposables.add(new DomEmitter(this.el, EventType.Change)).event; } @memoize get onPointerUp(): Event<PointerEvent> { return this.disposables.add(new DomEmitter(this.el, EventType.End)).event; } constructor(private el: HTMLElement) { } dispose(): void { this.disposables.dispose(); } } class OrthogonalPointerEventFactory implements IPointerEventFactory { @memoize get onPointerMove(): Event<PointerEvent> { return this.factory.onPointerMove; } @memoize get onPointerUp(): Event<PointerEvent> { return this.factory.onPointerUp; } constructor(private factory: IPointerEventFactory) { } dispose(): void { // noop } } const PointerEventsDisabledCssClass = 'pointer-events-disabled'; /** * The {@link Sash} is the UI component which allows the user to resize other * components. It's usually an invisible horizontal or vertical line which, when * hovered, becomes highlighted and can be dragged along the perpendicular dimension * to its direction. * * Features: * - Touch event handling * - Corner sash support * - Hover with different mouse cursor support * - Configurable hover size * - Linked sash support, for 2x2 corner sashes */ export class Sash extends Disposable { private el: HTMLElement; private layoutProvider: ISashLayoutProvider; private orientation: Orientation; private size: number; private hoverDelay = globalHoverDelay; private hoverDelayer = this._register(new Delayer(this.hoverDelay)); private _state: SashState = SashState.Enabled; private readonly onDidEnablementChange = this._register(new Emitter<SashState>()); private readonly _onDidStart = this._register(new Emitter<ISashEvent>()); private readonly _onDidChange = this._register(new Emitter<ISashEvent>()); private readonly _onDidReset = this._register(new Emitter<void>()); private readonly _onDidEnd = this._register(new Emitter<void>()); private readonly orthogonalStartSashDisposables = this._register(new DisposableStore()); private _orthogonalStartSash: Sash | undefined; private readonly orthogonalStartDragHandleDisposables = this._register(new DisposableStore()); private _orthogonalStartDragHandle: HTMLElement | undefined; private readonly orthogonalEndSashDisposables = this._register(new DisposableStore()); private _orthogonalEndSash: Sash | undefined; private readonly orthogonalEndDragHandleDisposables = this._register(new DisposableStore()); private _orthogonalEndDragHandle: HTMLElement | undefined; get state(): SashState { return this._state; } get orthogonalStartSash(): Sash | undefined { return this._orthogonalStartSash; } get orthogonalEndSash(): Sash | undefined { return this._orthogonalEndSash; } /** * The state of a sash defines whether it can be interacted with by the user * as well as what mouse cursor to use, when hovered. */ set state(state: SashState) { if (this._state === state) { return; } this.el.classList.toggle('disabled', state === SashState.Disabled); this.el.classList.toggle('minimum', state === SashState.AtMinimum); this.el.classList.toggle('maximum', state === SashState.AtMaximum); this._state = state; this.onDidEnablementChange.fire(state); } /** * An event which fires whenever the user starts dragging this sash. */ readonly onDidStart: Event<ISashEvent> = this._onDidStart.event; /** * An event which fires whenever the user moves the mouse while * dragging this sash. */ readonly onDidChange: Event<ISashEvent> = this._onDidChange.event; /** * An event which fires whenever the user double clicks this sash. */ readonly onDidReset: Event<void> = this._onDidReset.event; /** * An event which fires whenever the user stops dragging this sash. */ readonly onDidEnd: Event<void> = this._onDidEnd.event; /** * A linked sash will be forwarded the same user interactions and events * so it moves exactly the same way as this sash. * * Useful in 2x2 grids. Not meant for widespread usage. */ linkedSash: Sash | undefined = undefined; /** * A reference to another sash, perpendicular to this one, which * aligns at the start of this one. A corner sash will be created * automatically at that location. * * The start of a horizontal sash is its left-most position. * The start of a vertical sash is its top-most position. */ set orthogonalStartSash(sash: Sash | undefined) { this.orthogonalStartDragHandleDisposables.clear(); this.orthogonalStartSashDisposables.clear(); if (sash) { const onChange = (state: SashState) => { this.orthogonalStartDragHandleDisposables.clear(); if (state !== SashState.Disabled) { this._orthogonalStartDragHandle = append(this.el, $('.orthogonal-drag-handle.start')); this.orthogonalStartDragHandleDisposables.add(toDisposable(() => this._orthogonalStartDragHandle!.remove())); this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, 'mouseenter')).event (() => Sash.onMouseEnter(sash), undefined, this.orthogonalStartDragHandleDisposables); this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, 'mouseleave')).event (() => Sash.onMouseLeave(sash), undefined, this.orthogonalStartDragHandleDisposables); } }; this.orthogonalStartSashDisposables.add(sash.onDidEnablementChange.event(onChange, this)); onChange(sash.state); } this._orthogonalStartSash = sash; } /** * A reference to another sash, perpendicular to this one, which * aligns at the end of this one. A corner sash will be created * automatically at that location. * * The end of a horizontal sash is its right-most position. * The end of a vertical sash is its bottom-most position. */ set orthogonalEndSash(sash: Sash | undefined) { this.orthogonalEndDragHandleDisposables.clear(); this.orthogonalEndSashDisposables.clear(); if (sash) { const onChange = (state: SashState) => { this.orthogonalEndDragHandleDisposables.clear(); if (state !== SashState.Disabled) { this._orthogonalEndDragHandle = append(this.el, $('.orthogonal-drag-handle.end')); this.orthogonalEndDragHandleDisposables.add(toDisposable(() => this._orthogonalEndDragHandle!.remove())); this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, 'mouseenter')).event (() => Sash.onMouseEnter(sash), undefined, this.orthogonalEndDragHandleDisposables); this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, 'mouseleave')).event (() => Sash.onMouseLeave(sash), undefined, this.orthogonalEndDragHandleDisposables); } }; this.orthogonalEndSashDisposables.add(sash.onDidEnablementChange.event(onChange, this)); onChange(sash.state); } this._orthogonalEndSash = sash; } /** * Create a new vertical sash. * * @param container A DOM node to append the sash to. * @param verticalLayoutProvider A vertical layout provider. * @param options The options. */ constructor(container: HTMLElement, verticalLayoutProvider: IVerticalSashLayoutProvider, options: IVerticalSashOptions); /** * Create a new horizontal sash. * * @param container A DOM node to append the sash to. * @param horizontalLayoutProvider A horizontal layout provider. * @param options The options. */ constructor(container: HTMLElement, horizontalLayoutProvider: IHorizontalSashLayoutProvider, options: IHorizontalSashOptions); constructor(container: HTMLElement, layoutProvider: ISashLayoutProvider, options: ISashOptions) { super(); this.el = append(container, $('.monaco-sash')); if (options.orthogonalEdge) { this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`); } if (isMacintosh) { this.el.classList.add('mac'); } const onMouseDown = this._register(new DomEmitter(this.el, 'mousedown')).event; this._register(onMouseDown(e => this.onPointerStart(e, new MouseEventFactory()), this)); const onMouseDoubleClick = this._register(new DomEmitter(this.el, 'dblclick')).event; this._register(onMouseDoubleClick(this.onPointerDoublePress, this)); const onMouseEnter = this._register(new DomEmitter(this.el, 'mouseenter')).event; this._register(onMouseEnter(() => Sash.onMouseEnter(this))); const onMouseLeave = this._register(new DomEmitter(this.el, 'mouseleave')).event; this._register(onMouseLeave(() => Sash.onMouseLeave(this))); this._register(Gesture.addTarget(this.el)); const onTouchStart = Event.map(this._register(new DomEmitter(this.el, EventType.Start)).event, e => ({ ...e, target: e.initialTarget ?? null })); this._register(onTouchStart(e => this.onPointerStart(e, new GestureEventFactory(this.el)), this)); const onTap = this._register(new DomEmitter(this.el, EventType.Tap)).event; const onDoubleTap = Event.map( Event.filter( Event.debounce<GestureEvent, { event: GestureEvent; count: number }>(onTap, (res, event) => ({ event, count: (res?.count ?? 0) + 1 }), 250), ({ count }) => count === 2 ), ({ event }) => ({ ...event, target: event.initialTarget ?? null }) ); this._register(onDoubleTap(this.onPointerDoublePress, this)); if (typeof options.size === 'number') { this.size = options.size; if (options.orientation === Orientation.VERTICAL) { this.el.style.width = `${this.size}px`; } else { this.el.style.height = `${this.size}px`; } } else { this.size = globalSize; this._register(onDidChangeGlobalSize.event(size => { this.size = size; this.layout(); })); } this._register(onDidChangeHoverDelay.event(delay => this.hoverDelay = delay)); this.layoutProvider = layoutProvider; this.orthogonalStartSash = options.orthogonalStartSash; this.orthogonalEndSash = options.orthogonalEndSash; this.orientation = options.orientation || Orientation.VERTICAL; if (this.orientation === Orientation.HORIZONTAL) { this.el.classList.add('horizontal'); this.el.classList.remove('vertical'); } else { this.el.classList.remove('horizontal'); this.el.classList.add('vertical'); } this.el.classList.toggle('debug', DEBUG); this.layout(); } private onPointerStart(event: PointerEvent, pointerEventFactory: IPointerEventFactory): void { EventHelper.stop(event); let isMultisashResize = false; if (!(event as any).__orthogonalSashEvent) { const orthogonalSash = this.getOrthogonalSash(event); if (orthogonalSash) { isMultisashResize = true; (event as any).__orthogonalSashEvent = true; orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory)); } } if (this.linkedSash && !(event as any).__linkedSashEvent) { (event as any).__linkedSashEvent = true; this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory)); } if (!this.state) { return; } const iframes = getElementsByTagName('iframe'); for (const iframe of iframes) { iframe.classList.add(PointerEventsDisabledCssClass); // disable mouse events on iframes as long as we drag the sash } const startX = event.pageX; const startY = event.pageY; const altKey = event.altKey; const startEvent: ISashEvent = { startX, currentX: startX, startY, currentY: startY, altKey }; this.el.classList.add('active'); this._onDidStart.fire(startEvent); // fix https://github.com/microsoft/vscode/issues/21675 const style = createStyleSheet(this.el); const updateStyle = () => { let cursor = ''; if (isMultisashResize) { cursor = 'all-scroll'; } else if (this.orientation === Orientation.HORIZONTAL) { if (this.state === SashState.AtMinimum) { cursor = 's-resize'; } else if (this.state === SashState.AtMaximum) { cursor = 'n-resize'; } else { cursor = isMacintosh ? 'row-resize' : 'ns-resize'; } } else { if (this.state === SashState.AtMinimum) { cursor = 'e-resize'; } else if (this.state === SashState.AtMaximum) { cursor = 'w-resize'; } else { cursor = isMacintosh ? 'col-resize' : 'ew-resize'; } } style.textContent = `* { cursor: ${cursor} !important; }`; }; const disposables = new DisposableStore(); updateStyle(); if (!isMultisashResize) { this.onDidEnablementChange.event(updateStyle, null, disposables); } const onPointerMove = (e: PointerEvent) => { EventHelper.stop(e, false); const event: ISashEvent = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey }; this._onDidChange.fire(event); }; const onPointerUp = (e: PointerEvent) => { EventHelper.stop(e, false); this.el.removeChild(style); this.el.classList.remove('active'); this._onDidEnd.fire(); disposables.dispose(); for (const iframe of iframes) { iframe.classList.remove(PointerEventsDisabledCssClass); } }; pointerEventFactory.onPointerMove(onPointerMove, null, disposables); pointerEventFactory.onPointerUp(onPointerUp, null, disposables); disposables.add(pointerEventFactory); } private onPointerDoublePress(e: MouseEvent): void { const orthogonalSash = this.getOrthogonalSash(e); if (orthogonalSash) { orthogonalSash._onDidReset.fire(); } if (this.linkedSash) { this.linkedSash._onDidReset.fire(); } this._onDidReset.fire(); } private static onMouseEnter(sash: Sash, fromLinkedSash: boolean = false): void { if (sash.el.classList.contains('active')) { sash.hoverDelayer.cancel(); sash.el.classList.add('hover'); } else { sash.hoverDelayer.trigger(() => sash.el.classList.add('hover'), sash.hoverDelay).then(undefined, () => { }); } if (!fromLinkedSash && sash.linkedSash) { Sash.onMouseEnter(sash.linkedSash, true); } } private static onMouseLeave(sash: Sash, fromLinkedSash: boolean = false): void { sash.hoverDelayer.cancel(); sash.el.classList.remove('hover'); if (!fromLinkedSash && sash.linkedSash) { Sash.onMouseLeave(sash.linkedSash, true); } } /** * Forcefully stop any user interactions with this sash. * Useful when hiding a parent component, while the user is still * interacting with the sash. */ clearSashHoverState(): void { Sash.onMouseLeave(this); } /** * Layout the sash. The sash will size and position itself * based on its provided {@link ISashLayoutProvider layout provider}. */ layout(): void { if (this.orientation === Orientation.VERTICAL) { const verticalProvider = (<IVerticalSashLayoutProvider>this.layoutProvider); this.el.style.left = verticalProvider.getVerticalSashLeft(this) - (this.size / 2) + 'px'; if (verticalProvider.getVerticalSashTop) { this.el.style.top = verticalProvider.getVerticalSashTop(this) + 'px'; } if (verticalProvider.getVerticalSashHeight) { this.el.style.height = verticalProvider.getVerticalSashHeight(this) + 'px'; } } else { const horizontalProvider = (<IHorizontalSashLayoutProvider>this.layoutProvider); this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - (this.size / 2) + 'px'; if (horizontalProvider.getHorizontalSashLeft) { this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + 'px'; } if (horizontalProvider.getHorizontalSashWidth) { this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + 'px'; } } } private getOrthogonalSash(e: PointerEvent): Sash | undefined { if (!e.target || !(e.target instanceof HTMLElement)) { return undefined; } if (e.target.classList.contains('orthogonal-drag-handle')) { return e.target.classList.contains('start') ? this.orthogonalStartSash : this.orthogonalEndSash; } return undefined; } override dispose(): void { super.dispose(); this.el.remove(); } }
the_stack
import { ArgumentNode, ASTNode, DefinitionNode, DirectiveNode, DocumentNode, FieldNode, FragmentDefinitionNode, FragmentSpreadNode, GraphQLError, InlineFragmentNode, Kind, OperationDefinitionNode, parse, SelectionNode, SelectionSetNode } from "graphql"; import { baseType, Directive, DirectiveTargetElement, FieldDefinition, InterfaceType, isCompositeType, isInterfaceType, isLeafType, isNullableType, isObjectType, isUnionType, ObjectType, runtimeTypesIntersects, Schema, SchemaRootKind, mergeVariables, Variables, variablesInArguments, VariableDefinitions, variableDefinitionsFromAST, CompositeType, typenameFieldName, NamedType, } from "./definitions"; import { assert, mapEntries, MapWithCachedArrays, MultiMap } from "./utils"; import { argumentsEquals, argumentsFromAST, isValidValue, valueToAST, valueToString } from "./values"; function validate(condition: any, message: () => string, sourceAST?: ASTNode): asserts condition { if (!condition) { throw new GraphQLError(message(), sourceAST); } } function haveSameDirectives<TElement extends OperationElement>(op1: TElement, op2: TElement): boolean { if (op1.appliedDirectives.length != op2.appliedDirectives.length) { return false; } for (const thisDirective of op1.appliedDirectives) { if (!op2.appliedDirectives.some(thatDirective => thisDirective.name === thatDirective.name && argumentsEquals(thisDirective.arguments(), thatDirective.arguments()))) { return false; } } return true; } abstract class AbstractOperationElement<T extends AbstractOperationElement<T>> extends DirectiveTargetElement<T> { constructor( schema: Schema, private readonly variablesInElement: Variables ) { super(schema); } variables(): Variables { return mergeVariables(this.variablesInElement, this.variablesInAppliedDirectives()); } abstract updateForAddingTo(selection: SelectionSet): T; } export class Field<TArgs extends {[key: string]: any} = {[key: string]: any}> extends AbstractOperationElement<Field<TArgs>> { readonly kind = 'Field' as const; constructor( readonly definition: FieldDefinition<CompositeType>, readonly args: TArgs = Object.create(null), readonly variableDefinitions: VariableDefinitions = new VariableDefinitions(), readonly alias?: string ) { super(definition.schema(), variablesInArguments(args)); this.validate(); } get name(): string { return this.definition.name; } responseName(): string { return this.alias ? this.alias : this.name; } get parentType(): CompositeType { return this.definition.parent; } withUpdatedDefinition(newDefinition: FieldDefinition<any>): Field<TArgs> { const newField = new Field<TArgs>(newDefinition, this.args, this.variableDefinitions, this.alias); for (const directive of this.appliedDirectives) { newField.applyDirective(directive.definition!, directive.arguments()); } return newField; } appliesTo(type: ObjectType | InterfaceType): boolean { const definition = type.field(this.name); return !!definition && this.selects(definition); } selects(definition: FieldDefinition<any>, assumeValid: boolean = false): boolean { // We've already validated that the field selects the definition on which it was built. if (definition == this.definition) { return true; } // This code largely mirrors validate, so we could generalize that and return false on exception, but this // method is called fairly often and that has been shown to impact performance quite a lot. So a little // bit of code duplication is ok. if (this.name !== definition.name) { return false; } // We need to make sure the field has valid values for every non-optional argument. for (const argDef of definition.arguments()) { const appliedValue = this.args[argDef.name]; if (appliedValue === undefined) { if (argDef.defaultValue === undefined && !isNullableType(argDef.type!)) { return false; } } else { if (!assumeValid && !isValidValue(appliedValue, argDef, this.variableDefinitions)) { return false; } } } // We also make sure the field application does not have non-null values for field that are not part of the definition. if (!assumeValid) { for (const [name, value] of Object.entries(this.args)) { if (value !== null && definition.argument(name) === undefined) { return false } } } return true; } private validate() { validate(this.name === this.definition.name, () => `Field name "${this.name}" cannot select field "${this.definition.coordinate}: name mismatch"`); // We need to make sure the field has valid values for every non-optional argument. for (const argDef of this.definition.arguments()) { const appliedValue = this.args[argDef.name]; if (appliedValue === undefined) { validate( argDef.defaultValue !== undefined || isNullableType(argDef.type!), () => `Missing mandatory value "${argDef.name}" in field selection "${this}"`); } else { validate( isValidValue(appliedValue, argDef, this.variableDefinitions), () => `Invalid value ${valueToString(appliedValue)} for argument "${argDef.coordinate}" of type ${argDef.type}`) } } // We also make sure the field application does not have non-null values for field that are not part of the definition. for (const [name, value] of Object.entries(this.args)) { validate( value === null || this.definition.argument(name) !== undefined, () => `Unknown argument "${name}" in field application of "${this.name}"`); } } updateForAddingTo(selectionSet: SelectionSet): Field<TArgs> { const selectionParent = selectionSet.parentType; const fieldParent = this.definition.parent; if (selectionParent.name !== fieldParent.name) { if (this.name === typenameFieldName) { return this.withUpdatedDefinition(selectionParent.typenameField()!); } // We accept adding a selection of an interface field to a selection of one of its subtype. But otherwise, it's invalid. // Do note that the field might come from a supergraph while the selection is on a subgraph, so we avoid relying on isDirectSubtype (because // isDirectSubtype relies on the subtype knowing which interface it implements, but the one of the subgraph might not declare implementing // the supergraph interface, even if it does in the subgraph). validate( !isUnionType(selectionParent) && ( (isInterfaceType(fieldParent) && fieldParent.allImplementations().some(i => i.name == selectionParent.name)) || (isObjectType(fieldParent) && fieldParent.name == selectionParent.name) ), () => `Cannot add selection of field "${this.definition.coordinate}" to selection set of parent type "${selectionSet.parentType}"` ); const fieldDef = selectionParent.field(this.name); validate(fieldDef, () => `Cannot add selection of field "${this.definition.coordinate}" to selection set of parent type "${selectionParent} (that does not declare that type)"`); return this.withUpdatedDefinition(fieldDef); } return this; } equals(that: OperationElement): boolean { if (this === that) { return true; } return that.kind === 'Field' && this.name === that.name && this.alias === that.alias && argumentsEquals(this.args, that.args) && haveSameDirectives(this, that); } toString(): string { const alias = this.alias ? this.alias + ': ' : ''; const entries = Object.entries(this.args); const args = entries.length == 0 ? '' : '(' + entries.map(([n, v]) => `${n}: ${valueToString(v, this.definition.argument(n)?.type)}`).join(', ') + ')'; return alias + this.name + args + this.appliedDirectivesToString(); } } export class FragmentElement extends AbstractOperationElement<FragmentElement> { readonly kind = 'FragmentElement' as const; readonly typeCondition?: CompositeType; constructor( private readonly sourceType: CompositeType, typeCondition?: string | CompositeType, ) { // TODO: we should do some validation here (remove the ! with proper error, and ensure we have some intersection between // the source type and the type condition) super(sourceType.schema(), []); this.typeCondition = typeCondition !== undefined && typeof typeCondition === 'string' ? this.schema().type(typeCondition)! as CompositeType : typeCondition; } get parentType(): CompositeType { return this.sourceType; } withUpdatedSourceType(newSourceType: CompositeType): FragmentElement { const newFragment = new FragmentElement(newSourceType, this.typeCondition); for (const directive of this.appliedDirectives) { newFragment.applyDirective(directive.definition!, directive.arguments()); } return newFragment; } updateForAddingTo(selectionSet: SelectionSet): FragmentElement { const selectionParent = selectionSet.parentType; const fragmentParent = this.parentType; const typeCondition = this.typeCondition; if (selectionParent != fragmentParent) { // As long as there an intersection between the type we cast into and the selection parent, it's ok. validate( !typeCondition || runtimeTypesIntersects(selectionParent, typeCondition), () => `Cannot add fragment of parent type "${this.parentType}" to selection set of parent type "${selectionSet.parentType}"` ); return this.withUpdatedSourceType(selectionParent); } return this; } equals(that: OperationElement): boolean { if (this === that) { return true; } return that.kind === 'FragmentElement' && this.typeCondition?.name === that.typeCondition?.name && haveSameDirectives(this, that); } toString(): string { return '...' + (this.typeCondition ? ' on ' + this.typeCondition : '') + this.appliedDirectivesToString(); } } export type OperationElement = Field<any> | FragmentElement; export type OperationPath = OperationElement[]; export function sameOperationPaths(p1: OperationPath, p2: OperationPath): boolean { if (p1 === p2) { return true; } if (p1.length !== p2.length) { return false; } for (let i = 0; i < p1.length; i++) { if (!p1[i].equals(p2[i])) { return false; } } return true; } export type RootOperationPath = { rootKind: SchemaRootKind, path: OperationPath } // TODO Operations can also have directives export class Operation { constructor( readonly rootKind: SchemaRootKind, readonly selectionSet: SelectionSet, readonly variableDefinitions: VariableDefinitions, readonly name?: string) { } optimize(fragments?: NamedFragments, minUsagesToOptimize: number = 2): Operation { if (!fragments) { return this; } let optimizedSelection = this.selectionSet.optimize(fragments); if (optimizedSelection === this.selectionSet) { return this; } // Optimizing fragments away, and then de-optimizing if it's used less than we want, feels a bit wasteful, // but it's simple and probably don't matter too much in practice (we only call this optimization on the // final compted query plan, so not a very hot path; plus in most case we won't even reach that point // either because there is no fragment, or none will have been optimized away and we'll exit above). We // can optimize later if this show up in profiling though. if (minUsagesToOptimize > 1) { const usages = new Map<string, number>(); optimizedSelection.collectUsedFragmentNames(usages); for (const fragment of fragments.names()) { if (!usages.has(fragment)) { usages.set(fragment, 0); } } const toDeoptimize = mapEntries(usages).filter(([_, count]) => count < minUsagesToOptimize).map(([name]) => name); optimizedSelection = optimizedSelection.expandFragments(toDeoptimize); } return new Operation(this.rootKind, optimizedSelection, this.variableDefinitions, this.name); } expandAllFragments(): Operation { const expandedSelections = this.selectionSet.expandFragments(); if (expandedSelections === this.selectionSet) { return this; } return new Operation( this.rootKind, expandedSelections, this.variableDefinitions, this.name ); } toString(expandFragments: boolean = false, prettyPrint: boolean = true): string { return this.selectionSet.toOperationString(this.rootKind, this.variableDefinitions, this.name, expandFragments, prettyPrint); } } function addDirectiveNodesToElement(directiveNodes: readonly DirectiveNode[] | undefined, element: DirectiveTargetElement<any>) { if (!directiveNodes) { return; } const schema = element.schema(); for (const node of directiveNodes) { const directiveDef = schema.directive(node.name.value); validate(directiveDef, () => `Unknown directive "@${node.name.value}" in selection`) element.applyDirective(directiveDef, argumentsFromAST(directiveDef.coordinate, node.arguments, directiveDef)); } } export function selectionSetOf(parentType: CompositeType, selection: Selection): SelectionSet { const selectionSet = new SelectionSet(parentType); selectionSet.add(selection); return selectionSet; } export class NamedFragmentDefinition extends DirectiveTargetElement<NamedFragmentDefinition> { constructor( schema: Schema, readonly name: string, readonly typeCondition: CompositeType, readonly selectionSet: SelectionSet ) { super(schema); } variables(): Variables { return mergeVariables(this.variablesInAppliedDirectives(), this.selectionSet.usedVariables()); } collectUsedFragmentNames(collector: Map<string, number>) { this.selectionSet.collectUsedFragmentNames(collector); } toFragmentDefinitionNode() : FragmentDefinitionNode { return { kind: 'FragmentDefinition', name: { kind: 'Name', value: this.name }, typeCondition: { kind: 'NamedType', name: { kind: 'Name', value: this.typeCondition.name } }, selectionSet: this.selectionSet.toSelectionSetNode() }; } toString(indent?: string): string { return (indent ?? '') + `fragment ${this.name} on ${this.typeCondition}${this.appliedDirectivesToString()} ${this.selectionSet.toString(false, true, indent)}`; } } export class NamedFragments { private readonly fragments = new MapWithCachedArrays<string, NamedFragmentDefinition>(); isEmpty(): boolean { return this.fragments.size === 0; } variables(): Variables { let variables: Variables = []; for (const fragment of this.fragments.values()) { variables = mergeVariables(variables, fragment.variables()); } return variables; } names(): readonly string[] { return this.fragments.keys(); } add(fragment: NamedFragmentDefinition) { if (this.fragments.has(fragment.name)) { throw new GraphQLError(`Duplicate fragment name '${fragment}'`); } this.fragments.set(fragment.name, fragment); } addIfNotExist(fragment: NamedFragmentDefinition) { if (!this.fragments.has(fragment.name)) { this.fragments.set(fragment.name, fragment); } } onType(type: NamedType): NamedFragmentDefinition[] { return this.fragments.values().filter(f => f.typeCondition.name === type.name); } without(names: string[]): NamedFragments { if (!names.some(n => this.fragments.has(n))) { return this; } const newFragments = new NamedFragments(); for (const fragment of this.fragments.values()) { if (!names.includes(fragment.name)) { // We want to keep that fragment. But that fragment might use a fragment we // remove, and if so, we need to expand that removed fragment. const updatedSelection = fragment.selectionSet.expandFragments(names, false); const newFragment = updatedSelection === fragment.selectionSet ? fragment : new NamedFragmentDefinition(fragment.schema(), fragment.name, fragment.typeCondition, updatedSelection); newFragments.add(newFragment); } } return newFragments; } get(name: string): NamedFragmentDefinition | undefined { return this.fragments.get(name); } definitions(): readonly NamedFragmentDefinition[] { return this.fragments.values(); } validate() { for (const fragment of this.fragments.values()) { fragment.selectionSet.validate(); } } toFragmentDefinitionNodes() : FragmentDefinitionNode[] { return this.definitions().map(f => f.toFragmentDefinitionNode()); } toString(indent?: string) { return this.definitions().map(f => f.toString(indent)).join('\n\n'); } } export class SelectionSet { // The argument is either the responseName (for fields), or the type name (for fragments), with the empty string being used as a special // case for a fragment with no type condition. private readonly _selections = new MultiMap<string, Selection>(); private _selectionCount = 0; private _cachedSelections?: readonly Selection[]; constructor( readonly parentType: CompositeType, readonly fragments?: NamedFragments ) { validate(!isLeafType(parentType), () => `Cannot have selection on non-leaf type ${parentType}`); } selections(reversedOrder: boolean = false): readonly Selection[] { if (!this._cachedSelections) { const selections = new Array(this._selectionCount); let idx = 0; for (const byResponseName of this._selections.values()) { for (const selection of byResponseName) { selections[idx++] = selection; } } this._cachedSelections = selections; } assert(this._cachedSelections, 'Cache should have been populated'); if (reversedOrder) { const reversed = new Array(this._selectionCount); for (let i = 0; i < this._selectionCount; i++) { reversed[i] = this._cachedSelections[this._selectionCount - i - 1]; } return reversed; } return this._cachedSelections; } usedVariables(): Variables { let variables: Variables = []; for (const byResponseName of this._selections.values()) { for (const selection of byResponseName) { variables = mergeVariables(variables, selection.usedVariables()); } } if (this.fragments) { variables = mergeVariables(variables, this.fragments.variables()); } return variables; } collectUsedFragmentNames(collector: Map<string, number>) { if (!this.fragments) { return; } for (const byResponseName of this._selections.values()) { for (const selection of byResponseName) { selection.collectUsedFragmentNames(collector); } } } optimize(fragments?: NamedFragments): SelectionSet { if (!fragments || fragments.isEmpty()) { return this; } // If any of the existing fragments of the selection set is also a name in the provided one, // we bail out of optimizing anything. Not ideal, but dealing with it properly complicate things // and we probably don't care for now as we'll call `optimize` mainly on result sets that have // no named fragments in the first place. if (this.fragments && this.fragments.definitions().some(def => fragments.get(def.name))) { return this; } const optimized = new SelectionSet(this.parentType, fragments); for (const selection of this.selections()) { optimized.add(selection.optimize(fragments)); } return optimized; } expandFragments(names?: string[], updateSelectionSetFragments: boolean = true): SelectionSet { if (!this.fragments) { return this; } if (names && names.length === 0) { return this; } const newFragments = updateSelectionSetFragments ? (names ? this.fragments?.without(names) : undefined) : this.fragments; const withExpanded = new SelectionSet(this.parentType, newFragments); for (const selection of this.selections()) { withExpanded.add(selection.expandFragments(names, updateSelectionSetFragments)); } return withExpanded; } mergeIn(selectionSet: SelectionSet) { for (const selection of selectionSet.selections()) { this.add(selection); } } addAll(selections: Selection[]): SelectionSet { selections.forEach(s => this.add(s)); return this; } add(selection: Selection): Selection { const toAdd = selection.updateForAddingTo(this); const key = toAdd.key(); const existing: Selection[] | undefined = this._selections.get(key); if (existing) { for (const existingSelection of existing) { if (existingSelection.kind === toAdd.kind && haveSameDirectives(existingSelection.element(), toAdd.element())) { if (toAdd.selectionSet) { existingSelection.selectionSet!.mergeIn(toAdd.selectionSet); } return existingSelection; } } } this._selections.add(key, toAdd); ++this._selectionCount; this._cachedSelections = undefined; return selection; } addPath(path: OperationPath) { let previousSelections: SelectionSet = this; let currentSelections: SelectionSet | undefined = this; for (const element of path) { validate(currentSelections, () => `Cannot apply selection ${element} to non-selectable parent type "${previousSelections.parentType}"`); const mergedSelection: Selection = currentSelections.add(selectionOfElement(element)); previousSelections = currentSelections; currentSelections = mergedSelection.selectionSet; } } addSelectionSetNode( node: SelectionSetNode | undefined, variableDefinitions: VariableDefinitions, fieldAccessor: (type: CompositeType, fieldName: string) => FieldDefinition<any> | undefined = (type, name) => type.field(name) ) { if (!node) { return; } for (const selectionNode of node.selections) { this.addSelectionNode(selectionNode, variableDefinitions, fieldAccessor); } } addSelectionNode( node: SelectionNode, variableDefinitions: VariableDefinitions, fieldAccessor: (type: CompositeType, fieldName: string) => FieldDefinition<any> | undefined = (type, name) => type.field(name) ) { this.add(this.nodeToSelection(node, variableDefinitions, fieldAccessor)); } private nodeToSelection( node: SelectionNode, variableDefinitions: VariableDefinitions, fieldAccessor: (type: CompositeType, fieldName: string) => FieldDefinition<any> | undefined ): Selection { let selection: Selection; switch (node.kind) { case 'Field': const definition: FieldDefinition<any> | undefined = fieldAccessor(this.parentType, node.name.value); validate(definition, () => `Cannot query field "${node.name.value}" on type "${this.parentType}".`, this.parentType.sourceAST); const type = baseType(definition.type!); selection = new FieldSelection( new Field(definition, argumentsFromAST(definition.coordinate, node.arguments, definition), variableDefinitions, node.alias?.value), isLeafType(type) ? undefined : new SelectionSet(type as CompositeType, this.fragments) ); if (node.selectionSet) { validate(selection.selectionSet, () => `Unexpected selection set on leaf field "${selection.element()}"`, selection.element().definition.sourceAST); selection.selectionSet.addSelectionSetNode(node.selectionSet, variableDefinitions, fieldAccessor); } break; case 'InlineFragment': const element = new FragmentElement(this.parentType, node.typeCondition?.name.value); selection = new InlineFragmentSelection( element, new SelectionSet(element.typeCondition ? element.typeCondition : element.parentType, this.fragments) ); selection.selectionSet.addSelectionSetNode(node.selectionSet, variableDefinitions, fieldAccessor); break; case 'FragmentSpread': const fragmentName = node.name.value; validate(this.fragments, () => `Cannot find fragment name "${fragmentName}" (no fragments were provided)`); selection = new FragmentSpreadSelection(this.parentType, this.fragments, fragmentName); break; } addDirectiveNodesToElement(node.directives, selection.element()); return selection; } equals(that: SelectionSet): boolean { if (this === that) { return true; } if (this._selections.size !== that._selections.size) { return false; } for (const [key, thisSelections] of this._selections) { const thatSelections = that._selections.get(key); if (!thatSelections || thisSelections.length !== thatSelections.length || !thisSelections.every(thisSelection => thatSelections.some(thatSelection => thisSelection.equals(thatSelection))) ) { return false } } return true; } contains(that: SelectionSet): boolean { if (this._selections.size < that._selections.size) { return false; } for (const [key, thatSelections] of that._selections) { const thisSelections = this._selections.get(key); if (!thisSelections || (thisSelections.length < thatSelections.length || !thatSelections.every(thatSelection => thisSelections.some(thisSelection => thisSelection.contains(thatSelection)))) ) { return false } } return true; } validate() { validate(!this.isEmpty(), () => `Invalid empty selection set`); for (const selection of this.selections()) { selection.validate(); const selectionFragments = selection.namedFragments(); // We make this an assertion because this is a programming error. But validate is a convenient place for this in practice. assert(!selectionFragments || selectionFragments === this.fragments, () => `Selection fragments (${selectionFragments}) for ${selection} does not match selection set one (${this.fragments})`); } } isEmpty(): boolean { return this._selections.size === 0; } toSelectionSetNode(): SelectionSetNode { // In theory, for valid operations, we shouldn't have empty selection sets (field selections whose type is a leaf will // have an undefined selection set, not an empty one). We do "abuse" this a bit however when create query "witness" // during composition validation where, to make it easier for users to locate the issue, we want the created witness // query to stop where the validation problem lies, even if we're not on a leaf type. To make this look nice and // explicit, we handle that case by create a fake selection set that just contains an ellipsis, indicate there is // supposed to be more but we elided it for clarity. And yes, the whole thing is a bit of a hack, albeit a convenient // one. if (this.isEmpty()) { return { kind: Kind.SELECTION_SET, selections: [{ kind: 'Field', name: { kind: Kind.NAME, value: '...', }, }] } } return { kind: Kind.SELECTION_SET, selections: Array.from(this.selectionsInPrintOrder(), s => s.toSelectionNode()) } } private selectionsInPrintOrder(): readonly Selection[] { // By default, we will print the selection the order in which things were added to it. // If __typename is selected however, we put it first. It's a detail but as __typename is a bit special it looks better, // and it happens to mimic prior behavior on the query plan side so it saves us from changing tests for no good reasons. const typenameSelection = this._selections.get(typenameFieldName); if (typenameSelection) { return typenameSelection.concat(this.selections().filter(s => s.kind != 'FieldSelection' || s.field.name !== typenameFieldName)); } else { return this.selections(); } } toOperationPaths(): OperationPath[] { return this.toOperationPathsInternal([]); } private toOperationPathsInternal(parentPaths: OperationPath[]): OperationPath[] { return this.selections().flatMap((selection) => { const updatedPaths = parentPaths.map(path => path.concat(selection.element())); return selection.selectionSet ? selection.selectionSet.toOperationPathsInternal(updatedPaths) : updatedPaths; }); } clone(): SelectionSet { const cloned = new SelectionSet(this.parentType); for (const selection of this.selections()) { cloned.add(selection.clone()); } return cloned; } toOperationString( rootKind: SchemaRootKind, variableDefinitions: VariableDefinitions, operationName?: string, expandFragments: boolean = false, prettyPrint: boolean = true ): string { const indent = prettyPrint ? '' : undefined; const fragmentsDefinitions = !expandFragments && this.fragments && !this.fragments.isEmpty() ? this.fragments.toString(indent) + "\n\n" : ""; if (rootKind == "query" && !operationName && variableDefinitions.isEmpty()) { return fragmentsDefinitions + this.toString(expandFragments, true, indent); } const nameAndVariables = operationName ? " " + (operationName + (variableDefinitions.isEmpty() ? "" : variableDefinitions.toString())) : (variableDefinitions.isEmpty() ? "" : " " + variableDefinitions.toString()); return fragmentsDefinitions + rootKind + nameAndVariables + " " + this.toString(expandFragments, true, indent); } /** * The string representation of this selection set. * * By default, this expand all fragments so that the returned string is self-contained. You can * use the `expandFragments` boolean to force fragments to not be expanded but the fragments * definitions will _not_ be included in the returned string. If you want a representation of * this selection set with fragments definitions included, use `toOperationString` instead. */ toString( expandFragments: boolean = true, includeExternalBrackets: boolean = true, indent?: string ): string { if (indent === undefined) { const selectionsToString = this.selections().map(s => s.toString(expandFragments)).join(' '); return includeExternalBrackets ? '{ ' + selectionsToString + ' }' : selectionsToString; } else { const selectionIndent = includeExternalBrackets ? indent + " " : indent; const selectionsToString = this.selections().map(s => s.toString(expandFragments, selectionIndent)).join('\n'); return includeExternalBrackets ? '{\n' + selectionsToString + '\n' + indent + '}' : selectionsToString; } } } export function selectionSetOfElement(element: OperationElement, subSelection?: SelectionSet): SelectionSet { const selectionSet = new SelectionSet(element.parentType); selectionSet.add(selectionOfElement(element, subSelection)); return selectionSet; } export function selectionOfElement(element: OperationElement, subSelection?: SelectionSet): Selection { return element.kind === 'Field' ? new FieldSelection(element, subSelection) : new InlineFragmentSelection(element, subSelection); } export function selectionSetOfPath(path: OperationPath, onPathEnd?: (finalSelectionSet: SelectionSet | undefined) => void): SelectionSet { validate(path.length > 0, () => `Cannot create a selection set from an empty path`); const last = selectionSetOfElement(path[path.length - 1]); let current = last; for (let i = path.length - 2; i >= 0; i--) { current = selectionSetOfElement(path[i], current); } if (onPathEnd) { onPathEnd(last.selections()[0].selectionSet); } return current; } export type Selection = FieldSelection | FragmentSelection; export class FieldSelection { readonly kind = 'FieldSelection' as const; readonly selectionSet?: SelectionSet; constructor( readonly field: Field<any>, initialSelectionSet? : SelectionSet ) { const type = baseType(field.definition.type!); // Field types are output type, and a named typethat is an output one and isn't a leaf is guaranteed to be selectable. this.selectionSet = isLeafType(type) ? undefined : (initialSelectionSet ? initialSelectionSet : new SelectionSet(type as CompositeType)); } key(): string { return this.element().responseName(); } element(): Field<any> { return this.field; } usedVariables(): Variables { return mergeVariables(this.element().variables(), this.selectionSet?.usedVariables() ?? []); } collectUsedFragmentNames(collector: Map<string, number>) { if (this.selectionSet) { this.selectionSet.collectUsedFragmentNames(collector); } } optimize(fragments: NamedFragments): FieldSelection { const optimizedSelection = this.selectionSet ? this.selectionSet.optimize(fragments) : undefined; return this.selectionSet === optimizedSelection ? this : new FieldSelection(this.field, optimizedSelection); } expandFragments(names?: string[], updateSelectionSetFragments: boolean = true): FieldSelection { const expandedSelection = this.selectionSet ? this.selectionSet.expandFragments(names, updateSelectionSetFragments) : undefined; return this.selectionSet === expandedSelection ? this : new FieldSelection(this.field, expandedSelection); } private fieldArgumentsToAST(): ArgumentNode[] | undefined { const entries = Object.entries(this.field.args); if (entries.length === 0) { return undefined; } return entries.map(([n, v]) => { return { kind: 'Argument', name: { kind: Kind.NAME, value: n }, value: valueToAST(v, this.field.definition.argument(n)!.type!)!, }; }); } validate() { // Note that validation is kind of redundant since `this.selectionSet.validate()` will check that it isn't empty. But doing it // allow to provide much better error messages. validate( !(this.selectionSet && this.selectionSet.isEmpty()), () => `Invalid empty selection set for field "${this.field.definition.coordinate}" of non-leaf type ${this.field.definition.type}`, this.field.definition.sourceAST ); this.selectionSet?.validate(); } updateForAddingTo(selectionSet: SelectionSet): FieldSelection { const updatedField = this.field.updateForAddingTo(selectionSet); return this.field === updatedField ? this : new FieldSelection(updatedField, this.selectionSet); } toSelectionNode(): FieldNode { const alias = this.field.alias ? { kind: Kind.NAME, value: this.field.alias, } : undefined; return { kind: 'Field', name: { kind: Kind.NAME, value: this.field.name, }, alias, arguments: this.fieldArgumentsToAST(), directives: this.element().appliedDirectivesToDirectiveNodes(), selectionSet: this.selectionSet?.toSelectionSetNode() }; } equals(that: Selection): boolean { if (this === that) { return true; } if (!(that instanceof FieldSelection) || !this.field.equals(that.field)) { return false; } if (!this.selectionSet) { return !that.selectionSet; } return !!that.selectionSet && this.selectionSet.equals(that.selectionSet); } contains(that: Selection): boolean { if (!(that instanceof FieldSelection) || !this.field.equals(that.field)) { return false; } if (!that.selectionSet) { return true; } return !!this.selectionSet && this.selectionSet.contains(that.selectionSet); } namedFragments(): NamedFragments | undefined { return this.selectionSet?.fragments; } clone(): FieldSelection { if (!this.selectionSet) { return this; } return new FieldSelection(this.field, this.selectionSet.clone()); } toString(expandFragments: boolean = true, indent?: string): string { return (indent ?? '') + this.field + (this.selectionSet ? ' ' + this.selectionSet.toString(expandFragments, true, indent) : ''); } } export abstract class FragmentSelection { readonly kind = 'FragmentSelection' as const; abstract key(): string; abstract element(): FragmentElement; abstract get selectionSet(): SelectionSet; abstract collectUsedFragmentNames(collector: Map<string, number>): void; abstract namedFragments(): NamedFragments | undefined; abstract optimize(fragments: NamedFragments): FragmentSelection; abstract expandFragments(names?: string[]): FragmentSelection; abstract toSelectionNode(): SelectionNode; abstract validate(): void; usedVariables(): Variables { return mergeVariables(this.element().variables(), this.selectionSet.usedVariables()); } updateForAddingTo(selectionSet: SelectionSet): FragmentSelection { const updatedFragment = this.element().updateForAddingTo(selectionSet); return this.element() === updatedFragment ? this : new InlineFragmentSelection(updatedFragment, this.selectionSet); } equals(that: Selection): boolean { if (this === that) { return true; } return (that instanceof FragmentSelection) && this.element().equals(that.element()) && this.selectionSet.equals(that.selectionSet); } contains(that: Selection): boolean { return (that instanceof FragmentSelection) && this.element().equals(that.element()) && this.selectionSet.contains(that.selectionSet); } clone(): FragmentSelection { return new InlineFragmentSelection(this.element(), this.selectionSet.clone()); } } class InlineFragmentSelection extends FragmentSelection { private readonly _selectionSet: SelectionSet; constructor( private readonly fragmentElement: FragmentElement, initialSelectionSet?: SelectionSet ) { super(); // TODO: we should do validate the type of the initial selection set. this._selectionSet = initialSelectionSet ? initialSelectionSet : new SelectionSet(fragmentElement.typeCondition ? fragmentElement.typeCondition : fragmentElement.parentType); } key(): string { return this.element().typeCondition?.name ?? ''; } validate() { // Note that validation is kind of redundant since `this.selectionSet.validate()` will check that it isn't empty. But doing it // allow to provide much better error messages. validate( !this.selectionSet.isEmpty(), () => `Invalid empty selection set for fragment "${this.element()}"` ); this.selectionSet.validate(); } get selectionSet(): SelectionSet { return this._selectionSet; } namedFragments(): NamedFragments | undefined { return this.selectionSet.fragments; } element(): FragmentElement { return this.fragmentElement; } toSelectionNode(): InlineFragmentNode { const typeCondition = this.element().typeCondition; return { kind: Kind.INLINE_FRAGMENT, typeCondition: typeCondition ? { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: typeCondition.name, }, } : undefined, directives: this.element().appliedDirectivesToDirectiveNodes(), selectionSet: this.selectionSet.toSelectionSetNode() }; } optimize(fragments: NamedFragments): FragmentSelection { const optimizedSelection = this.selectionSet.optimize(fragments); const typeCondition = this.element().typeCondition; if (typeCondition) { for (const candidate of fragments.onType(typeCondition)) { if (candidate.selectionSet.equals(optimizedSelection)) { fragments.addIfNotExist(candidate); return new FragmentSpreadSelection(this.element().parentType, fragments, candidate.name); } } } return this.selectionSet === optimizedSelection ? this : new InlineFragmentSelection(this.fragmentElement, optimizedSelection); } expandFragments(names?: string[], updateSelectionSetFragments: boolean = true): FragmentSelection { const expandedSelection = this.selectionSet.expandFragments(names, updateSelectionSetFragments); return this.selectionSet === expandedSelection ? this : new InlineFragmentSelection(this.element(), expandedSelection); } collectUsedFragmentNames(collector: Map<string, number>): void { this.selectionSet.collectUsedFragmentNames(collector); } toString(expandFragments: boolean = true, indent?: string): string { return (indent ?? '') + this.fragmentElement + ' ' + this.selectionSet.toString(expandFragments, true, indent); } } class FragmentSpreadSelection extends FragmentSelection { private readonly namedFragment: NamedFragmentDefinition; // Note that the named fragment directives are copied on this element and appear first (the spreadDirectives // method rely on this to be able to extract the directives that are specific to the spread itself). private readonly _element : FragmentElement; constructor( sourceType: CompositeType, private readonly fragments: NamedFragments, fragmentName: string ) { super(); const fragmentDefinition = fragments.get(fragmentName); validate(fragmentDefinition, () => `Unknown fragment "...${fragmentName}"`); this.namedFragment = fragmentDefinition; this._element = new FragmentElement(sourceType, fragmentDefinition.typeCondition); for (const directive of fragmentDefinition.appliedDirectives) { this._element.applyDirective(directive.definition!, directive.arguments()); } } key(): string { return '...' + this.namedFragment.name; } element(): FragmentElement { return this._element; } namedFragments(): NamedFragments | undefined { return this.fragments; } get selectionSet(): SelectionSet { return this.namedFragment.selectionSet; } validate(): void { // We don't do anything because fragment definition are validated when created. } toSelectionNode(): FragmentSpreadNode { const spreadDirectives = this.spreadDirectives(); const directiveNodes = spreadDirectives.length === 0 ? undefined : spreadDirectives.map(directive => { return { kind: 'Directive', name: { kind: Kind.NAME, value: directive.name, }, arguments: directive.argumentsToAST() } as DirectiveNode; }); return { kind: 'FragmentSpread', name: { kind: 'Name', value: this.namedFragment.name }, directives: directiveNodes, }; } optimize(_: NamedFragments): FragmentSelection { return this; } expandFragments(names?: string[], updateSelectionSetFragments: boolean = true): FragmentSelection { if (names && !names.includes(this.namedFragment.name)) { return this; } return new InlineFragmentSelection(this._element, this.selectionSet.expandFragments(names, updateSelectionSetFragments)); } collectUsedFragmentNames(collector: Map<string, number>): void { this.selectionSet.collectUsedFragmentNames(collector); const usageCount = collector.get(this.namedFragment.name); collector.set(this.namedFragment.name, usageCount === undefined ? 1 : usageCount + 1); } private spreadDirectives(): Directive<FragmentElement>[] { return this._element.appliedDirectives.slice(this.namedFragment.appliedDirectives.length); } toString(expandFragments: boolean = true, indent?: string): string { if (expandFragments) { return (indent ?? '') + this._element + ' ' + this.selectionSet.toString(true, true, indent); } else { const directives = this.spreadDirectives(); const directiveString = directives.length == 0 ? '' : ' ' + directives.join(' '); return (indent ?? '') + '...' + this.namedFragment.name + directiveString; } } } export function operationFromDocument( schema: Schema, document: DocumentNode, operationName?: string, ) : Operation { let operation: OperationDefinitionNode | undefined; const fragments = new NamedFragments(); // We do a first pass to collect the operation, and create all named fragment, but without their selection set yet. // This allow later to be able to access any fragment regardless of the order in which the fragments are defined. document.definitions.forEach(definition => { switch (definition.kind) { case Kind.OPERATION_DEFINITION: validate(!operation || operationName, () => 'Must provide operation name if query contains multiple operations.'); if (!operationName || (definition.name && definition.name.value === operationName)) { operation = definition; } break; case Kind.FRAGMENT_DEFINITION: const name = definition.name.value; const typeName = definition.typeCondition.name.value; const typeCondition = schema.type(typeName); if (!typeCondition) { throw new GraphQLError(`Unknown type "${typeName}" for fragment "${name}"`, definition); } if (!isCompositeType(typeCondition)) { throw new GraphQLError(`Invalid fragment "${name}" on non-composite type "${typeName}"`, definition); } const fragment = new NamedFragmentDefinition(schema, name, typeCondition, new SelectionSet(typeCondition, fragments)); addDirectiveNodesToElement(definition.directives, fragment); fragments.add(fragment); break; } }); validate(operation, () => operationName ? `Unknown operation named "${operationName}"` : 'No operation found in provided document.'); // Note that we need the variables to handle the fragments, as they can be used there. const variableDefinitions = operation.variableDefinitions ? variableDefinitionsFromAST(schema, operation.variableDefinitions) : new VariableDefinitions(); // We can now parse all fragments. document.definitions.forEach(definition => { switch (definition.kind) { case Kind.FRAGMENT_DEFINITION: const fragment = fragments.get(definition.name.value)!; fragment.selectionSet.addSelectionSetNode(definition.selectionSet, variableDefinitions); break; } }); fragments.validate(); return operationFromAST(schema, operation, fragments); } function operationFromAST( schema: Schema, operation: OperationDefinitionNode, fragments: NamedFragments ) : Operation { const rootType = schema.schemaDefinition.root(operation.operation); validate(rootType, () => `The schema has no "${operation.operation}" root type defined`); const variableDefinitions = operation.variableDefinitions ? variableDefinitionsFromAST(schema, operation.variableDefinitions) : new VariableDefinitions(); return new Operation( operation.operation, parseSelectionSet(rootType.type, operation.selectionSet, variableDefinitions, fragments), variableDefinitions, operation.name?.value ); } export function parseOperation(schema: Schema, operation: string, operationName?: string): Operation { return operationFromDocument(schema, parse(operation), operationName); } export function parseSelectionSet( parentType: CompositeType, source: string | SelectionSetNode, variableDefinitions: VariableDefinitions = new VariableDefinitions(), fragments?: NamedFragments, fieldAccessor: (type: CompositeType, fieldName: string) => FieldDefinition<any> | undefined = (type, name) => type.field(name) ): SelectionSet { // TODO: we should maybe allow the selection, when a string, to contain fragment definitions? const node = typeof source === 'string' ? parseOperationAST(source.trim().startsWith('{') ? source : `{${source}}`).selectionSet : source; const selectionSet = new SelectionSet(parentType, fragments); selectionSet.addSelectionSetNode(node, variableDefinitions, fieldAccessor); selectionSet.validate(); return selectionSet; } function parseOperationAST(source: string): OperationDefinitionNode { const parsed = parse(source); validate(parsed.definitions.length === 1, () => 'Selections should contain a single definitions, found ' + parsed.definitions.length); const def = parsed.definitions[0]; validate(def.kind === 'OperationDefinition', () => 'Expected an operation definition but got a ' + def.kind); return def; } export function operationToDocument(operation: Operation): DocumentNode { const operationAST: OperationDefinitionNode = { kind: 'OperationDefinition', operation: operation.rootKind, selectionSet: operation.selectionSet.toSelectionSetNode(), variableDefinitions: operation.variableDefinitions.toVariableDefinitionNodes(), }; const fragmentASTs: DefinitionNode[] = operation.selectionSet.fragments ? operation.selectionSet.fragments?.toFragmentDefinitionNodes() : []; return { kind: Kind.DOCUMENT, definitions: [operationAST as DefinitionNode].concat(fragmentASTs), }; }
the_stack
import React from 'react'; import { Components, registerComponent } from '../../lib/vulcan-lib'; import { Link } from '../../lib/reactRouterWrapper'; import { useCurrentUser } from '../common/withUser' import {AnalyticsContext} from "../../lib/analyticsEvents"; import type { RecommendationsAlgorithm } from '../../lib/collections/users/recommendationSettings'; import classNames from 'classnames'; import { forumTitleSetting, forumTypeSetting, siteNameWithArticleSetting } from '../../lib/instanceSettings'; import { annualReviewAnnouncementPostPathSetting, annualReviewEnd, annualReviewNominationPhaseEnd, annualReviewReviewPhaseEnd, annualReviewStart } from '../../lib/publicSettings'; import moment from 'moment'; import { eligibleToNominate, getReviewPhase, ReviewYear, REVIEW_NAME_IN_SITU, REVIEW_NAME_TITLE, REVIEW_YEAR } from '../../lib/reviewUtils'; import { userIsAdmin } from '../../lib/vulcan-users'; const isEAForum = forumTypeSetting.get() === "EAForum" const styles = (theme: ThemeType): JssStyles => ({ learnMore: { color: theme.palette.lwTertiary.main }, subtitle: { width: "100%", display: 'flex', justifyContent: 'space-between' }, reviewTimeline: { ...theme.typography.commentStyle, display: 'flex', marginBottom: 6, marginTop: -8 }, nominationBlock: {flexGrow: 1, marginRight: 2, flexBasis: 0}, reviewBlock: {flexGrow: 2, marginRight: 2, flexBasis: 0}, votingBlock: {flexGrow: 1, flexBasis: 0}, blockText: { color: theme.palette.text.invertedBackgroundText, zIndex: 1, whiteSpace: "nowrap", }, blockLabel: { marginRight: 10, }, progress: { position: 'relative', marginBottom: 2, padding: 4, backgroundColor: theme.palette.greyAlpha(.14), display: 'flex', justifyContent: 'space-between', '&:hover': { boxShadow: `0px 0px 10px ${theme.palette.boxShadowColor(0.1)}`, opacity: 0.9 } }, activeProgress: { backgroundColor: isEAForum ? theme.palette.primary.main : theme.palette.review.activeProgress, }, coloredProgress: { position: 'absolute', top: 0, left: 0, height: '100%', backgroundColor: isEAForum ? theme.palette.lwTertiary.main : theme.palette.review.progressBar, }, nominationDate: {}, actionButtonRow: { textAlign: "right", display: "flex", justifyContent: "flex-end", marginTop: 8 }, actionButtonCTA: { backgroundColor: theme.palette.primary.main, paddingTop: 6, paddingBottom: 6, paddingLeft: 12, paddingRight: 12, borderRadius: 3, color: theme.palette.text.invertedBackgroundText, ...theme.typography.commentStyle, display: "inline-block", marginLeft: 12 }, actionButton: { border: `solid 1px ${theme.palette.grey[400]}`, paddingTop: 6, paddingBottom: 6, paddingLeft: 12, paddingRight: 12, borderRadius: 3, color: theme.palette.grey[600], ...theme.typography.commentStyle, display: "inline-block", marginLeft: 12 }, adminButton: { border: `solid 1px ${theme.palette.review.adminButton}`, color: theme.palette.review.adminButton, }, buttonWrapper: { flexGrow: 0, flexShrink: 0 }, hideOnMobile: { [theme.breakpoints.down('sm')]: { display: 'none' } }, showOnMobile: { [theme.breakpoints.up('md')]: { display: 'none' } }, timeRemaining: { ...theme.typography.commentStyle, fontSize: 14, color: theme.palette.grey[500] } }) /** * Get the algorithm for review recommendations * * Needs to be a function so it gets rerun after a potential database setting * update that changes the review phase */ export function getReviewAlgorithm(): RecommendationsAlgorithm { const reviewPhase = getReviewPhase() || "NOMINATIONS" // Not sure why the type assertion at the end is necessary const reviewPhaseInfo = { NOMINATIONS: {reviewNominations: REVIEW_YEAR}, REVIEWS: {reviewReviews: REVIEW_YEAR}, VOTING: {reviewReviews: REVIEW_YEAR}, }[reviewPhase] as {reviewNominations: ReviewYear} | {reviewReviews: ReviewYear} return { method: "sample", count: 3, scoreOffset: 0, scoreExponent: 0, personalBlogpostModifier: 0, frontpageModifier: 0, curatedModifier: 0, includePersonal: true, includeMeta: true, ...reviewPhaseInfo, onlyUnread: false, excludeDefaultRecommendations: true } } const nominationStartDate = moment.utc(annualReviewStart.get()) const nominationEndDate = moment.utc(annualReviewNominationPhaseEnd.get()) const reviewEndDate = moment.utc(annualReviewReviewPhaseEnd.get()) const voteEndDate = moment.utc(annualReviewEnd.get()) const forumTitle = forumTitleSetting.get() const nominationPhaseDateRange = <span>{nominationStartDate.format('MMM Do')} – {nominationEndDate.format('MMM Do')}</span> const reviewPhaseDateRange = <span>{nominationEndDate.clone().format('MMM Do')} – {reviewEndDate.format('MMM Do')}</span> const votingPhaseDateRange = <span>{reviewEndDate.clone().format('MMM Do')} – {voteEndDate.format('MMM Do')}</span> // EA will use LW text next year, so I've kept the forumType genericization export const overviewTooltip = isEAForum ? <div> <div>The EA Forum is reflecting on the best EA writing, in three phases</div> <ul> <li><em>Nomination</em> ({nominationPhaseDateRange})</li> <li><em>Review</em> ({reviewPhaseDateRange})</li> <li><em>Voting</em> ({votingPhaseDateRange})</li> </ul> <div>To be eligible, posts must have been posted before January 1st, 2021.</div> <br/> {/* TODO:(Review) this won't be true in other phases */} <div>(Currently this section shows a random sample of eligible posts, weighted by karma)</div> </div> : <div> <div>The {forumTitle} community is reflecting on the best posts from {REVIEW_YEAR}, in three phases:</div> <ul> <li><em>Preliminary Voting</em> ({nominationPhaseDateRange})</li> <li><em>Review</em> ({reviewPhaseDateRange})</li> <li><em>Final Voting</em> ({votingPhaseDateRange})</li> </ul> {!isEAForum && <div>The {forumTitle} moderation team will incorporate that information, along with their judgment, into a "Best of {REVIEW_YEAR}" sequence.</div>} <p>We're currently in the preliminary voting phase. Nominate posts by casting a preliminary vote, or vote on existing nominations to help us prioritize them during the Review Phase.</p> </div> const FrontpageReviewWidget = ({classes, showFrontpageItems=true}: {classes: ClassesType, showFrontpageItems?: boolean}) => { const { SectionTitle, SettingsButton, RecommendationsList, LWTooltip, LatestReview, PostsList2 } = Components const currentUser = useCurrentUser(); // These should be calculated at render const currentDate = moment.utc() const activeRange = getReviewPhase() const nominationsTooltip = isEAForum ? <div> <div>Nominate posts for the {REVIEW_NAME_IN_SITU}</div> <ul> <li>Any post from before 2021 can be nominated</li> <li>Any user registered before the start of the review can nominate posts</li> <li>Posts with at least one positive vote proceed to the Review Phase.</li> </ul> <div>If you've been actively reading {siteNameWithArticleSetting.get()} before now, but didn't register an account, reach out to us on intercom.</div> </div> : <div> <div>Cast initial votes for the {REVIEW_YEAR} Review.</div> <ul> <li>Nominate a post by casting a <em>preliminary vote</em>, or vote on an existing nomination to help us prioritize it during the Review Phase.</li> <li>Any post from {REVIEW_YEAR} can be nominated</li> <li>Any user registered before {REVIEW_YEAR} can nominate posts for review</li> <li>Posts will need at least one vote to proceed to the Review Phase.</li> </ul> </div> const reviewTooltip = isEAForum ? <> <div>Review posts for the {REVIEW_NAME_IN_SITU} (Opens {nominationEndDate.clone().format('MMM Do')})</div> <ul> <li>Write reviews of posts nominated for the {REVIEW_NAME_IN_SITU}</li> <li>Only posts with at least one review are eligible for the final vote</li> </ul> </> : <> <div>Review posts for the {REVIEW_YEAR} Review (Opens {nominationEndDate.clone().format('MMM Do')})</div> <ul> <li>Write reviews of posts nominated for the {REVIEW_YEAR} Review</li> <li>Only posts with at least one review are eligible for the final vote</li> </ul> </> const voteTooltip = isEAForum ? <> <div>Cast your final votes for the {REVIEW_NAME_IN_SITU}. (Opens {reviewEndDate.clone().format('MMM Do')})</div> <ul> <li>Look over nominated posts and vote on them</li> <li>Any user registered before {nominationStartDate.format('MMM Do')} can vote in the review</li> </ul> </> : <> <div>Cast your final votes for the {REVIEW_YEAR} Review. (Opens {reviewEndDate.clone().format('MMM Do')})</div> <ul> <li>Look over {/* TODO: Raymond Arnold look here, sentence fragment */} </li> <li>Any user registered before {REVIEW_YEAR} can vote in the review</li> <li>The end result will be compiled into a canonical sequence and best-of {REVIEW_YEAR} book</li> </ul> {/* TODO: Raymond Arnold look here, This isn't that useful to say any more */} <div> Before the vote starts, you can try out the vote process on posts nominated and reviewed in {REVIEW_YEAR-1}</div> </> const dateFraction = (fractionDate: moment.Moment, startDate: moment.Moment, endDate: moment.Moment) => { if (fractionDate < startDate) return 0 return ((fractionDate.unix() - startDate.unix())/(endDate.unix() - startDate.unix())*100).toFixed(2) } const allEligiblePostsUrl = isEAForum ? `/allPosts?timeframe=yearly&before=${REVIEW_YEAR+1}-01-01&limit=25&sortedBy=top&filter=unnominated&includeShortform=false` : `/allPosts?timeframe=yearly&after=2020-01-01&before=2021-01-01&limit=100&sortedBy=top&filter=unnominated&includeShortform=false` const reviewPostPath = annualReviewAnnouncementPostPathSetting.get() if (!reviewPostPath) { // eslint-disable-next-line no-console console.error("No review announcement post path set") } const allPhaseButtons = <> {!showFrontpageItems && userIsAdmin(currentUser) && <LWTooltip className={classes.buttonWrapper} title={`Look at metrics related to the Review`}> <Link to={'/reviewAdmin'} className={classNames(classes.actionButton, classes.adminButton)}> Review Admin </Link> </LWTooltip>} </> return ( <AnalyticsContext pageSectionContext="frontpageReviewWidget"> <div> <SectionTitle title={<LWTooltip title={overviewTooltip} placement="bottom-start"> <Link to={"/reviewVoting"}> {REVIEW_NAME_TITLE} </Link> </LWTooltip>} > <LWTooltip title={overviewTooltip} className={classes.hideOnMobile}> <Link to={reviewPostPath || ""}> <SettingsButton showIcon={false} label={`How does the ${REVIEW_NAME_IN_SITU} work?`}/> </Link> </LWTooltip> </SectionTitle> <div className={classes.reviewTimeline}> <div className={classes.nominationBlock}> <LWTooltip placement="bottom-start" title={nominationsTooltip} className={classNames(classes.progress, {[classes.activeProgress]: activeRange === "NOMINATIONS"})}> <div className={classNames(classes.blockText, classes.blockLabel)}>Preliminary Voting</div> <div className={classNames(classes.blockText, classes.hideOnMobile)}>{nominationEndDate.format('MMM Do')}</div> {activeRange === "NOMINATIONS" && <div className={classes.coloredProgress} style={{width: `${dateFraction(currentDate, nominationStartDate, nominationEndDate)}%`}} />} </LWTooltip> </div> <div className={classes.reviewBlock}> <LWTooltip placement="bottom-start" title={reviewTooltip} className={classNames(classes.progress, {[classes.activeProgress]: activeRange === "REVIEWS"})}> <div className={classNames(classes.blockText, classes.blockLabel)}>Reviews</div> <div className={classNames(classes.blockText, classes.hideOnMobile)}>{reviewEndDate.format('MMM Do')}</div> {activeRange === "REVIEWS" && <div className={classes.coloredProgress} style={{width: `${dateFraction(currentDate, nominationEndDate, reviewEndDate)}%`}}/>} </LWTooltip> </div> <div className={classes.votingBlock}> <LWTooltip placement="bottom-start" title={voteTooltip} className={classNames(classes.progress, {[classes.activeProgress]: activeRange === "VOTING"})}> <div className={classNames(classes.blockText, classes.blockLabel)}>Final Voting</div> <div className={classNames(classes.blockText, classes.hideOnMobile)}>{voteEndDate.format('MMM Do')}</div> {activeRange === "VOTING" && <div className={classes.coloredProgress} style={{width: `${dateFraction(currentDate, reviewEndDate, voteEndDate)}%`}}/>} </LWTooltip> </div> </div> {/* TODO: Improve logged out user experience */} {activeRange === "NOMINATIONS" && eligibleToNominate(currentUser) && <div className={classes.actionButtonRow}> {showFrontpageItems && <LatestReview/>} {allPhaseButtons} <LWTooltip className={classes.buttonWrapper} title={`Nominate posts you previously upvoted.`}> <Link to={`/votesByYear/${isEAForum ? '%e2%89%a42020' : REVIEW_YEAR}`} className={classes.actionButton}> <span> <span className={classes.hideOnMobile}>Your</span> {isEAForum && '≤'}{REVIEW_YEAR} Upvotes </span> </Link> </LWTooltip> <LWTooltip className={classes.buttonWrapper} title={`Nominate posts ${isEAForum ? 'in or before' : 'from'} ${REVIEW_YEAR}`}> <Link to={allEligiblePostsUrl} className={classes.actionButton}> All <span className={classes.hideOnMobile}>{isEAForum ? 'Eligible' : REVIEW_YEAR}</span> Posts </Link> </LWTooltip> {showFrontpageItems && <LWTooltip className={classes.buttonWrapper} title={<div> <p>Reviews Dashboard</p> <ul> <li>View all posts with at least one preliminary vote.</li> <li>Cast additional votes, to help prioritize posts during the Review Phase.</li> <li>Start writing reviews.</li> </ul> </div>}> <Link to={"/reviewVoting/2020"} className={classes.actionButtonCTA}> Vote on <span className={classes.hideOnMobile}>nominated</span> posts </Link> </LWTooltip>} </div>} {/* Post list */} {showFrontpageItems && activeRange !== "NOMINATIONS" && <AnalyticsContext listContext={`frontpageReviewReviews`} reviewYear={`${REVIEW_YEAR}`}> <PostsList2 terms={{ view:"reviewVoting", before: `${REVIEW_YEAR+1}-01-01`, ...(isEAForum ? {} : {after: `${REVIEW_YEAR}-01-01`}), limit: 3, itemsPerPage: 10 }} > <div> {/* TODO: make the time-remaining show up correctly throughout the review */} {/* If there's less than 24 hours remaining, show the remaining time */} {voteEndDate.diff(new Date()) < (24 * 60 * 60 * 1000) && <span className={classes.timeRemaining}> {voteEndDate.fromNow()} remaining </span>} {eligibleToNominate(currentUser) && <Link to={"/reviews"} className={classes.actionButtonCTA}> {activeRange === "REVIEWS" && <span>Review {REVIEW_YEAR} Posts</span>} {activeRange === "VOTING" && <span>Cast Final Votes</span>} </Link> } </div> </PostsList2> </AnalyticsContext>} {!showFrontpageItems && activeRange !== "NOMINATIONS" && <AnalyticsContext listContext={`frontpageReviewReviews`} reviewYear={`${REVIEW_YEAR}`}> {eligibleToNominate(currentUser) && <div className={classes.actionButtonRow}> {allPhaseButtons} </div>} </AnalyticsContext>} </div> </AnalyticsContext> ) } const FrontpageReviewWidgetComponent = registerComponent('FrontpageReviewWidget', FrontpageReviewWidget, {styles}); declare global { interface ComponentTypes { FrontpageReviewWidget: typeof FrontpageReviewWidgetComponent } }
the_stack
import { JsPsych, JsPsychPlugin, ParameterType, TrialType } from "jspsych"; const info = <const>{ name: "image-button-response", parameters: { /** The image to be displayed */ stimulus: { type: ParameterType.IMAGE, pretty_name: "Stimulus", default: undefined, }, /** Set the image height in pixels */ stimulus_height: { type: ParameterType.INT, pretty_name: "Image height", default: null, }, /** Set the image width in pixels */ stimulus_width: { type: ParameterType.INT, pretty_name: "Image width", default: null, }, /** Maintain the aspect ratio after setting width or height */ maintain_aspect_ratio: { type: ParameterType.BOOL, pretty_name: "Maintain aspect ratio", default: true, }, /** Array containing the label(s) for the button(s). */ choices: { type: ParameterType.STRING, pretty_name: "Choices", default: undefined, array: true, }, /** The HTML for creating button. Can create own style. Use the "%choice%" string to indicate where the label from the choices parameter should be inserted. */ button_html: { type: ParameterType.HTML_STRING, pretty_name: "Button HTML", default: '<button class="jspsych-btn">%choice%</button>', array: true, }, /** Any content here will be displayed under the button. */ prompt: { type: ParameterType.HTML_STRING, pretty_name: "Prompt", default: null, }, /** How long to show the stimulus. */ stimulus_duration: { type: ParameterType.INT, pretty_name: "Stimulus duration", default: null, }, /** How long to show the trial. */ trial_duration: { type: ParameterType.INT, pretty_name: "Trial duration", default: null, }, /** The vertical margin of the button. */ margin_vertical: { type: ParameterType.STRING, pretty_name: "Margin vertical", default: "0px", }, /** The horizontal margin of the button. */ margin_horizontal: { type: ParameterType.STRING, pretty_name: "Margin horizontal", default: "8px", }, /** If true, then trial will end when user responds. */ response_ends_trial: { type: ParameterType.BOOL, pretty_name: "Response ends trial", default: true, }, /** * If true, the image will be drawn onto a canvas element (prevents blank screen between consecutive images in some browsers). * If false, the image will be shown via an img element. */ render_on_canvas: { type: ParameterType.BOOL, pretty_name: "Render on canvas", default: true, }, }, }; type Info = typeof info; /** * **image-button-response** * * jsPsych plugin for displaying an image stimulus and getting a button response * * @author Josh de Leeuw * @see {@link https://www.jspsych.org/plugins/jspsych-image-button-response/ image-button-response plugin documentation on jspsych.org} */ class ImageButtonResponsePlugin implements JsPsychPlugin<Info> { static info = info; constructor(private jsPsych: JsPsych) {} trial(display_element: HTMLElement, trial: TrialType<Info>) { var height, width; var html; if (trial.render_on_canvas) { var image_drawn = false; // first clear the display element (because the render_on_canvas method appends to display_element instead of overwriting it with .innerHTML) if (display_element.hasChildNodes()) { // can't loop through child list because the list will be modified by .removeChild() while (display_element.firstChild) { display_element.removeChild(display_element.firstChild); } } // create canvas element and image var canvas = document.createElement("canvas"); canvas.id = "jspsych-image-button-response-stimulus"; canvas.style.margin = "0"; canvas.style.padding = "0"; var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = () => { // if image wasn't preloaded, then it will need to be drawn whenever it finishes loading if (!image_drawn) { getHeightWidth(); // only possible to get width/height after image loads ctx.drawImage(img, 0, 0, width, height); } }; img.src = trial.stimulus; // get/set image height and width - this can only be done after image loads because uses image's naturalWidth/naturalHeight properties const getHeightWidth = () => { if (trial.stimulus_height !== null) { height = trial.stimulus_height; if (trial.stimulus_width == null && trial.maintain_aspect_ratio) { width = img.naturalWidth * (trial.stimulus_height / img.naturalHeight); } } else { height = img.naturalHeight; } if (trial.stimulus_width !== null) { width = trial.stimulus_width; if (trial.stimulus_height == null && trial.maintain_aspect_ratio) { height = img.naturalHeight * (trial.stimulus_width / img.naturalWidth); } } else if (!(trial.stimulus_height !== null && trial.maintain_aspect_ratio)) { // if stimulus width is null, only use the image's natural width if the width value wasn't set // in the if statement above, based on a specified height and maintain_aspect_ratio = true width = img.naturalWidth; } canvas.height = height; canvas.width = width; }; getHeightWidth(); // call now, in case image loads immediately (is cached) // create buttons var buttons = []; if (Array.isArray(trial.button_html)) { if (trial.button_html.length == trial.choices.length) { buttons = trial.button_html; } else { console.error( "Error in image-button-response plugin. The length of the button_html array does not equal the length of the choices array" ); } } else { for (var i = 0; i < trial.choices.length; i++) { buttons.push(trial.button_html); } } var btngroup_div = document.createElement("div"); btngroup_div.id = "jspsych-image-button-response-btngroup"; html = ""; for (var i = 0; i < trial.choices.length; i++) { var str = buttons[i].replace(/%choice%/g, trial.choices[i]); html += '<div class="jspsych-image-button-response-button" style="display: inline-block; margin:' + trial.margin_vertical + " " + trial.margin_horizontal + '" id="jspsych-image-button-response-button-' + i + '" data-choice="' + i + '">' + str + "</div>"; } btngroup_div.innerHTML = html; // add canvas to screen and draw image display_element.insertBefore(canvas, null); if (img.complete && Number.isFinite(width) && Number.isFinite(height)) { // if image has loaded and width/height have been set, then draw it now // (don't rely on img onload function to draw image when image is in the cache, because that causes a delay in the image presentation) ctx.drawImage(img, 0, 0, width, height); image_drawn = true; } // add buttons to screen display_element.insertBefore(btngroup_div, canvas.nextElementSibling); // add prompt if there is one if (trial.prompt !== null) { display_element.insertAdjacentHTML("beforeend", trial.prompt); } } else { // display stimulus as an image element html = '<img src="' + trial.stimulus + '" id="jspsych-image-button-response-stimulus">'; //display buttons var buttons = []; if (Array.isArray(trial.button_html)) { if (trial.button_html.length == trial.choices.length) { buttons = trial.button_html; } else { console.error( "Error in image-button-response plugin. The length of the button_html array does not equal the length of the choices array" ); } } else { for (var i = 0; i < trial.choices.length; i++) { buttons.push(trial.button_html); } } html += '<div id="jspsych-image-button-response-btngroup">'; for (var i = 0; i < trial.choices.length; i++) { var str = buttons[i].replace(/%choice%/g, trial.choices[i]); html += '<div class="jspsych-image-button-response-button" style="display: inline-block; margin:' + trial.margin_vertical + " " + trial.margin_horizontal + '" id="jspsych-image-button-response-button-' + i + '" data-choice="' + i + '">' + str + "</div>"; } html += "</div>"; // add prompt if (trial.prompt !== null) { html += trial.prompt; } // update the page content display_element.innerHTML = html; // set image dimensions after image has loaded (so that we have access to naturalHeight/naturalWidth) var img = display_element.querySelector( "#jspsych-image-button-response-stimulus" ) as HTMLImageElement; if (trial.stimulus_height !== null) { height = trial.stimulus_height; if (trial.stimulus_width == null && trial.maintain_aspect_ratio) { width = img.naturalWidth * (trial.stimulus_height / img.naturalHeight); } } else { height = img.naturalHeight; } if (trial.stimulus_width !== null) { width = trial.stimulus_width; if (trial.stimulus_height == null && trial.maintain_aspect_ratio) { height = img.naturalHeight * (trial.stimulus_width / img.naturalWidth); } } else if (!(trial.stimulus_height !== null && trial.maintain_aspect_ratio)) { // if stimulus width is null, only use the image's natural width if the width value wasn't set // in the if statement above, based on a specified height and maintain_aspect_ratio = true width = img.naturalWidth; } img.style.height = height.toString() + "px"; img.style.width = width.toString() + "px"; } // start timing var start_time = performance.now(); for (var i = 0; i < trial.choices.length; i++) { display_element .querySelector("#jspsych-image-button-response-button-" + i) .addEventListener("click", (e) => { var btn_el = e.currentTarget as HTMLButtonElement; var choice = btn_el.getAttribute("data-choice"); // don't use dataset for jsdom compatibility after_response(choice); }); } // store response var response = { rt: null, button: null, }; // function to end trial when it is time const end_trial = () => { // kill any remaining setTimeout handlers this.jsPsych.pluginAPI.clearAllTimeouts(); // gather the data to store for the trial var trial_data = { rt: response.rt, stimulus: trial.stimulus, response: response.button, }; // clear the display display_element.innerHTML = ""; // move on to the next trial this.jsPsych.finishTrial(trial_data); }; // function to handle responses by the subject function after_response(choice) { // measure rt var end_time = performance.now(); var rt = Math.round(end_time - start_time); response.button = parseInt(choice); response.rt = rt; // after a valid response, the stimulus will have the CSS class 'responded' // which can be used to provide visual feedback that a response was recorded display_element.querySelector("#jspsych-image-button-response-stimulus").className += " responded"; // disable all the buttons after a response var btns = document.querySelectorAll(".jspsych-image-button-response-button button"); for (var i = 0; i < btns.length; i++) { //btns[i].removeEventListener('click'); btns[i].setAttribute("disabled", "disabled"); } if (trial.response_ends_trial) { end_trial(); } } // hide image if timing is set if (trial.stimulus_duration !== null) { this.jsPsych.pluginAPI.setTimeout(() => { display_element.querySelector<HTMLElement>( "#jspsych-image-button-response-stimulus" ).style.visibility = "hidden"; }, trial.stimulus_duration); } // end trial if time limit is set if (trial.trial_duration !== null) { this.jsPsych.pluginAPI.setTimeout(() => { end_trial(); }, trial.trial_duration); } else if (trial.response_ends_trial === false) { console.warn( "The experiment may be deadlocked. Try setting a trial duration or set response_ends_trial to true." ); } } } export default ImageButtonResponsePlugin;
the_stack
import { ISPHttpClientOptions, MSGraphClient, SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http"; import "@pnp/sp/lists"; import { sp } from "@pnp/sp/presets/all"; import "@pnp/sp/views"; import { Web } from "@pnp/sp/webs"; import { initializeIcons } from "@uifabric/icons"; import "bootstrap/dist/css/bootstrap.min.css"; import { ThemeStyle } from "msteams-ui-styles-core"; import * as React from "react"; import Col from "react-bootstrap/Col"; import Media from "react-bootstrap/Media"; import Row from "react-bootstrap/Row"; import siteconfig from "../config/siteconfig.json"; import styles from "../scss/CMPHome.module.scss"; import ApproveChampion from "./ApproveChampion"; import ChampionLeaderBoard from "./ChampionLeaderBoard"; import ClbAddMember from "./ClbAddMember"; import ClbChampionsList from "./ClbChampionsList"; import DigitalBadge from "./DigitalBadge"; import EmployeeView from "./EmployeeView"; import Header from "./Header"; import { IClbHomeProps } from "./IClbHomeProps"; import TOTLandingPage from "./TOTLandingPage"; initializeIcons(); export interface IClbHomeState { cB: boolean; clB: boolean; addMember: boolean; approveMember: boolean; ChampionsList: boolean; cV: boolean; siteUrl: string; eV: boolean; dB: boolean; sitename: string; inclusionpath: string; siteId: any; isShow: boolean; loggedinUserName: string; loggedinUserEmail: string; enableTOT: boolean; isTOTEnabled: boolean; isUserAdded: boolean; userStatus: string; firstName: string; } //Global Variables const cmpLog: string = "CMP Logs: "; let flagCheckUserRole: boolean = true; const errorMessage: string = "An unexpected error occured "; let rootSiteURL: string; let spweb: any; export default class ClbHome extends React.Component< IClbHomeProps, IClbHomeState > { constructor(_props: any) { super(_props); this.state = { siteUrl: this.props.siteUrl, cB: false, addMember: false, approveMember: false, ChampionsList: false, clB: false, cV: false, eV: false, dB: false, sitename: siteconfig.sitename, inclusionpath: siteconfig.inclusionPath, siteId: "", isShow: false, loggedinUserName: "", loggedinUserEmail: "", enableTOT: false, isTOTEnabled: false, isUserAdded: false, userStatus: "", firstName: "" }; this.checkUserRole = this.checkUserRole.bind(this); //Set the context for PNP sp.setup({ spfxContext: this.props.context }); //set context if (this.props.context.pageContext.web.serverRelativeUrl == "/") rootSiteURL = this.props.context.pageContext.web.absoluteUrl; else rootSiteURL = this.props.siteUrl; spweb = Web(rootSiteURL + '/' + this.state.inclusionpath + "/" + siteconfig.sitename); } public componentDidMount() { this.setState({ isShow: true, }); //check if TOT is already enabled this.checkTOTIsEnabled(); //Get current user details and set state this.props.context.spHttpClient .get( "/_api/SP.UserProfiles.PeopleManager/GetMyProperties", SPHttpClient.configurations.v1 ) .then((responseuser: SPHttpClientResponse) => { responseuser.json().then((datauser: any) => { this.setState({ loggedinUserName: datauser.DisplayName }); this.setState({ loggedinUserEmail: datauser.Email }); //Create site and lists when app is installed this.createSiteAndLists().then(() => { //Check current user's role and set UI components this.checkUserRole(datauser.Email); }); var props = {}; datauser.UserProfileProperties.forEach((prop) => { props[prop.Key] = prop.Value; }); datauser.userProperties = props; this.setState({ firstName: datauser.userProperties.FirstName }); }); }).catch((error) => { alert(errorMessage + "while retrieving user details. Below is the " + JSON.stringify(error)); console.error("CMP_CLBHome_componentDidMount_FailedToGetUserDetails \n", JSON.stringify(error)); }); } //verify tot is enabled private async checkTOTIsEnabled() { try { const listStructure: any = siteconfig.totLists; let listsPresent = []; let allTOTLists = []; let fieldsMisMatchCount = 0; await listStructure.forEach(async (element) => { const spListTitle: string = element["listName"]; const fieldsToCreate: string[] = element["fields"]; allTOTLists.push(spListTitle); await spweb.lists.getByTitle(spListTitle).get().then(async (list) => { if (list != undefined) { listsPresent.push(spListTitle); //validate for fields let totalFieldsToCreate = await this.checkFieldExists(spListTitle, fieldsToCreate); if (totalFieldsToCreate.length != 0) { fieldsMisMatchCount++; } } }) .catch(() => { this.setState({ isTOTEnabled: false }); }); //if mismatch found across lists if (listsPresent.length == 0 || (listsPresent.length != allTOTLists.length) || fieldsMisMatchCount > 0) { this.setState({ isTOTEnabled: false }); } else { this.setState({ isTOTEnabled: true }); } }); } catch (error) { alert(errorMessage + "while verifying tournament of Teams is enabled. Below is the " + JSON.stringify(error)); console.error("CMP_CLBHome_checkTOTIsEnabled_FailedToVerifyListsFields \n", JSON.stringify(error)); } } //validate if the list column already exists private async checkFieldExists(spListTitle: string, fieldsToCreate: string[]) { let totalFieldsToCreate = []; try { const filterFields = await spweb.lists.getByTitle(spListTitle).fields .filter("Hidden eq false and ReadOnlyField eq false") .get(); for (let i = 0; i < fieldsToCreate.length; i++) { // compare fields const parser = new DOMParser(); const xml = parser.parseFromString(fieldsToCreate[i], 'text/xml'); let fieldNameToCheck = xml.querySelector('Field').getAttribute('DisplayName'); let fieldExists = filterFields.filter(e => e.Title == fieldNameToCheck); if (fieldExists.length == 0) { totalFieldsToCreate.push(fieldsToCreate[i]); } } return totalFieldsToCreate; } catch (error) { alert(errorMessage + "while checking required fields exists. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_clbhome_checkFieldExists \n", error); } } //create lists private createNewList(siteId: any, item: any) { this.props.context.msGraphClientFactory .getClient() .then(async (client: MSGraphClient) => { client .api("sites/" + siteId + "/lists") .version("v1.0") .header("Content-Type", "application/json") .responseType("json") .post(item, (errClbHome, _res, rawresponse) => { if (!errClbHome) { if (rawresponse.status === 201) { console.log(cmpLog + "List created: " + "'" + item.displayName + "'"); setTimeout(() => { this.props.context.spHttpClient .get( "/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties", SPHttpClient.configurations.v1 ) .then( ( userProperties: SPHttpClientResponse ) => { userProperties .json() .then(async (adminUser: any) => { let goAndCreateMember: boolean; goAndCreateMember = false; if (adminUser) { this.props.context.spHttpClient .get( "/" + this.state.inclusionpath + "/" + this.state.sitename + `/_api/web/lists/GetByTitle('Member List')/Items?$filter= Title eq '${adminUser.Email}'`, SPHttpClient.configurations.v1 ) .then((response: SPHttpClientResponse) => { response.json().then((datada) => { if (!datada.error) { let val = datada.value; if (val.length === 0 && item.displayName === "Member List") { { const listDefinition: any = { Title: adminUser.Email, FirstName: adminUser.DisplayName.split( " " )[0], LastName: adminUser.DisplayName.split( " " )[1], // "Region": '', // "Country": '', Role: "Manager", Status: "Approved", Group: "IT Pro", FocusArea: "All", }; const spHttpClientOptions: ISPHttpClientOptions = { body: JSON.stringify( listDefinition ), }; const url: string = "/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/web/lists/GetByTitle('Member List')/items"; this.props.context.spHttpClient .post( url, SPHttpClient.configurations .v1, spHttpClientOptions ) .then( ( newUserResponse: SPHttpClientResponse ) => { this.setState({ isShow: false, }); if ( newUserResponse.status === 201 ) { alert( ` ${this.state.loggedinUserName} has been added as a manager to the Champion Management Platform, please refresh the app to complete the setup.` ); } else { alert( "Response status " + newUserResponse.status + " - " + newUserResponse.statusText ); } } ); } } } }); }); } }); } ); }, 6000); setTimeout(() => { if (item.displayName === "Events List") { siteconfig.eventsMasterData.forEach( (eventData) => { let eventDataList: any = { Title: eventData.Title, Points: eventData.Points, Description: eventData.Description, IsActive: true, }; const spHttpClientOptions: ISPHttpClientOptions = { body: JSON.stringify(eventDataList), }; const url: string = "/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/web/lists/GetByTitle('Events List')/items"; this.props.context.spHttpClient .post( url, SPHttpClient.configurations.v1, spHttpClientOptions ) .then( ( newUserResponse: SPHttpClientResponse ) => { } ); } ); } }, 5000); } } }); }).catch((error) => { alert(errorMessage + "while creating new list. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_createNewList_FailedtoCreateList \n", JSON.stringify(error)); }); } //When app is installed create new site collection and lists if not existing already private async createSiteAndLists() { console.log(cmpLog + "Checking if site exists already."); //Set Variables var exSiteId; try { //Check if CMP site exists await sp.site.exists(rootSiteURL + "/" + this.state.inclusionpath + "/" + this.state.sitename).then((response) => { if (response != undefined) { //If CMP site does not exist, create the site and lists if (!response) { flagCheckUserRole = false; console.log(cmpLog + "Creating new site collection: '" + this.state.sitename + "'"); //Create a new site collection const createSiteUrl: string = "/_api/SPSiteManager/create"; const siteDefinition: any = { request: { Title: this.state.sitename, Url: this.state.siteUrl.replace("https:/", "https://").replace("https:///", "https://") + "/" + this.state.inclusionpath + "/" + this.state.sitename, Lcid: 1033, ShareByEmailEnabled: true, Description: "Description", WebTemplate: "STS#3", SiteDesignId: "6142d2a0-63a5-4ba0-aede-d9fefca2c767", Owner: this.state.loggedinUserEmail, }, }; const spHttpsiteClientOptions: ISPHttpClientOptions = { body: JSON.stringify(siteDefinition), }; //HTTP post request for creating a new site collection this.props.context.spHttpClient .post( createSiteUrl, SPHttpClient.configurations.v1, spHttpsiteClientOptions ) .then((siteResponse: SPHttpClientResponse) => { //If site is succesfully created if (siteResponse.status === 200) { console.log(cmpLog + "Created new site collection: '" + this.state.sitename + "'"); siteResponse.json().then((siteData: any) => { if (siteData.SiteId) { exSiteId = siteData.SiteId; this.setState({ siteId: siteData.SiteId }, () => { let isMembersListNotExists = false; console.log(cmpLog + "Creating Lists in new site"); //Create 3 lists in the newly created site if (exSiteId) { let lists = []; siteconfig.lists.forEach((item) => { let listColumns = []; item.columns.forEach((element) => { let column; switch (element.type) { case "text": column = { name: element.name, text: {}, }; listColumns.push(column); break; case "choice": switch (element.name) { case "Region": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Africa", "Asia", "Australia / Pacific", "Europe", "Middle East", "North America / Central America / Caribbean", "South America", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Country": column = { name: element.name, choice: { allowTextEntry: false, choices: ["INDIA", "USA"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Role": column = { name: element.name, choice: { allowTextEntry: false, choices: ["Manager", "Champion"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Status": column = { name: element.name, choice: { allowTextEntry: false, choices: ["Approved", "Pending"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "FocusArea": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Marketing", "Teamwork", "Business Apps", "Virtual Events", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Group": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "IT Pro", "Sales", "Engineering", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Description": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Event Moderator", "Office Hours", "Blogs", "Training", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; default: break; } break; case "boolean": column = { name: element.name, boolean: {}, }; listColumns.push(column); break; case "dateTime": column = { name: element.name, dateTime: {}, }; listColumns.push(column); break; case "number": column = { name: element.name, number: {}, }; listColumns.push(column); break; default: break; } }); let list = { displayName: item.listName, columns: listColumns, list: { template: "genericList", }, }; lists.push(list); }); lists.forEach((item) => { let siteId = item.displayName === siteconfig.lists[0].listName ? this.state.siteId // siteconfig.rootSiteId : exSiteId; if ( item.displayName === siteconfig.lists[0].listName && !isMembersListNotExists ) { this.createNewList(siteId, item); } else { this.createNewList(siteId, item); } }); } }); } }); //site is newly created and got 200 response, now create Digital Lib this.createDigitalBadgeLib(); } }).catch((error) => { alert(errorMessage + "while creating new site. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_createSiteAndLists_FailedToCreateSite \n", JSON.stringify(error)); }); }//IF END //If CMP site already exists create only lists. else { //Check if Lists exists already this.props.context.spHttpClient .get("/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/web/lists/GetByTitle('Member List')/Items", SPHttpClient.configurations.v1) .then((responseMemberList: SPHttpClientResponse) => { if (responseMemberList.status === 404) { //If lists do not exist create lists. Else no action is required console.log(cmpLog + "Site already existing but lists not found"); console.log(cmpLog + "Getting site collection ID for creating lists"); flagCheckUserRole = false; //Get Sitecollection ID for creating lists this.props.context.spHttpClient .get("/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/site/id", SPHttpClient.configurations.v1) .then((responseuser: SPHttpClientResponse) => { if (responseuser.status === 404) { alert(errorMessage + "while setting up the App. Please try refreshing or loading after some time."); console.error("CMP_CLBHome_createSiteAndLists_FailedToGetSiteID \n"); } else { responseuser.json().then((datauser: any) => { exSiteId = datauser.value; if (exSiteId) { console.log(cmpLog + "Creating lists"); //Set up List Creation Information let lists = []; siteconfig.lists.forEach((item) => { let listColumns = []; item.columns.forEach((element) => { let column; switch (element.type) { case "text": column = { name: element.name, text: {}, }; listColumns.push(column); break; case "choice": switch (element.name) { case "Region": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Africa", "Asia", "Australia / Pacific", "Europe", "Middle East", "North America / Central America / Caribbean", "South America", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Country": column = { name: element.name, choice: { allowTextEntry: false, choices: ["INDIA", "USA"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Role": column = { name: element.name, choice: { allowTextEntry: false, choices: ["Manager", "Champion"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Status": column = { name: element.name, choice: { allowTextEntry: false, choices: ["Approved", "Pending"], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "FocusArea": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Marketing", "Teamwork", "Business Apps", "Virtual Events", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Group": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "IT Pro", "Sales", "Engineering", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; case "Description": column = { name: element.name, choice: { allowTextEntry: false, choices: [ "Event Moderator", "Office Hours", "Blogs", "Training", ], displayAs: "dropDownMenu", }, }; listColumns.push(column); break; default: break; } break; case "boolean": column = { name: element.name, boolean: {}, }; listColumns.push(column); break; case "dateTime": column = { name: element.name, dateTime: {}, }; listColumns.push(column); break; case "number": column = { name: element.name, number: {}, }; listColumns.push(column); break; default: break; } }); let list = { displayName: item.listName, columns: listColumns, list: { template: "genericList", }, }; lists.push(list); }); //Iterate and create all the lists lists.forEach((item) => { this.createNewList(exSiteId, item); }); } }); } }).catch((error) => { alert(errorMessage + "while retrieving SiteID. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_createSiteAndLists_FailedToGetSiteID \n", JSON.stringify(error)); }); } }).catch((error) => { alert(errorMessage + "while checking if MemberList exists. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_createSiteAndLists_FailedToCheckMemberListExists \n", JSON.stringify(error)); }); //site exists, check if Digital Badge lib exists, create if not present this.createDigitalBadgeLib(); }//End of else part - CMP site already exists create only lists. }//First IF END }).catch((error) => { alert(errorMessage + "while checking if site exists. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_createSiteAndLists_FailedtoCheckIfSiteExists \n", JSON.stringify(error)); }); } catch (error) { console.error("CMP_CLBHome_createSiteAndLists \n", error); alert(errorMessage + "while creating site and lists. Below are the details: \n" + error); } } //create digital lib to store the badges private async createDigitalBadgeLib() { try { const listStructure: any = siteconfig.libraries; for (let i = 0; i < listStructure.length; i++) { const spListTitle: string = listStructure[i]["listName"]; const spListTemplate = listStructure[i]["listTemplate"]; //check if digital assests lib exists, create if doesn't exists and upload default badge await spweb.lists.getByTitle(spListTitle).get().then(async () => { }). catch(async () => { //create lib await spweb.lists.add(spListTitle, "", spListTemplate, true).then(async () => { fetch(require('../assets/images/CMPBadge.png')).then(res => res.blob()).then((blob) => { spweb.getFolderByServerRelativeUrl("/" + this.state.inclusionpath + "/" + this.state.sitename + "/" + spListTitle).files.add("digitalbadge.png", blob, true) .then((res) => { res.file.getItem().then(item => { item.update({ Title: "Teamwork Champion" }); }); }); }); const deafultXML = await spweb.lists.getByTitle(spListTitle).defaultView.fields.getSchemaXml(); let titleFieldIndex = deafultXML.indexOf("Title"); if (titleFieldIndex == -1) { await spweb.lists.getByTitle(spListTitle).defaultView.fields.add("Title"); } }); }); //catch end } } catch (error) { console.error("CMP_CLBHome_createDigitalBadgeLib \n", error); } } //Check current users's role from "Member List" and set the UI components accordingly private async checkUserRole(userEmail: string) { try { if (flagCheckUserRole) { console.log(cmpLog + "Checking user role and setting the UI components"); this.props.context.spHttpClient .get( "/" + this.state.inclusionpath + "/" + this.state.sitename + "/_api/web/lists/GetByTitle('Member List')/Items?$filter=Title eq '" + userEmail.toLowerCase() + "'", SPHttpClient.configurations.v1 ) .then((response: SPHttpClientResponse) => { if (response.status === 200) { this.setState({ isShow: false, }); } response.json().then((datada) => { if (!datada.error) { let dataexists: any = datada.value.find( (x) => x.Title.toLowerCase() === this.state.loggedinUserEmail.toLowerCase() ); if (dataexists) { if (dataexists.Status === "Approved") { if (dataexists.Role === "Manager") { this.setState({ clB: true }); } else if (dataexists.Role === "Champion") { this.setState({ cV: true }); } } else if ( dataexists.Role === "Employee" || dataexists.Role === "Champion" || dataexists.Role === "Manager" ) { this.setState({ eV: true }); } } else this.setState({ eV: true }); } }); }).catch((error) => { alert(errorMessage + "while retrieving user role. Below are the details: \n" + JSON.stringify(error)); console.error("CMP_CLBHome_checkUserRole_FailedtoGetUserRole \n", JSON.stringify(error)); }); } } catch (error) { console.error("CMP_CLBHome_checkUserRole \n", error); alert(errorMessage + " while retrieving user role. Below are the details: \n" + error); } } public render(): React.ReactElement<IClbHomeProps> { return ( <div className={styles.clbHome} > {this.state.isShow && <div className={styles.load}></div>} < div className={styles.container} > <div> <Header showSearch={this.state.cB} clickcallback={() => this.setState({ cB: false, ChampionsList: false, addMember: false, dB: false, approveMember: false, enableTOT: false }) } /> </div> {!this.state.cB && !this.state.ChampionsList && !this.state.addMember && !this.state.approveMember && !this.state.dB && !this.state.enableTOT && ( <div> <div className={styles.imgheader}> <span className={styles.cmpPageHeading}>Welcome {this.state.firstName}!</span> </div> <div className={styles.grid}> <div className={styles.quickguide}>Get Started</div> <Row className="mt-4"> <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor} onClick={() => this.setState({ cB: !this.state.cB })} > <div className={styles.mb}> <img src={require("../assets/CMPImages/ChampionLeaderBoard.svg")} alt="Champion Leader Board" title="Champion Leader Board" className={styles.dashboardimgs} /> <div className={styles.center} title="Champion Leader Board"> Champion Leader Board </div> </div> </Media> </Col> {(this.state.cV || this.state.clB) && ( <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor} onClick={() => this.setState({ addMember: !this.state.addMember, }) } > <div className={styles.mb}> <img src={require("../assets/CMPImages/AddMembers.svg")} alt="Adding Members Start adding the people you will collaborate with in your..." title="Adding Members Start adding the people you will collaborate with in your..." className={styles.dashboardimgs} /> <div className={styles.center} title="Add Members">Add Members</div> </div> </Media> </Col> )} {(this.state.cV || this.state.clB) && ( <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor} onClick={() => this.setState({ dB: !this.state.dB })} > <div className={styles.mb}> <img src={require("../assets/CMPImages/DigitalBadge.svg")} alt="Digital Badge, Get your Champion Badge" title="Digital Badge, Get your Champion Badge" className={styles.dashboardimgs} /> <div className={styles.center} title="Digital Badge">Digital Badge</div> </div> </Media> </Col> )} {this.state.isTOTEnabled && ( <Col sm={3} className={styles.imageLayout}> <div> <Media className={styles.cursor} onClick={() => this.setState({ enableTOT: !this.state.enableTOT })} > <div className={styles.mb}> <img src={require("../assets/CMPImages/TournamentOfTeams.svg")} alt="Tournament of Teams" title="Tournament of Teams" className={styles.dashboardimgs} /> {this.state.isTOTEnabled && (<div className={`${styles.center} ${styles.totLabel}`} title="Tournament of Teams"> Tournament of Teams</div>)} </div> </Media> </div> </Col>)} </Row> {this.state.clB && !this.state.cV && ( <div className={styles.admintools}>Admin Tools</div>)} {this.state.clB && !this.state.cV && ( <Row className="mt-4"> <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor}> <div className={styles.mb}> <a href={`/${this.state.inclusionpath}/${this.state.sitename}/Lists/Member%20List/AllItems.aspx`} target="_blank" > <img src={require("../assets/CMPImages/ChampionList.svg")} alt="Accessing Champions List" title="Accessing Champions List" className={styles.dashboardimgs} /> </a> <div className={styles.center} title="Champions List">Champions List</div> </div> </Media> </Col> <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor}> <div className={styles.mb}> <a href={`/${this.state.inclusionpath}/${this.state.sitename}/Lists/Events%20List/AllItems.aspx`} target="_blank" > <img src={require("../assets/CMPImages/EventsList.svg")} alt="Accessing Events List" title="Accessing Events List" className={styles.dashboardimgs} /> </a> <div className={styles.center} title="Events List">Events List</div> </div> </Media> </Col> <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor}> <div className={styles.mb}> <a href={`/${this.state.inclusionpath}/${this.state.sitename}/Lists/Event%20Track%20Details/AllItems.aspx`} target="_blank" > <img src={require("../assets/CMPImages/EventTrackList.svg")} alt="Accessing Event Track List" title="Accessing Event Track List" className={styles.dashboardimgs} /> </a> <div className={styles.center} title="Event Track List"> Event Track List </div> </div> </Media> </Col> <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor} onClick={() => this.setState({ approveMember: !this.state.approveMember, }) } > <div className={styles.mb}> <img src={require("../assets/CMPImages/ManageApprovals.svg")} alt="Approve Champion" title="Approve Champion" className={styles.dashboardimgs} /> <div className={styles.center} title="Manage Approvals"> Manage Approvals </div> </div> </Media> </Col> {!this.state.isTOTEnabled && ( <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor} onClick={() => this.setState({ enableTOT: !this.state.enableTOT })} > <div className={styles.mb}> <img src={require("../assets/CMPImages/EnableTOT.svg")} alt="Enable Tournament of Teams" title="Enable Tournament of Teams" className={styles.dashboardimgs} /> {!this.state.isTOTEnabled && (<div className={`${styles.center} ${styles.enableTournamentLabel}`} title="Enable Tournament of Teams"> Enable Tournament of Teams</div>)} </div> </Media> </Col>)} <Col sm={3} className={styles.imageLayout}> <Media className={styles.cursor}> <div className={styles.mb}> <a href={`/${this.state.inclusionpath}/${this.state.sitename}/Digital%20Badge%20Assets/Forms/AllItems.aspx`} target="_blank" > <img src={require("../assets/CMPImages/ManageDigitalBadges.svg")} alt="Manage Digital Badges" title="Manage Digital Badges" className={styles.dashboardimgs} /> </a> <div className={styles.center} title="Manage Digital Badges"> Manage Digital Badges </div> </div> </Media> </Col> </Row> )} {this.state.clB && !this.state.cV && ( <Row> </Row> )} </div> </div> ) } { this.state.cB && this.state.clB && ( <ChampionLeaderBoard siteUrl={this.props.siteUrl} context={this.props.context} onClickCancel={() => this.setState({ clB: true, cB: false })} /> ) } { this.state.cB && this.state.cV && ( <ChampionLeaderBoard siteUrl={this.props.siteUrl} context={this.props.context} onClickCancel={() => this.setState({ clB: false, cB: false })} /> ) } { this.state.enableTOT && ( <TOTLandingPage siteUrl={this.props.siteUrl} context={this.props.context} isTOTEnabled={this.state.isTOTEnabled} /> ) } { this.state.addMember && ( <ClbAddMember siteUrl={this.props.siteUrl} context={this.props.context} onClickCancel={() => this.setState({ addMember: false, ChampionsList: true, isUserAdded: false }) } onClickSave={(userStatus: string) => this.setState({ addMember: false, ChampionsList: true, isUserAdded: true, userStatus: userStatus }) } onClickBack={() => { this.setState({ addMember: false }); }} /> ) } { this.state.approveMember && ( <ApproveChampion siteUrl={this.props.siteUrl} context={this.props.context} isEmp={this.state.cV === true || this.state.clB === true} onClickAddmember={() => this.setState({ cB: false, ChampionsList: false, addMember: false, approveMember: false }) } /> ) } { this.state.ChampionsList && ( <ClbChampionsList siteUrl={this.props.siteUrl} context={this.props.context} isEmp={this.state.cV === true || this.state.clB === true} userAdded={this.state.isUserAdded} userStatus={this.state.userStatus} onClickAddmember={() => this.setState({ cB: false, ChampionsList: false, addMember: false, approveMember: false }) } /> ) } { this.state.cB && this.state.eV && ( <EmployeeView siteUrl={this.props.siteUrl} context={this.props.context} onClickCancel={() => this.setState({ eV: true, cB: false })} /> ) } { this.state.dB && ( <DigitalBadge siteUrl={this.props.siteUrl} context={this.props.context} clientId="" description="" theme={ThemeStyle.Light} fontSize={12} clickcallback={() => this.setState({ dB: false })} clickcallchampionview={() => this.setState({ cB: false, eV: false, dB: false }) } /> ) } </div > </div > ); } }
the_stack
import * as ts from 'typescript'; import * as fs from 'fs-extra'; import { spawn } from 'cross-spawn'; import { Emitter } from './emitter'; import { Helpers } from './helpers'; export enum ForegroundColorEscapeSequences { Grey = '\u001b[90m', Red = '\u001b[91m', Green = '\u001b[92m', Yellow = '\u001b[93m', Blue = '\u001b[94m', Pink = '\u001b[95m', Cyan = '\u001b[96m', White = '\u001b[97m' } export enum BackgroundColorEscapeSequences { Grey = '\u001b[100m', Red = '\u001b[101m', Green = '\u001b[102m', Yellow = '\u001b[103m', Blue = '\u001b[104m', Pink = '\u001b[105m', Cyan = '\u001b[106m', White = '\u001b[107m' } export enum BoldForegroundColorEscapeSequences { Grey = '\u001b[90;1m', Red = '\u001b[91;1m', Green = '\u001b[92;1m', Yellow = '\u001b[93;1m', Blue = '\u001b[94;1m', Pink = '\u001b[95;1m', Cyan = '\u001b[96;1m', White = '\u001b[97;1m' } export enum BoldBackgroundColorEscapeSequences { Grey = '\u001b[100;1m', Red = '\u001b[101;1m', Green = '\u001b[102;1m', Yellow = '\u001b[103;1m', Blue = '\u001b[104;1m', Pink = '\u001b[105;1m', Cyan = '\u001b[106;1m', White = '\u001b[107;1m' } const underlineStyleSequence = '\u001b[4m'; const gutterStyleSequence = '\u001b[7m'; const resetEscapeSequence = '\u001b[0m'; export class Run { private formatHost: ts.FormatDiagnosticsHost; private versions: Map<string, number> = new Map<string, number>(); public constructor() { this.formatHost = <ts.FormatDiagnosticsHost>{ getCanonicalFileName: path => path, getCurrentDirectory: ts.sys.getCurrentDirectory, getNewLine: () => ts.sys.newLine }; } public static processOptions(cmdLineArgs: string[]): any { const options = {}; for (let i = 2; i < cmdLineArgs.length; i++) { const item = cmdLineArgs[i]; if (!item || item[0] !== '-') { continue; } const option = item.substring(1); options[option] = true; if (option === 'run_on_compile') { options[option] = cmdLineArgs[++i]; } } return options; } public static processFiles(cmdLineArgs: string[]): any { const files = []; for (let i = 2; i < cmdLineArgs.length; i++) { const item = cmdLineArgs[i]; if (!item || item[0] === '-') { if (item === '-run_on_compile') { ++i; } continue; } files.push(item); } if (files.length === 0) { return 'tsconfig.json'; } return files.length === 1 ? files[0] : files; } public run(sourcesOrConfigFile: string[] | string, cmdLineOptions: any): void { if (typeof (sourcesOrConfigFile) === 'string') { if (sourcesOrConfigFile.endsWith('.json')) { const configPath = ts.findConfigFile('./', ts.sys.fileExists, sourcesOrConfigFile); if (configPath) { this.compileWithConfig(configPath, cmdLineOptions); return; } else { throw new Error('Could not find a valid \'tsconfig.json\'.'); } } this.compileSources([sourcesOrConfigFile], cmdLineOptions); return; } this.compileSources(sourcesOrConfigFile, cmdLineOptions); } public compileSources(sources: string[], cmdLineOptions: any): void { this.generateBinary(ts.createProgram(sources, {}), sources, undefined, cmdLineOptions); } public compileWithConfig(configPath: string, cmdLineOptions: any): void { const configFile = ts.readJsonConfigFile(configPath, ts.sys.readFile); const parseConfigHost: ts.ParseConfigHost = { useCaseSensitiveFileNames: true, readDirectory: ts.sys.readDirectory, fileExists: ts.sys.fileExists, readFile: ts.sys.readFile }; const parsedCommandLine = ts.parseJsonSourceFileConfigFileContent(configFile, parseConfigHost, './'); const watch = cmdLineOptions && 'watch' in cmdLineOptions; cmdLineOptions.outDir = parsedCommandLine.options && parsedCommandLine.options.outDir; if (!watch) { // simple case, just compile const program = ts.createProgram({ rootNames: parsedCommandLine.fileNames, options: parsedCommandLine.options }); this.generateBinary(program, parsedCommandLine.fileNames, parsedCommandLine.options, cmdLineOptions); } else { const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; const watchCompilingHost = ts.createWatchCompilerHost( configPath, {}, ts.sys, createProgram, (d) => this.reportDiagnostic(d), (d) => this.reportWatchStatusChanged(d) ); watchCompilingHost.afterProgramCreate = program => { this.generateBinary( program.getProgram(), parsedCommandLine.fileNames, parsedCommandLine.options, cmdLineOptions); }; console.log(ForegroundColorEscapeSequences.Cyan + 'Watching...' + resetEscapeSequence); ts.createWatchProgram(watchCompilingHost); } } private reportDiagnostic(diagnostic: ts.Diagnostic) { const category = ts.DiagnosticCategory[diagnostic.category]; let action; let color; switch (<ts.DiagnosticCategory>diagnostic.category) { case ts.DiagnosticCategory.Warning: action = console.warn; color = ForegroundColorEscapeSequences.Yellow; break; case ts.DiagnosticCategory.Error: action = console.error; color = ForegroundColorEscapeSequences.Red; break; case ts.DiagnosticCategory.Suggestion: action = console.warn; color = ForegroundColorEscapeSequences.White; break; case ts.DiagnosticCategory.Message: action = console.log; color = resetEscapeSequence; break; } action(category, this.formatHost.getNewLine()); action( category, diagnostic.code, ':', ts.flattenDiagnosticMessageText(color + diagnostic.messageText + resetEscapeSequence, this.formatHost.getNewLine())); } private reportWatchStatusChanged(diagnostic: ts.Diagnostic) { console.log(ts.formatDiagnostic(diagnostic, this.formatHost)); } private generateBinary( program: ts.Program, sources: string[], options: ts.CompilerOptions, cmdLineOptions: any) { if (!cmdLineOptions.suppressOutput) { console.log(ForegroundColorEscapeSequences.Pink + 'Generating binary files...' + resetEscapeSequence); } const sourceFiles = program.getSourceFiles(); let outDir = cmdLineOptions.outDir || ''; if (outDir) { const lastChar = outDir[outDir.length - 1]; if (lastChar !== '/' && lastChar !== '\\') { outDir += '/'; } if (!fs.pathExistsSync(outDir)) { fs.mkdirSync(outDir, {recursive: true}); } } let rootFolder = process.cwd().replace(/\\/g, '/'); const lastChar2 = rootFolder[rootFolder.length - 1]; if (lastChar2 !== '/' && lastChar2 !== '\\') { rootFolder += '/'; } sourceFiles.filter(s => !s.fileName.endsWith('.d.ts') && sources.some(sf => s.fileName.endsWith(sf))).forEach(s => { // track version const paths = sources.filter(sf => s.fileName.endsWith(sf)); (<any>s).__path = paths[0]; const fileVersion = (<any>s).version; if (fileVersion) { const latestVersion = this.versions[s.fileName]; if (latestVersion && latestVersion === fileVersion) { if (!cmdLineOptions.suppressOutput) { console.log( 'File: ' + ForegroundColorEscapeSequences.White + s.fileName + resetEscapeSequence + ' current version:' + fileVersion + ', last version:' + latestVersion + '. ' + ForegroundColorEscapeSequences.Red + 'Skipped.' + resetEscapeSequence); } return; } this.versions[s.fileName] = fileVersion; } if (!cmdLineOptions.suppressOutput) { console.log( ForegroundColorEscapeSequences.Cyan + 'Processing File: ' + resetEscapeSequence + ForegroundColorEscapeSequences.White + s.fileName + resetEscapeSequence); } const emitterHeader = new Emitter(program.getTypeChecker(), options, cmdLineOptions, false, program.getCurrentDirectory()); emitterHeader.HeaderMode = true; emitterHeader.processNode(s); const emitterSource = new Emitter(program.getTypeChecker(), options, cmdLineOptions, false, program.getCurrentDirectory()); emitterSource.SourceMode = true; emitterSource.processNode(s); let fileNameNoExt = s.fileName.endsWith('.ts') ? s.fileName.substr(0, s.fileName.length - 3) : s.fileName; if (fileNameNoExt.startsWith(rootFolder)) { fileNameNoExt = fileNameNoExt.substring(rootFolder.length); } const fileNameHeader = Helpers.correctFileNameForCxx(fileNameNoExt.concat('.', 'h')); const fileNameCpp = Helpers.correctFileNameForCxx(fileNameNoExt.concat('.', 'cpp')); if (!cmdLineOptions.suppressOutput) { console.log( ForegroundColorEscapeSequences.Cyan + 'Writing to file: ' + resetEscapeSequence + ForegroundColorEscapeSequences.White + outDir + fileNameCpp + resetEscapeSequence); } fs.writeFileSync(outDir + fileNameHeader, emitterHeader.writer.getText()); fs.writeFileSync(outDir + fileNameCpp, emitterSource.writer.getText()); }); if (!cmdLineOptions.suppressOutput) { console.log(ForegroundColorEscapeSequences.Pink + 'Binary files have been generated...' + resetEscapeSequence); } if (cmdLineOptions.run_on_compile) { const result_compile: any = spawn.sync(cmdLineOptions.run_on_compile); if (result_compile.error) { console.log(ForegroundColorEscapeSequences.Red + 'Error: '); console.log(result_compile.error); console.log(ForegroundColorEscapeSequences.White + ''); } if (result_compile.stdout.length) { console.log(ForegroundColorEscapeSequences.Yellow + 'Result: '); console.log(result_compile.stdout.toString()); console.log(ForegroundColorEscapeSequences.White + ''); } if (result_compile.stderr.length) { console.log(ForegroundColorEscapeSequences.Red + 'Error output: '); console.log(result_compile.stderr.toString()); console.log(ForegroundColorEscapeSequences.White + ''); } } } public test(sources: string[], cmdLineOptions?: any, header?: string, footer?: string): string { let actualOutput = ''; // change folder process.chdir('test'); const fileName = 'test_'; const tempSourceFiles = sources.map((s: string, index: number) => fileName + index + '.ts'); const tempCxxFiles = sources.map((s: string, index: number) => fileName + index + '.cpp'); const tempHFiles = sources.map((s: string, index: number) => fileName + index + '.h'); // clean up tempSourceFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); tempCxxFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); tempHFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); try { sources.forEach((s: string, index: number) => { if (fs.existsSync(s)) { s = fs.readFileSync(s).toString(); if (header) { if (fs.existsSync(header)) { s = fs.readFileSync(header).toString() + s; } else { s = header + s; } } if (footer) { if (fs.existsSync(footer)) { s = s + fs.readFileSync(footer).toString(); } else { s = s + footer; } } } fs.writeFileSync(fileName + index + '.ts', s); }); // to use tsconfig to compile this.run('tsconfig.test.json', { suppressOutput: true }); // compiling const result_compile: any = spawn.sync('ms_test.bat', tempCxxFiles); if (result_compile.error) { actualOutput = result_compile.error.stack; } else if (result_compile.stdout.length) { actualOutput = result_compile.stdout.toString(); if (actualOutput.indexOf(': error') === -1) { actualOutput = ''; } } if (!actualOutput && result_compile.stderr.length) { actualOutput = result_compile.stderr.toString(); if (actualOutput.indexOf(': error') === -1) { actualOutput = ''; } } if (!actualOutput) { // start program and test it to const result: any = spawn.sync('testapp1', []); if (result.error) { actualOutput = result.error.stack; } else { actualOutput = (<Uint8Array>result.stdout).toString(); } } } catch (e) { // clean up tempSourceFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); tempCxxFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); process.chdir('..'); throw e; } // clean up tempSourceFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); tempCxxFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); tempHFiles.forEach(f => { if (fs.existsSync(f)) { fs.unlinkSync(f); } }); process.chdir('..'); return actualOutput; } }
the_stack
import { format, isNullOrUndefined } from "util"; import * as moment from "moment"; import * as chalk from "chalk"; /** * Class to contain writing log messages * @export * @class Logger */ export class Logger { /** * Supported levels of logging * @static * @memberof Logger */ public static readonly LEVELS = ["trace", "debug", "info", "warn", "error", "fatal"]; /** * Default log level * @static * @memberof Logger */ public static readonly LEVEL_DEFAULT = "info"; /** * Obtain instance of logger * @readonly * @static * @memberof Logger */ public static get get() { if (isNullOrUndefined(this.mLog)) { this.mLog = new Logger(); } return this.mLog; } /** * Determine if level is valid * @static * @param {string} level - level to validate * @returns - true if level exists, false otherwise * @memberof Logger */ public static isValidLevel(level: string) { return Logger.LEVELS.indexOf(level) < 0 ? false : true; } /** * Validate levels of logging * @static * @param {string} level - level to validate * @memberof Logger */ public static validateLevel(level: string) { if (!Logger.isValidLevel(level)) { throw new Error("invalid level"); } } /** * Static instance of logger object * @private * @static * @type {Logger} * @memberof Logger */ private static mLog: Logger; /** * Whether or not to prefix log messages * @private * @type {boolean} * @memberof Logger */ private mPrefix: boolean; /** * Whether or not to color log messages * @private * @type {boolean} * @memberof Logger */ private mColor: boolean; /** * Whether or not logging should be suppressed * @private * @type {boolean} * @memberof Logger */ private mIsOn: boolean; /** * Current set log level * @private * @type {string} * @memberof Logger */ private mLevel: string; /** * Creates an instance of Logger. * @memberof Logger */ constructor() { this.mLevel = Logger.LEVEL_DEFAULT; this.mPrefix = false; this.mColor = true; this.mLevel = this.mLevel.toLocaleLowerCase(); this.mIsOn = true; Logger.validateLevel(this.mLevel); } /** * Return whether ot not trace level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isTraceEnabled(): boolean { return Logger.LEVELS.indexOf("trace") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Return whether ot not debug level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isDebugEnabled(): boolean { return Logger.LEVELS.indexOf("debug") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Return whether ot not info level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isInfoEnabled(): boolean { return Logger.LEVELS.indexOf("info") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Return whether ot not warn level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isWarnEnabled(): boolean { return Logger.LEVELS.indexOf("warn") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Return whether ot not error level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isErrorEnabled(): boolean { return Logger.LEVELS.indexOf("error") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Return whether ot not fatal level logging is enabled * @returns {boolean} - true if level is enabled * @memberof Logger */ public isFatalEnabled(): boolean { return Logger.LEVELS.indexOf("fatal") >= Logger.LEVELS.indexOf(this.level) ? this.on : false; } /** * Trace level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public trace(message: string, ...args: any[]): string { if (!this.isTraceEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("TRACE") + message; } if (this.color) { adjustedMessage = chalk.cyan(adjustedMessage); } return this.writeStdout(adjustedMessage, args); } /** * Debug level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public debug(message: string, ...args: any[]): string { if (!this.isDebugEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("DEBUG") + message; } if (this.color) { adjustedMessage = chalk.green(adjustedMessage); } return this.writeStdout(adjustedMessage, args); } /** * Info level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public info(message: string, ...args: any[]): string { if (!this.isInfoEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("INFO") + message; } if (this.color) { adjustedMessage = chalk.blue(adjustedMessage); } return this.writeStdout(adjustedMessage, args); } /** * Warns level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public warn(message: string, ...args: any[]): string { if (!this.isWarnEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("WARN") + message; } if (this.color) { adjustedMessage = chalk.yellow(adjustedMessage); } return this.writeStderr(adjustedMessage, args); } /** * Error level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public error(message: string, ...args: any[]): string { if (!this.isErrorEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("ERROR") + message; } if (this.color) { adjustedMessage = chalk.red(adjustedMessage); } return this.writeStderr(adjustedMessage, args); } /** * Fatal level message * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ public fatal(message: string, ...args: any[]): string { if (!this.isFatalEnabled()) { return; } let adjustedMessage = message; if (this.prefix) { adjustedMessage = this.buildPrefix("FATAL") + message; } if (this.color) { adjustedMessage = chalk.magenta(adjustedMessage); } return this.writeStderr(adjustedMessage, args); } /** * Write to stderr * @private * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ private writeStderr(message: string, ...args: any[]): string { const data = this.format(message, args); process.stderr.write(this.format(message, args)); return data; } /** * Write to stdout * @private * @param {string} message - message to write * @param {...any[]} args - arguments for the message * @returns {string} - data written * @memberof Logger */ private writeStdout(message: string, ...args: any[]): string { const data = this.format(message, args); process.stdout.write(data); return data; } /** * Formats a message for argument substitution * @private * @param {string} data - message to write * @param {...any[]} args - arguments for the message * @returns {string} - substituted strong * @memberof Logger */ private format(data: string, ...args: any[]) { let formatted = data; // TODO(Kelosky): this is not ideal, but works for simple cases of // .debug(%s, "sub string"). if (this.formatEnabled && !isNullOrUndefined(args) && args.length > 0) { let defined = false; args.forEach((arg) => { arg.forEach((ntry: string[]) => { if (ntry.length > 0) { defined = true; } }); }); // if every argument is undefined, dont format it if (defined) { formatted = format(data, args); } } return formatted + "\n"; } /** * Build a message prefix * @private * @param {string} type - type for this message prefix (e.g. DEBUG) * @returns {string} - built prefix * @memberof Logger */ private buildPrefix(type: string) { return "[" + moment().format("YYYY/MM/DD HH:MM:SS") + "]" + " " + "[" + type + "]" + " "; } /** * Get whether or not format is enabled * @readonly * @memberof Logger */ get formatEnabled() { return true; } /** * Set whether or not color is enabled * @memberof Logger */ set color(isEnabled: boolean) { this.mColor = isEnabled; } /** * Get whether or not color is enabled * @type {boolean} * @memberof Logger */ get color(): boolean { return this.mColor; } /** * Set whether or not logging should occur * @memberof Logger */ set on(isOn: boolean) { this.mIsOn = isOn; } /** * Get if logging is on * @memberof Logger */ get on() { return this.mIsOn; } /** * Get current logging level * @readonly * @memberof Logger */ get level() { return this.mLevel; } /** * Get whether or not messages are prefixed * @type {boolean} * @memberof Logger */ get prefix(): boolean { return this.mPrefix; } /** * Set whether ot not to prefix messages * @memberof Logger */ set prefix(prefix) { this.mPrefix = prefix; } }
the_stack
// <copyright file="configure-preference" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> import * as React from 'react'; import * as microsoftTeams from "@microsoft/teams-js"; import { Flex, Text, Dropdown, RadioGroup, Loader, Button } from "@fluentui/react-northstar"; import { WithTranslation, withTranslation } from "react-i18next"; import { TFunction } from "i18next"; import { getPreferenceDetails } from "../../helpers/helper"; import { getAllCategories } from "../../api/category-api"; import Resources from '../../constants/resources'; import "../../styles/configure-preferences.css"; interface IConfigurePreferencesProps extends WithTranslation { configurePreferencesDetails: IConfigurePreferencesDetails; changeDialogOpenState: (isOpen: boolean) => void; } export interface IConfigurePreferencesState { loading: boolean, selectedCategoryList: Array<any>, allCategories: Array<any>, selectedDigestFrequency: string | undefined; isSubmitLoading: boolean; isCategoryPresent: boolean; configurePreferencesDetails: IConfigurePreferencesDetails; } interface IConfigurePreferencesDetails { categories: string; digestFrequency: string; teamId: string; } class ConfigurePreferences extends React.Component<IConfigurePreferencesProps, IConfigurePreferencesState> { localize: TFunction; userObjectId: string = ""; teamId: string = ""; appInsights: any; telemetry: string | undefined = ""; theme: string | undefined; constructor(props: any) { super(props); this.localize = this.props.t; this.teamId = ""; this.state = { allCategories: [], selectedDigestFrequency: Resources.weeklyDigestFrequencyText, selectedCategoryList: [], loading: true, isSubmitLoading: false, isCategoryPresent: true, configurePreferencesDetails: { ...this.props.configurePreferencesDetails } } } /** * Used to initialize Microsoft Teams sdk */ async componentDidMount() { microsoftTeams.initialize(); microsoftTeams.getContext(async (context) => { this.teamId = context.teamId!; this.theme = context.theme; this.setState({ loading: true }); }); await this.getCategory(); await this.getPreferences(); } /** *Get preferences from API */ async getPreferences() { let result = await getPreferenceDetails(this.teamId); let category: Array<any> = []; if (result !== undefined) { result.categories.forEach((value) => { let matchedData = this.state.allCategories.find(element => element.key === value); if (matchedData) { category.push({ key: matchedData.key, header: matchedData.header, }); } }); this.setState({ selectedCategoryList: category, selectedDigestFrequency: result.frequency }); } this.setState({ loading: false }); } /** *Get categories from API */ async getCategory() { this.setState({ loading: true }); let category = await getAllCategories(); if (category.status === 200 && category.data) { let categoryDetails: any[] = []; category.data.forEach((value) => { categoryDetails.push({ key: value.categoryId, header: value.categoryName, }); }); this.setState({ allCategories: categoryDetails, }); } this.setState({ loading: false }); } /** * Method to submit and save preferences details. */ onSubmitClick = async () => { if (this.state.selectedCategoryList.length === 0) { this.setState({ isCategoryPresent: false }); return; } this.setState({ isSubmitLoading: true }); let configureDetails = this.state.configurePreferencesDetails; let categoryUniqueIds: Array<any> = []; this.state.selectedCategoryList.forEach((value) => { categoryUniqueIds.push(value.key); }); configureDetails.digestFrequency = this.state.selectedDigestFrequency!; configureDetails.categories = categoryUniqueIds.join(';'); configureDetails.teamId = this.teamId; let toBot = { configureDetails, command: Resources.submitPreferencesTaskModule }; this.setState({ isSubmitLoading: false }); microsoftTeams.tasks.submitTask(toBot); } /** *Sets state of selectedCategoryList by removing category using its index. *@param index Index of category to be deleted. */ onCategoryRemoveClick = (index: number) => { let categories = this.state.selectedCategoryList; categories.splice(index, 1); this.setState({ selectedCategoryList: categories }); } /** * Method to get selected digest frequency value in state. * @param e event parameter. * @param props event parameter. */ getDigestFrequency = (e: any, props: any) => { this.setState({ selectedDigestFrequency: props.value }) } /** * Digest frequency radio button details. */ getItems() { return [ { name: Resources.digestFrequencyRadioName, key: Resources.weeklyDigestFrequencyText, label: this.localize('weeklyFrequencyText'), value: Resources.weeklyDigestFrequencyText, }, { name: Resources.digestFrequencyRadioName, key: Resources.monthlyDigestFrequencyText, label: this.localize('monthlyFrequencyText'), value: Resources.monthlyDigestFrequencyText, }, ] } getA11ySelectionMessage = { onAdd: item => { if (item) { let selectedCategories = this.state.selectedCategoryList; let category = this.state.allCategories.find(category => category.key === item.key); selectedCategories.push(category); this.setState({ selectedCategoryList: selectedCategories, isCategoryPresent: true }); } return ""; }, onRemove: item => { let categoryList = this.state.selectedCategoryList; let filterCategories = categoryList.filter(category => category.key !== item.key); this.setState({ selectedCategoryList: filterCategories }); return ""; } } /** *Returns text component containing error message for failed name field validation *@param {boolean} isValuePresent Indicates whether value is present */ private getRequiredFieldError = (isValuePresent: boolean) => { if (!isValuePresent) { return (<Text content={this.localize("fieldRequiredMessage")} className="field-error-message" error size="medium" />); } return (<></>); } public render(): JSX.Element { if (!this.state.loading) { return ( <div className="configure-preferences-div"> <Flex gap="gap.smaller"> <div className="top-spacing"> <Text size="small" content={this.localize("digestFrequencyLabel")} /> </div> </Flex> <Flex gap="gap.smaller" className="frequency-radio"> <RadioGroup vertical items={this.getItems()} defaultCheckedValue={this.state.selectedDigestFrequency} checkedValue={this.state.selectedDigestFrequency} onCheckedValueChange={(e: any, props: any) => this.getDigestFrequency(e, props)} /> </Flex> <Flex gap="gap.smaller" className="add-toppadding"> <Text size="small" content={"*" + this.localize("categoriesLabel")} /> <Flex.Item push> {this.getRequiredFieldError(this.state.isCategoryPresent)} </Flex.Item> </Flex> <Flex vAlign="center"> <Flex.Item align="start" grow> <Dropdown className="top-space" items={this.state.allCategories} multiple search fluid placeholder={this.localize("categoriesPlaceholder")} getA11ySelectionMessage={this.getA11ySelectionMessage} noResultsMessage={this.localize("noCategoryMatchFoundText")} value={this.state.selectedCategoryList} /> </Flex.Item> </Flex> <div className="tab-footer"> <Flex hAlign="end" > <Button primary loading={this.state.isSubmitLoading} disabled={this.state.isSubmitLoading} content={this.localize("Save")} onClick={this.onSubmitClick} /> </Flex> </div> </div> ); } else { return ( <div className="dialog-container-div-preferences"> <Loader className="preference-loader" /> </div> ) } } } export default withTranslation()(ConfigurePreferences)
the_stack
import * as mongoose from 'mongoose' import { TransactionModel, Operation, Status } from './mongooseTransactions.collection' /** Class representing a transaction. */ export default class Transaction { /** Index used for retrieve the executed transaction in the run */ private rollbackIndex = 0 /** Boolean value for enable or disable saving transaction on db */ private useDb: boolean = false /** The id of the current transaction document on database */ private transactionId = '' /** The actions to execute on mongoose collections when transaction run is called */ private operations: Operation[] = [] /** * Create a transaction. * @param useDb - The boolean parameter allow to use transaction collection on db (default false) * @param transactionId - The id of the transaction to load, load the transaction * from db if you set useDb true (default "") */ constructor(useDb = false) { this.useDb = useDb this.transactionId = '' } /** * Load transaction from transaction collection on db. * @param transactionId - The id of the transaction to load. * @trows Error - Throws error if the transaction is not found */ public async loadDbTransaction(transactionId: string) { const loadedTransaction = await TransactionModel.findOne({ _id: transactionId }) .lean() .exec() if (!loadedTransaction) return null loadedTransaction.operations.forEach(operation => { operation.model = mongoose.model(operation.modelName) }) this.operations = loadedTransaction.operations this.rollbackIndex = loadedTransaction.rollbackIndex this.transactionId = transactionId return loadedTransaction } /** * Remove transaction from transaction collection on db, * if the transactionId param is null, remove all documents in the collection. * @param transactionId - Optional. The id of the transaction to remove (default null). */ public async removeDbTransaction(transactionId = null) { try { if (transactionId === null) { await TransactionModel.deleteMany({}).exec() } else { await TransactionModel.deleteOne({ _id: transactionId }).exec() } } catch (error) { throw new Error('Fail remove transaction[s] in removeDbTransaction') } } /** * If the instance is db true, return the actual or new transaction id. * @throws Error - Throws error if the instance is not a db instance. */ public async getTransactionId() { if (this.transactionId === '') { await this.createTransaction() } return this.transactionId } /** * Get transaction operations array from transaction object or collection on db. * @param transactionId - Optional. If the transaction id is passed return the elements of the transaction id * else return the elements of current transaction (default null). */ public async getOperations(transactionId = null) { if (transactionId) { return await TransactionModel.findOne({ _id: transactionId }) .lean() .exec() } else { return this.operations } } /** * Save transaction operations array on db. * @throws Error - Throws error if the instance is not a db instance. * @return transactionId - The transaction id on database */ public async saveOperations() { if (this.transactionId === '') { await this.createTransaction() } await TransactionModel.updateOne( { _id: this.transactionId }, { operations: this.operations, rollbackIndex: this.rollbackIndex } ) return this.transactionId } /** * Clean the operations object to begin a new transaction on the same instance. */ public async clean() { this.operations = [] this.rollbackIndex = 0 this.transactionId = '' if (this.useDb) { await this.createTransaction() } } /** * Create the insert transaction and rollback states. * @param modelName - The string containing the mongoose model name. * @param data - The object containing data to insert into mongoose model. * @returns id - The id of the object to insert. */ public insert( modelName: string, data, options = {} ): mongoose.Types.ObjectId { const model = mongoose.model(modelName) if (!data._id) { data._id = new mongoose.Types.ObjectId() } const operation: Operation = { data, findId: data._id, model, modelName, oldModel: null, options, rollbackType: 'remove', status: Status.pending, type: 'insert' } this.operations.push(operation) return data._id } /** * Create the findOneAndUpdate transaction and rollback states. * @param modelName - The string containing the mongoose model name. * @param findId - The id of the object to update. * @param dataObj - The object containing data to update into mongoose model. */ public update(modelName, findId, data, options = {}) { const model = mongoose.model(modelName) const operation: Operation = { data, findId, model, modelName, oldModel: null, options, rollbackType: 'update', status: Status.pending, type: 'update' } this.operations.push(operation) return operation } /** * Create the remove transaction and rollback states. * @param modelName - The string containing the mongoose model name. * @param findObj - The object containing data to find mongoose collection. */ public remove(modelName, findId, options = {}) { const model = mongoose.model(modelName) const operation: Operation = { data: null, findId, model, modelName, oldModel: null, options, rollbackType: 'insert', status: Status.pending, type: 'remove' } this.operations.push(operation) return operation } /** * Run the operations and check errors. * @returns Array of objects - The objects returned by operations * Error - The error object containing: * data - the input data of operation * error - the error returned by the operation * executedTransactions - the number of executed operations * remainingTransactions - the number of the not executed operations */ public async run() { if (this.useDb && this.transactionId === '') { await this.createTransaction() } const final = [] return this.operations.reduce((promise, transaction, index) => { return promise.then(async result => { let operation: any = {} switch (transaction.type) { case 'insert': operation = this.insertTransaction( transaction.model, transaction.data ) break case 'update': operation = this.findByIdTransaction( transaction.model, transaction.findId ).then(findRes => { transaction.oldModel = findRes return this.updateTransaction( transaction.model, transaction.findId, transaction.data, transaction.options ) }) break case 'remove': operation = this.findByIdTransaction( transaction.model, transaction.findId ).then(findRes => { transaction.oldModel = findRes return this.removeTransaction( transaction.model, transaction.findId ) }) break } return operation .then(async query => { this.rollbackIndex = index this.updateOperationStatus(Status.success, index) if (index === this.operations.length - 1) { await this.updateDbTransaction(Status.success) } final.push(query) return final }) .catch(async err => { this.updateOperationStatus(Status.error, index) await this.updateDbTransaction(Status.error) throw err }) }) }, Promise.resolve([])) } /** * Rollback the executed operations if any error occurred. * @param stepNumber - (optional) the number of the operation to rollback - default to length of * operation successfully runned * @returns Array of objects - The objects returned by rollback operations * Error - The error object containing: * data - the input data of operation * error - the error returned by the operation * executedTransactions - the number of rollbacked operations * remainingTransactions - the number of the not rollbacked operations */ public async rollback(howmany = this.rollbackIndex + 1) { if (this.useDb && this.transactionId === '') { await this.createTransaction() } let transactionsToRollback: any = this.operations.slice( 0, this.rollbackIndex + 1 ) transactionsToRollback.reverse() if (howmany !== this.rollbackIndex + 1) { transactionsToRollback = transactionsToRollback.slice(0, howmany) } const final = [] return transactionsToRollback.reduce((promise, transaction, index) => { return promise.then(result => { let operation: any = {} switch (transaction.rollbackType) { case 'insert': operation = this.insertTransaction( transaction.model, transaction.oldModel ) break case 'update': operation = this.updateTransaction( transaction.model, transaction.findId, transaction.oldModel ) break case 'remove': operation = this.removeTransaction( transaction.model, transaction.findId ) break } return operation .then(async query => { this.rollbackIndex-- this.updateOperationStatus(Status.rollback, index) if (index === this.operations.length - 1) { await this.updateDbTransaction(Status.rollback) } final.push(query) return final }) .catch(async err => { this.updateOperationStatus(Status.errorRollback, index) await this.updateDbTransaction(Status.errorRollback) throw err }) }) }, Promise.resolve([])) } private async findByIdTransaction(model, findId) { return await model .findOne({ _id: findId }) .lean() .exec() } private async createTransaction() { if (!this.useDb) { throw new Error('You must set useDB true in the constructor') } const transaction = await TransactionModel.create({ operations: this.operations, rollbackIndex: this.rollbackIndex }) this.transactionId = transaction._id return transaction } private insertTransaction(model, data) { return new Promise((resolve, reject) => { model.create(data, (err, result) => { if (err) { return reject(this.transactionError(err, data)) } else { return resolve(result) } }) }) } private updateTransaction(model, id, data, options = { new: false }) { return new Promise((resolve, reject) => { model.findOneAndUpdate( { _id: id }, data, options, (err, result) => { if (err) { return reject(this.transactionError(err, { id, data })) } else { if (!result) { return reject( this.transactionError( new Error('Entity not found'), { id, data } ) ) } return resolve(result) } } ) }) } private removeTransaction(model, id) { return new Promise((resolve, reject) => { model.findOneAndRemove({ _id: id }, (err, data) => { if (err) { return reject(this.transactionError(err, id)) } else { if (data == null) { return reject( this.transactionError( new Error('Entity not found'), id ) ) } else { return resolve(data) } } }) }) } private transactionError(error, data) { return { data, error, executedTransactions: this.rollbackIndex + 1, remainingTransactions: this.operations.length - (this.rollbackIndex + 1) } } private updateOperationStatus(status, index) { this.operations[index].status = status } private async updateDbTransaction(status) { if (this.useDb && this.transactionId !== '') { return await TransactionModel.findByIdAndUpdate( this.transactionId, { operations: this.operations, rollbackIndex: this.rollbackIndex, status }, { new: true } ) } } }
the_stack
import { assert, expect } from "chai"; import { classModifierToString, containerTypeToString, CustomAttributeContainerType, ECClassModifier, parseClassModifier, parseCustomAttributeContainerType, parsePrimitiveType, parseRelationshipEnd, parseSchemaItemType, parseStrength, parseStrengthDirection, PrimitiveType, primitiveTypeToString, RelationshipEnd, relationshipEndToString, SchemaItemType, schemaItemTypeToString, StrengthDirection, strengthDirectionToString, strengthToString, StrengthType, } from "../ECObjects"; import { ECObjectsError, ECObjectsStatus } from "../Exception"; describe("Parsing/ToString Functions", () => { it("parsePrimitiveType", () => { expect(parsePrimitiveType("BInaRy")).equal(PrimitiveType.Binary); expect(parsePrimitiveType("boOL")).equal(PrimitiveType.Boolean); expect(parsePrimitiveType("boOLean")).equal(PrimitiveType.Boolean); expect(parsePrimitiveType("DaTEtime")).equal(PrimitiveType.DateTime); expect(parsePrimitiveType("DouBlE")).equal(PrimitiveType.Double); expect(parsePrimitiveType("beNTlEY.gEoMeTrY.CoMmoN.igeOMeTRY")).equal(PrimitiveType.IGeometry); expect(parsePrimitiveType("INt")).equal(PrimitiveType.Integer); expect(parsePrimitiveType("loNG")).equal(PrimitiveType.Long); expect(parsePrimitiveType("PoInt2d")).equal(PrimitiveType.Point2d); expect(parsePrimitiveType("POinT3d")).equal(PrimitiveType.Point3d); expect(parsePrimitiveType("STrINg")).equal(PrimitiveType.String); expect(parsePrimitiveType("invalid type")).to.be.undefined; }); it("primitiveTypeToString", () => { expect(primitiveTypeToString(PrimitiveType.Binary)).to.equal("binary"); expect(primitiveTypeToString(PrimitiveType.Boolean)).to.equal("boolean"); expect(primitiveTypeToString(PrimitiveType.DateTime)).to.equal("dateTime"); expect(primitiveTypeToString(PrimitiveType.Double)).to.equal("double"); expect(primitiveTypeToString(PrimitiveType.IGeometry)).to.equal("Bentley.Geometry.Common.IGeometry"); expect(primitiveTypeToString(PrimitiveType.Integer)).to.equal("int"); expect(primitiveTypeToString(PrimitiveType.Long)).to.equal("long"); expect(primitiveTypeToString(PrimitiveType.Point2d)).to.equal("point2d"); expect(primitiveTypeToString(PrimitiveType.Point3d)).to.equal("point3d"); expect(primitiveTypeToString(PrimitiveType.String)).to.equal("string"); expect(() => primitiveTypeToString(PrimitiveType.Uninitialized)).to.throw(ECObjectsError, "An invalid PrimitiveType has been provided."); }); it("parseClassModifier", () => { expect(parseClassModifier("Abstract")).to.equal(ECClassModifier.Abstract); expect(parseClassModifier("Sealed")).to.equal(ECClassModifier.Sealed); expect(parseClassModifier("None")).to.equal(ECClassModifier.None); expect(parseClassModifier("aBSTraCT")).to.equal(ECClassModifier.Abstract); expect(parseClassModifier("sEALEd")).to.equal(ECClassModifier.Sealed); expect(parseClassModifier("NoNE")).to.equal(ECClassModifier.None); expect(parseClassModifier("invalid modifier")).to.be.undefined; }); it("classModiferToString", () => { expect(classModifierToString(ECClassModifier.Abstract)).to.equal("Abstract"); expect(classModifierToString(ECClassModifier.Sealed)).to.equal("Sealed"); expect(classModifierToString(ECClassModifier.None)).to.equal("None"); expect(() => classModifierToString(5 as ECClassModifier)).to.throw(ECObjectsError, "An invalid ECClassModifier has been provided."); }); it("parseCustomAttributeContainerType", () => { expect(parseCustomAttributeContainerType("SChEma")).to.equal(CustomAttributeContainerType.Schema); expect(parseCustomAttributeContainerType("ENTiTycLAsS")).to.equal(CustomAttributeContainerType.EntityClass); expect(parseCustomAttributeContainerType("CUstOmAttRIBUteClASs")).to.equal(CustomAttributeContainerType.CustomAttributeClass); expect(parseCustomAttributeContainerType("StRuCTclAsS")).to.equal(CustomAttributeContainerType.StructClass); expect(parseCustomAttributeContainerType("rElATIonSHIPcLaSS")).to.equal(CustomAttributeContainerType.RelationshipClass); expect(parseCustomAttributeContainerType("anYCLaSS")).to.equal(CustomAttributeContainerType.AnyClass); expect(parseCustomAttributeContainerType("pRImiTIVeProPErtY")).to.equal(CustomAttributeContainerType.PrimitiveProperty); expect(parseCustomAttributeContainerType("StRuCTProperty")).to.equal(CustomAttributeContainerType.StructProperty); expect(parseCustomAttributeContainerType("ARRayPRoPertY")).to.equal(CustomAttributeContainerType.PrimitiveArrayProperty); expect(parseCustomAttributeContainerType("sTRUctArrayPrOPErTy")).to.equal(CustomAttributeContainerType.StructArrayProperty); expect(parseCustomAttributeContainerType("nAviGAtIoNProPerTY")).to.equal(CustomAttributeContainerType.NavigationProperty); expect(parseCustomAttributeContainerType("AnyProPErTy")).to.equal(CustomAttributeContainerType.AnyProperty); expect(parseCustomAttributeContainerType("SouRcEReLatIoNShiPCoNstRaInT")).to.equal(CustomAttributeContainerType.SourceRelationshipConstraint); expect(parseCustomAttributeContainerType("TarGETreLATIoNShIPCOnSTrAInT")).to.equal(CustomAttributeContainerType.TargetRelationshipConstraint); expect(parseCustomAttributeContainerType("AnyRELaTioNShiPCoNSTrAInt")).to.equal(CustomAttributeContainerType.AnyRelationshipConstraint); expect(parseCustomAttributeContainerType("aNy")).to.equal(CustomAttributeContainerType.Any); expect(() => parseCustomAttributeContainerType("invalid type")).to.throw(ECObjectsError, "invalid type is not a valid CustomAttributeContainerType value."); const combo = CustomAttributeContainerType.Schema | CustomAttributeContainerType.AnyClass | CustomAttributeContainerType.TargetRelationshipConstraint | CustomAttributeContainerType.StructProperty; expect(parseCustomAttributeContainerType(";Schema|AnyClass,TargetRelationshipConstraint;StructProperty")).to.equal(combo); }); it("containerTypeToString", () => { expect(containerTypeToString(CustomAttributeContainerType.Schema)).to.equal("Schema"); expect(containerTypeToString(CustomAttributeContainerType.EntityClass)).to.equal("EntityClass"); expect(containerTypeToString(CustomAttributeContainerType.CustomAttributeClass)).to.equal("CustomAttributeClass"); expect(containerTypeToString(CustomAttributeContainerType.StructClass)).to.equal("StructClass"); expect(containerTypeToString(CustomAttributeContainerType.RelationshipClass)).to.equal("RelationshipClass"); expect(containerTypeToString(CustomAttributeContainerType.AnyClass)).to.equal("AnyClass"); expect(containerTypeToString(CustomAttributeContainerType.PrimitiveProperty)).to.equal("PrimitiveProperty"); expect(containerTypeToString(CustomAttributeContainerType.StructProperty)).to.equal("StructProperty"); expect(containerTypeToString(CustomAttributeContainerType.PrimitiveArrayProperty)).to.equal("ArrayProperty"); expect(containerTypeToString(CustomAttributeContainerType.StructArrayProperty)).to.equal("StructArrayProperty"); expect(containerTypeToString(CustomAttributeContainerType.NavigationProperty)).to.equal("NavigationProperty"); expect(containerTypeToString(CustomAttributeContainerType.AnyProperty)).to.equal("AnyProperty"); expect(containerTypeToString(CustomAttributeContainerType.SourceRelationshipConstraint)).to.equal("SourceRelationshipConstraint"); expect(containerTypeToString(CustomAttributeContainerType.TargetRelationshipConstraint)).to.equal("TargetRelationshipConstraint"); expect(containerTypeToString(CustomAttributeContainerType.AnyRelationshipConstraint)).to.equal("AnyRelationshipConstraint"); expect(containerTypeToString(CustomAttributeContainerType.Any)).to.equal("Any"); const combo = CustomAttributeContainerType.Schema | CustomAttributeContainerType.AnyClass | CustomAttributeContainerType.TargetRelationshipConstraint | CustomAttributeContainerType.StructProperty; expect(containerTypeToString(combo)).to.equal("Schema, AnyClass, StructProperty, TargetRelationshipConstraint"); }); it("parseRelationshipEnd", () => { expect(parseRelationshipEnd("SoUrCE")).to.equal(RelationshipEnd.Source); expect(parseRelationshipEnd("TarGeT")).to.equal(RelationshipEnd.Target); expect(parseRelationshipEnd("inVAlId")).to.be.undefined; }); it("relationshipEndToString", () => { expect(relationshipEndToString(RelationshipEnd.Source)).to.equal("Source"); expect(relationshipEndToString(RelationshipEnd.Target)).to.equal("Target"); expect(() => relationshipEndToString(5 as RelationshipEnd)).to.throw(ECObjectsError, "An invalid RelationshipEnd has been provided."); }); it("parseStrength", () => { expect(parseStrength("ReFEReNcInG")).to.equal(StrengthType.Referencing); expect(parseStrength("HOLdIng")).to.equal(StrengthType.Holding); expect(parseStrength("EMBedDiNG")).to.equal(StrengthType.Embedding); expect(parseStrength("inVAlId")).to.be.undefined; }); it("strengthToString", () => { expect(strengthToString(StrengthType.Embedding)).to.equal("Embedding"); expect(strengthToString(StrengthType.Referencing)).to.equal("Referencing"); expect(strengthToString(StrengthType.Holding)).to.equal("Holding"); expect(() => strengthToString(5 as StrengthType)).to.throw(ECObjectsError, "An invalid Strength has been provided."); }); it("parseStrengthDirection", () => { expect(parseStrengthDirection("forward")).to.equal(StrengthDirection.Forward); expect(parseStrengthDirection("BACKWARD")).to.equal(StrengthDirection.Backward); expect(parseStrengthDirection("invalid")).to.be.undefined; }); it("strengthDirectionToString", () => { expect(strengthDirectionToString(StrengthDirection.Backward)).to.equal("Backward"); expect(strengthDirectionToString(StrengthDirection.Forward)).to.equal("Forward"); expect(() => strengthDirectionToString(5 as StrengthDirection)).to.throw(ECObjectsError, "An invalid StrengthDirection has been provided."); }); it("parseSchemaItemType", () => { expect(parseSchemaItemType("eNtItyCLaSs")).to.equal(SchemaItemType.EntityClass); expect(parseSchemaItemType("mIXIn")).to.equal(SchemaItemType.Mixin); expect(parseSchemaItemType("sTRuCTcLaSS")).to.equal(SchemaItemType.StructClass); expect(parseSchemaItemType("cuSTomATTRIbuTEClaSs")).to.equal(SchemaItemType.CustomAttributeClass); expect(parseSchemaItemType("rELAtIONsHiPClaSs")).to.equal(SchemaItemType.RelationshipClass); expect(parseSchemaItemType("enUmERAtiON")).to.equal(SchemaItemType.Enumeration); expect(parseSchemaItemType("KiNDofQuaNTiTy")).to.equal(SchemaItemType.KindOfQuantity); expect(parseSchemaItemType("prOpeRtYcAteGoRy")).to.equal(SchemaItemType.PropertyCategory); expect(parseSchemaItemType("inVAlId")).to.be.undefined; }); it("schemaItemTypeToString", () => { expect(schemaItemTypeToString(SchemaItemType.EntityClass)).to.equal("EntityClass"); expect(schemaItemTypeToString(SchemaItemType.Mixin)).to.equal("Mixin"); expect(schemaItemTypeToString(SchemaItemType.StructClass)).to.equal("StructClass"); expect(schemaItemTypeToString(SchemaItemType.CustomAttributeClass)).to.equal("CustomAttributeClass"); expect(schemaItemTypeToString(SchemaItemType.RelationshipClass)).to.equal("RelationshipClass"); expect(schemaItemTypeToString(SchemaItemType.Enumeration)).to.equal("Enumeration"); expect(schemaItemTypeToString(SchemaItemType.KindOfQuantity)).to.equal("KindOfQuantity"); expect(schemaItemTypeToString(SchemaItemType.PropertyCategory)).to.equal("PropertyCategory"); expect(() => schemaItemTypeToString(50 as SchemaItemType)).to.throw(ECObjectsError, "An invalid SchemaItemType has been provided."); }); }); describe("ECObjectsError ", () => { it("toDebugString", () => { expect(new ECObjectsError(ECObjectsStatus.DuplicateItem).toDebugString()).to.equal("ECObjectsStatus.DuplicateItem"); expect(new ECObjectsError(ECObjectsStatus.DuplicateProperty, "msg").toDebugString()).to.equal("ECObjectsStatus.DuplicateProperty: msg"); expect(new ECObjectsError(ECObjectsStatus.DuplicateSchema, "msg").toDebugString()).to.equal("ECObjectsStatus.DuplicateSchema: msg"); expect(new ECObjectsError(ECObjectsStatus.ImmutableSchema, "msg").toDebugString()).to.equal("ECObjectsStatus.ImmutableSchema: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidContainerType, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidContainerType: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidECJson, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidECJson: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidECName, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidECName: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidECVersion, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidECVersion: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidEnumValue, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidEnumValue: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidModifier, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidModifier: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidMultiplicity, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidMultiplicity: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidPrimitiveType, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidPrimitiveType: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidSchemaItemType, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidSchemaItemType: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidStrength, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidStrength: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidStrengthDirection, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidStrengthDirection: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidRelationshipEnd, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidRelationshipEnd: msg"); expect(new ECObjectsError(ECObjectsStatus.InvalidType, "msg").toDebugString()).to.equal("ECObjectsStatus.InvalidType: msg"); expect(new ECObjectsError(ECObjectsStatus.MissingSchemaUrl, "msg").toDebugString()).to.equal("ECObjectsStatus.MissingSchemaUrl: msg"); expect(new ECObjectsError(ECObjectsStatus.UnableToLocateSchema, "msg").toDebugString()).to.equal("ECObjectsStatus.UnableToLocateSchema: msg"); assert.throw(() => new ECObjectsError(-9999).toDebugString(), "Programmer Error"); }); });
the_stack
import { throttle } from 'lodash'; import { ClientReadableStream, Status, Error as GRPCError } from 'grpc-web'; import { GetEventsRequest, GetEventsResponse, EventType, EventFilter, ServiceState, ServiceLinkState, K8sNamespaceState, Flows as PBFlows, } from '~backend/proto/ui/ui_pb'; import { Notification as PBNotification } from '~backend/proto/ui/notifications_pb'; import { Flow as PBFlow, FlowFilter, EventTypeFilter, } from '~backend/proto/flow/flow_pb'; import { HubbleFlow } from '~/domain/hubble'; import { Flow } from '~/domain/flows'; import { CiliumEventTypes } from '~/domain/cilium'; import { ReservedLabel, SpecialLabel, Labels } from '~/domain/labels'; import { filterFlow, Filters, FilterEntry, FilterDirection, FilterKind, } from '~/domain/filtering'; import * as dataHelpers from '~/domain/helpers'; import { EventEmitter } from '~/utils/emitter'; import { IEventStream, EventParams, EventStreamHandlers, EventKind, } from '~/api/general/event-stream'; import { GeneralStreamEventKind } from '~/api/general/stream'; import EventCase = GetEventsResponse.EventCase; type GRPCEventStream = ClientReadableStream<GetEventsResponse>; type FlowFilters = [FlowFilter[], FlowFilter[]]; export class EventStream extends EventEmitter<EventStreamHandlers> implements IEventStream { public static readonly FlowsThrottleDelay: number = 250; private filters?: Filters; private stream: GRPCEventStream; private flowBuffer: Flow[] = []; private throttledFlowReceived: () => void = () => { return; }; // TODO: add another params to handle filters public static buildRequest( opts: EventParams, filters: Filters, ): GetEventsRequest { const req = new GetEventsRequest(); if (opts.flow) { req.addEventTypes(EventType.FLOW); } if (opts.flows) { req.addEventTypes(EventType.FLOWS); } if (opts.namespaces) { req.addEventTypes(EventType.K8S_NAMESPACE_STATE); } if (opts.services) { req.addEventTypes(EventType.SERVICE_STATE); } if (opts.serviceLinks) { req.addEventTypes(EventType.SERVICE_LINK_STATE); } if (opts.status) { req.addEventTypes(EventType.STATUS); } const [wlFlowFilters, blFlowFilters] = EventStream.buildFlowFilters( filters, ); const ffToEventFilter = (ff: FlowFilter) => { const filter = new EventFilter(); filter.setFlowFilter(ff); return filter; }; const wlFilters = wlFlowFilters.map(ffToEventFilter); const blFilters = blFlowFilters.map(ffToEventFilter); req.setWhitelistList(wlFilters); req.setBlacklistList(blFilters); return req; } public static baseWhitelistFilter(filters?: Filters): FlowFilter { const wlFilter = new FlowFilter(); const eventTypes: CiliumEventTypes[] = []; if (filters?.httpStatus) { // Filter by http status code allows only l7 event type eventTypes.push(CiliumEventTypes.L7); wlFilter.addHttpStatusCode(filters.httpStatus); } else { eventTypes.push(CiliumEventTypes.Drop, CiliumEventTypes.Trace); } eventTypes.forEach(eventTypeNumber => { const eventTypeFilter = new EventTypeFilter(); eventTypeFilter.setType(eventTypeNumber); wlFilter.addEventType(eventTypeFilter); }); if (filters?.verdict) { wlFilter.addVerdict(dataHelpers.verdictToPb(filters.verdict)); } // TODO: code for handling tcp flags should be here // NOTE: 1.9.1 gets rid of that field, wait for the next release wlFilter.addReply(false); return wlFilter; } public static buildBlacklistFlowFilters(filters?: Filters): FlowFilter[] { const blFilters: FlowFilter[] = []; // filter out reserved:unknown const [blSrcUnknownLabelFilter, blDstUnknownLabelFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcUnknownLabelFilter.addSourceLabel(ReservedLabel.Unknown); blDstUnknownLabelFilter.addDestinationLabel(ReservedLabel.Unknown); blFilters.push(blSrcUnknownLabelFilter, blDstUnknownLabelFilter); if (filters?.skipHost) { // filter out reserved:host const [blSrcHostLabelFilter, blDstHostLabelFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcHostLabelFilter.addSourceLabel(ReservedLabel.Host); blDstHostLabelFilter.addDestinationLabel(ReservedLabel.Host); blFilters.push(blSrcHostLabelFilter, blDstHostLabelFilter); } if (filters?.skipKubeDns) { // filter out kube-dns const [blSrcKubeDnsFilter, blDstKubeDnsFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcKubeDnsFilter.addSourceLabel(SpecialLabel.KubeDNS); blDstKubeDnsFilter.addDestinationLabel(SpecialLabel.KubeDNS); blDstKubeDnsFilter.addDestinationPort('53'); blFilters.push(blSrcKubeDnsFilter, blDstKubeDnsFilter); } if (filters?.skipRemoteNode) { // filter out reserved:remote-node const [blSrcRemoteNodeLabelFilter, blDstRemoteNodeLabelFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcRemoteNodeLabelFilter.addSourceLabel(ReservedLabel.RemoteNode); blDstRemoteNodeLabelFilter.addDestinationLabel(ReservedLabel.RemoteNode); blFilters.push(blSrcRemoteNodeLabelFilter, blDstRemoteNodeLabelFilter); } if (filters?.skipPrometheusApp) { // filter out prometheus app const [blSrcPrometheusFilter, blDstPrometheusFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcPrometheusFilter.addSourceLabel(SpecialLabel.PrometheusApp); blDstPrometheusFilter.addDestinationLabel(SpecialLabel.PrometheusApp); blFilters.push(blSrcPrometheusFilter, blDstPrometheusFilter); } // filter out intermediate dns requests const [blSrcLocalDnsFilter, blDstLocalDnsFilter] = [ new FlowFilter(), new FlowFilter(), ]; blSrcLocalDnsFilter.addSourceFqdn('*.cluster.local*'); blDstLocalDnsFilter.addDestinationFqdn('*.cluster.local*'); blFilters.push(blSrcLocalDnsFilter, blDstLocalDnsFilter); // filter out icmp flows const [blICMPv4Filter, blICMPv6Filter] = [ new FlowFilter(), new FlowFilter(), ]; blICMPv4Filter.addProtocol('ICMPv4'); blICMPv6Filter.addProtocol('ICMPv6'); blFilters.push(blICMPv4Filter, blICMPv6Filter); return blFilters; } public static filterEntryWhitelistFilters( filters: Filters, filter: FilterEntry, ): FlowFilter[] { const { kind, direction, query } = filter; const wlFilters: FlowFilter[] = []; const podsInNamespace = `${filters.namespace}/`; const pod = filter.podNamespace ? `${filter.podNamespace}/${filter.query}` : `${filters.namespace}/${filter.query}`; if (filter.fromRequired) { // NOTE: this makes possible to catch flows [outside of ns] -> [ns] // NOTE: but flows [ns] -> [outside of ns] are lost... const toInside = EventStream.baseWhitelistFilter(filters); toInside.addDestinationPod(podsInNamespace); // NOTE: ...this filter fixes this last case const fromInside = EventStream.baseWhitelistFilter(filters); fromInside.addSourcePod(podsInNamespace); switch (kind) { case FilterKind.Label: { toInside.addSourceLabel(query); fromInside.addSourceLabel(query); break; } case FilterKind.Ip: { toInside.addSourceIp(query); fromInside.addSourceIp(query); break; } case FilterKind.Dns: { toInside.addSourceFqdn(query); fromInside.addSourceFqdn(query); break; } case FilterKind.Identity: { toInside.addSourceIdentity(+query); fromInside.addSourceIdentity(+query); break; } case FilterKind.Pod: { toInside.addSourcePod(pod); fromInside.clearSourcePodList(); if (!pod.startsWith(podsInNamespace)) { fromInside.addDestinationPod(podsInNamespace); } fromInside.addSourcePod(pod); break; } } wlFilters.push(toInside, fromInside); } if (filter.toRequired) { // NOTE: this makes possible to catch flows [ns] -> [outside of ns] // NOTE: but flows [outside of ns] -> [ns] are lost... const fromInside = EventStream.baseWhitelistFilter(filters); fromInside.addSourcePod(podsInNamespace); // NOTE: ...this filter fixes this last case const toInside = EventStream.baseWhitelistFilter(filters); toInside.addDestinationPod(podsInNamespace); switch (kind) { case FilterKind.Label: { fromInside.addDestinationLabel(query); toInside.addDestinationLabel(query); break; } case FilterKind.Ip: { fromInside.addDestinationIp(query); toInside.addDestinationIp(query); break; } case FilterKind.Dns: { fromInside.addDestinationFqdn(query); toInside.addDestinationFqdn(query); break; } case FilterKind.Identity: { fromInside.addDestinationIdentity(+query); toInside.addDestinationIdentity(+query); break; } case FilterKind.Pod: { fromInside.addDestinationPod(pod); toInside.clearDestinationPodList(); if (!pod.startsWith(podsInNamespace)) { toInside.addSourcePod(podsInNamespace); } toInside.addDestinationPod(pod); break; } } wlFilters.push(fromInside, toInside); } return wlFilters; } // Taken from previous FlowStream class public static buildFlowFilters(filters: Filters): FlowFilters { const namespace = filters?.namespace; const wlFilters: FlowFilter[] = []; const blFilters = EventStream.buildBlacklistFlowFilters(filters); const [wlSrcFilter, wlDstFilter] = [ EventStream.baseWhitelistFilter(filters), EventStream.baseWhitelistFilter(filters), ]; if (!filters.filters?.length) { wlSrcFilter.addSourcePod(`${namespace}/`); wlDstFilter.addDestinationPod(`${namespace}/`); wlFilters.push(wlSrcFilter, wlDstFilter); return [wlFilters, blFilters]; } filters.filters.forEach(filter => { const feWlFilters = EventStream.filterEntryWhitelistFilters( filters, filter, ); wlFilters.push(...feWlFilters); }); return [wlFilters, blFilters]; } constructor(stream: GRPCEventStream, filters?: Filters) { super(); this.stream = stream; this.filters = filters; this.setupThrottledHandlers(); this.setupEventHandlers(); } private setupThrottledHandlers() { this.throttledFlowReceived = throttle(() => { this.emit(EventKind.Flows, this.flowBuffer.reverse()); this.flowBuffer = []; }, this.flowsDelay); } private setupEventHandlers() { this.stream.on(GeneralStreamEventKind.Data, (res: GetEventsResponse) => { const eventKind = res.getEventCase(); switch (eventKind) { case EventCase.EVENT_NOT_SET: return; case EventCase.FLOW: return this.onFlowReceived(res.getFlow()); case EventCase.FLOWS: return this.onFlowsReceived(res.getFlows()); case EventCase.SERVICE_STATE: return this.onServiceReceived(res.getServiceState()); case EventCase.SERVICE_LINK_STATE: return this.onLinkReceived(res.getServiceLinkState()); case EventCase.K8S_NAMESPACE_STATE: return this.onNamespaceReceived(res.getK8sNamespaceState()); case EventCase.NOTIFICATION: return this.onNotificationReceived(res.getNotification()); } }); this.stream.on(GeneralStreamEventKind.Status, (st: Status) => { this.emit(GeneralStreamEventKind.Status, st); }); this.stream.on(GeneralStreamEventKind.Error, (e: GRPCError) => { this.emit(GeneralStreamEventKind.Error, e); }); this.stream.on(GeneralStreamEventKind.End, () => { this.emit(GeneralStreamEventKind.End); }); } private onNotificationReceived(notif: PBNotification | undefined) { if (notif == null) return; const notification = dataHelpers.notifications.fromPb(notif); if (notification == null) { console.error('invalid notification pb received: ', notif); return; } this.emit(EventKind.Notification, notification); } private onFlowReceived(pbFlow: PBFlow | undefined) { if (pbFlow == null) return; const flow = dataHelpers.flowFromRelay( dataHelpers.hubbleFlowFromPb(pbFlow), ); if (this.filters == null || filterFlow(flow, this.filters)) { this.flowBuffer.push(flow); this.throttledFlowReceived(); } } private onFlowsReceived(pbFlows: PBFlows | undefined) { if (pbFlows == null) return; const pbFlowsList = pbFlows.getFlowsList(); if (pbFlowsList.length === 0) return; pbFlowsList.forEach(pbFlow => { const flow = dataHelpers.flowFromRelay( dataHelpers.hubbleFlowFromPb(pbFlow), ); if (this.filters == null || filterFlow(flow, this.filters)) { this.flowBuffer.push(flow); } }); if (this.flowBuffer.length === 0) return; this.throttledFlowReceived(); } private onServiceReceived(sstate: ServiceState | undefined) { if (sstate == null) return; const svc = sstate.getService(); const ch = sstate.getType(); if (!svc || !ch) return; const service = dataHelpers.relayServiceFromPb(svc); const change = dataHelpers.stateChangeFromPb(ch); this.emit(EventKind.Service, { service, change }); } private onLinkReceived(link: ServiceLinkState | undefined) { if (link == null) return; const linkObj = link.getServiceLink(); const ch = link.getType(); if (!linkObj || !ch) return; this.emit(EventKind.ServiceLink, { serviceLink: dataHelpers.relayServiceLinkFromPb(linkObj), change: dataHelpers.stateChangeFromPb(ch), }); } private onNamespaceReceived(ns: K8sNamespaceState | undefined) { if (ns == null) return; const nsObj = ns.getNamespace(); const change = ns.getType(); if (!nsObj || !change) return; this.emit(EventKind.Namespace, { name: nsObj.getName(), change: dataHelpers.stateChangeFromPb(change), }); } public async stop(dropEventHandlers?: boolean) { dropEventHandlers = dropEventHandlers ?? false; if (dropEventHandlers) { this.offAllEvents(); } this.stream.cancel(); } public get flowsDelay() { return EventStream.FlowsThrottleDelay; } }
the_stack
describe('Liquid', () => { const baseModule = Cypress.env("BASE_MODULE"); const basePath = ''; beforeEach(() => { cy.intercept('/liquid/api/block/**').as('block'); cy.intercept('/liquid/api/blocks/').as('blocks'); cy.intercept('/liquid/api/tx/**/outspends').as('outspends'); cy.intercept('/liquid/api/block/**/txs/**').as('block-txs'); cy.intercept('/resources/pools.json').as('pools'); Cypress.Commands.add('waitForBlockData', () => { cy.wait('@socket'); cy.wait('@block'); cy.wait('@outspends'); }); }); if (baseModule === 'liquid') { it('check first mempool block after skeleton loads', () => { cy.visit(`${basePath}`); cy.waitForSkeletonGone(); cy.get('#mempool-block-0 > .blockLink').should('exist'); }); it('loads the dashboard', () => { cy.visit(`${basePath}`); cy.waitForSkeletonGone(); }); it('loads the blocks page', () => { cy.visit(`${basePath}`); cy.get('#btn-blocks').click().then(() => { cy.wait(1000); }); cy.waitForSkeletonGone(); }); it('loads a specific block page', () => { cy.visit(`${basePath}/block/7e1369a23a5ab861e7bdede2aadcccae4ea873ffd9caf11c7c5541eb5bcdff54`); cy.waitForSkeletonGone(); }); it('loads the graphs page', () => { cy.visit(`${basePath}`); cy.waitForSkeletonGone(); cy.get('#btn-graphs').click().then(() => { cy.wait(1000); }); }); it('loads the tv page - desktop', () => { cy.visit(`${basePath}/tv`); cy.waitForSkeletonGone(); }); it('loads the graphs page - mobile', () => { cy.visit(`${basePath}`) cy.waitForSkeletonGone(); cy.get('#btn-graphs').click().then(() => { cy.viewport('iphone-6'); cy.wait(1000); cy.get('.tv-only').should('not.exist'); }); }); it('renders unconfidential addresses correctly on mobile', () => { cy.viewport('iphone-6'); cy.visit(`${basePath}/address/ex1qqmmjdwrlg59c8q4l75sj6wedjx57tj5grt8pat`); cy.waitForSkeletonGone(); //TODO: Add proper IDs for these selectors const firstRowSelector = '.container-xl > :nth-child(3) > div > :nth-child(1) > .table > tbody'; const thirdRowSelector = '.container-xl > :nth-child(3) > div > :nth-child(3)'; cy.get(firstRowSelector).invoke('css', 'width').then(firstRowWidth => { cy.get(thirdRowSelector).invoke('css', 'width').then(thirdRowWidth => { expect(parseInt(firstRowWidth)).to.be.lessThan(parseInt(thirdRowWidth)); }); }); }); describe('peg in/peg out', () => { it('loads peg in addresses', () => { cy.visit(`${basePath}/tx/fe764f7bedfc2a37b29d9c8aef67d64a57d253a6b11c5a55555cfd5826483a58`); cy.waitForSkeletonGone(); //TODO: Change to an element id so we don't assert on a string cy.get('.table-tx-vin').should('contain', 'Peg-in'); cy.get('.table-tx-vin a').click().then(() => { cy.waitForSkeletonGone(); if (baseModule === 'liquid') { cy.url().should('eq', 'https://mempool.space/tx/f148c0d854db4174ea420655235f910543f0ec3680566dcfdf84fb0a1697b592'); } else { //TODO: Use an environment variable to get the hostname cy.url().should('eq', 'http://localhost:4200/tx/f148c0d854db4174ea420655235f910543f0ec3680566dcfdf84fb0a1697b592'); } }); }); it('loads peg out addresses', () => { cy.visit(`${basePath}/tx/ecf6eba04ffb3946faa172343c87162df76f1a57b07b0d6dc6ad956b13376dc8`); cy.waitForSkeletonGone(); cy.get('.table-tx-vout a').first().click().then(() => { cy.waitForSkeletonGone(); if (baseModule === 'liquid') { cy.url().should('eq', 'https://mempool.space/address/1BxoGcMg14oaH3CwHD2hF4gU9VcfgX5yoR'); } else { //TODO: Use an environment variable to get the hostname cy.url().should('eq', 'http://localhost:4200/address/1BxoGcMg14oaH3CwHD2hF4gU9VcfgX5yoR'); } //TODO: Add a custom class so we don't assert on a string cy.get('.badge').should('contain', 'Liquid Peg Out'); }); }); }); describe('assets', () => { it('shows the assets screen', () => { cy.visit(`${basePath}/assets`); cy.waitForSkeletonGone(); cy.get('.featuredBox .card').should('have.length.at.least', 5); }); it('allows searching assets', () => { cy.visit(`${basePath}/assets`); cy.waitForSkeletonGone(); cy.get('.container-xl input').click().type('Liquid Bitcoin').then(() => { cy.get('ngb-typeahead-window', { timeout: 30000 }).should('have.length', 1); }); }); it('shows a specific asset ID', () => { cy.visit(`${basePath}/assets`); cy.waitForSkeletonGone(); cy.get('.container-xl input').click().type('Liquid AUD').then(() => { cy.get('ngb-typeahead-window:nth-of-type(1) button', { timeout: 30000 }).click(); }); }); }); describe('unblinded TX', () => { it('should not show an unblinding error message for regular txs', () => { cy.visit(`${basePath}/tx/82a479043ec3841e0d3f829afc8df4f0e2bbd675a13f013ea611b2fde0027d45`); cy.waitForSkeletonGone(); cy.get('.error-unblinded').should('not.exist'); }); it('show unblinded TX', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=100000,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,0ab9f70650f16b1db8dfada05237f7d0d65191c3a13183da8a2ddddfbde9a2ad,fd98b2edc5530d76acd553f206a431f4c1fab27e10e290ad719582af878e98fc,2364760,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,90c7a43b15b905bca045ca42a01271cfe71d2efe3133f4197792c24505cb32ed,12eb5959d9293b8842e7dd8bc9aa9639fd3fd031c5de3ba911adeca94eb57a3a`); cy.waitForSkeletonGone(); cy.get('.table-tx-vin tr:nth-child(1) .amount').should('contain.text', '0.02465000 L-BTC'); cy.get('.table-tx-vin tr').should('have.class', 'assetBox'); cy.get('.table-tx-vout tr:nth-child(1) .amount').should('contain.text', '0.00100000 L-BTC'); cy.get('.table-tx-vout tr:nth-child(2) .amount').should('contain.text', '0.02364760 L-BTC'); cy.get('.table-tx-vout tr').should('have.class', 'assetBox'); }); it('show empty unblinded TX', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=`); cy.waitForSkeletonGone(); cy.get('.table-tx-vin tr:nth-child(1)').should('have.class', ''); cy.get('.table-tx-vin tr:nth-child(1) .amount').should('contain.text', 'Confidential'); cy.get('.table-tx-vout tr:nth-child(1)').should('have.class', ''); cy.get('.table-tx-vout tr:nth-child(2)').should('have.class', ''); cy.get('.table-tx-vout tr:nth-child(1) .amount').should('contain.text', 'Confidential'); cy.get('.table-tx-vout tr:nth-child(2) .amount').should('contain.text', 'Confidential'); }); it('show invalid unblinded TX hex', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=123`); cy.waitForSkeletonGone(); cy.get('.table-tx-vin tr').should('have.class', ''); cy.get('.table-tx-vout tr').should('have.class', ''); cy.get('.error-unblinded').contains('Error: Invalid blinding data (invalid hex)'); }); it('show first unblinded vout', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=100000,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,0ab9f70650f16b1db8dfada05237f7d0d65191c3a13183da8a2ddddfbde9a2ad,fd98b2edc5530d76acd553f206a431f4c1fab27e10e290ad719582af878e98fc`); cy.waitForSkeletonGone(); cy.get('.table-tx-vout tr:nth-child(1)').should('have.class', 'assetBox'); cy.get('.table-tx-vout tr:nth-child(1) .amount').should('contain.text', '0.00100000 L-BTC'); }); it('show second unblinded vout', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=2364760,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,90c7a43b15b905bca045ca42a01271cfe71d2efe3133f4197792c24505cb32ed,12eb5959d9293b8842e7dd8bc9aa9639fd3fd031c5de3ba911adeca94eb57a3a`); cy.get('.table-tx-vout tr:nth-child(2').should('have.class', 'assetBox'); cy.get('.table-tx-vout tr:nth-child(2) .amount').should('contain.text', '0.02364760 L-BTC'); }); it('show invalid error unblinded TX', () => { cy.visit(`${basePath}/tx/f2f41c0850e8e7e3f1af233161fd596662e67c11ef10ed15943884186fbb7f46#blinded=100000,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,0ab9f70650f16b1db8dfada05237f7d0d65191c3a13183da8a2ddddfbde9a2ad,fd98b2edc5530d76acd553f206a431f4c1fab27e10e290ad719582af878e98fc,2364760,6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d,90c7a43b15b905bca045ca42a01271cfe71d2efe3133f4197792c24505cb32ed,12eb5959d9293b8842e7dd8bc9aa9639fd3fd031c5de3ba911adeca94eb57a3c`); cy.waitForSkeletonGone(); cy.get('.table-tx-vout tr').should('have.class', 'assetBox'); cy.get('.error-unblinded').contains('Error: Invalid blinding data.'); }); it('shows asset peg in/out and burn transactions', () => { cy.visit(`${basePath}/assets/asset/6f0279e9ed041c3d710a9f57d0c02928416460c4b722ae3457a11eec381c526d`); cy.waitForSkeletonGone(); cy.get('.table-tx-vout tr').not('.assetBox'); cy.get('.table-tx-vin tr').not('.assetBox'); }); it('prevents regressing issue #644', () => { cy.visit(`${basePath}/tx/393b890966f305e7c440fcfb12a13f51a7a9011cc59ff5f14f6f93214261bd82`); cy.waitForSkeletonGone(); }); }); } else { it.skip(`Tests cannot be run on the selected BASE_MODULE ${baseModule}`); } });
the_stack
import { Rect, equalRect } from "../../frontend/src/board/geometry" import { AppEvent, Board, Id, Item, getItem, findItem, findItemIdsRecursively, isBoardHistoryEntry, PersistableBoardItemEvent, isTextItem, TextItem, Connection, isContainedBy, MoveItem, ConnectionEndPoint, Point, isContainer, } from "./domain" import _ from "lodash" import { arrayToObject } from "./migration" import { maybeChangeContainer } from "../../frontend/src/board/item-setcontainer" export function boardReducer( board: Board, event: PersistableBoardItemEvent, ): [Board, PersistableBoardItemEvent | null] { if (isBoardHistoryEntry(event) && event.serial) { const firstSerial = event.firstSerial ? event.firstSerial : event.serial if (firstSerial !== board.serial + 1) { console.warn(`Serial skip ${board.serial} -> ${event.serial}`) } board = { ...board, serial: event.serial } } switch (event.action) { case "connection.add": { const { connection } = event validateConnection(board, connection) if (board.connections.some((c) => c.id === connection.id)) { throw Error(`Connection ${connection.id} already exists on board ${board.id}`) } return [ { ...board, connections: board.connections.concat(connection) }, { action: "connection.delete", boardId: event.boardId, connectionId: event.connection.id }, ] } case "connection.modify": { const { connection } = event validateConnection(board, connection) const existingConnection = board.connections.find((c) => c.id === connection.id) if (!existingConnection) { throw Error(`Trying to modify nonexisting connection ${connection.id} on board ${board.id}`) } return [ { ...board, connections: board.connections.map((c) => (c === existingConnection ? connection : c)) }, { action: "connection.modify", boardId: event.boardId, connection: existingConnection }, ] } case "connection.delete": { const { connectionId } = event const existingConnection = board.connections.find((c) => c.id === connectionId) if (!existingConnection) { throw Error(`Trying to delete nonexisting connection ${connectionId} on board ${board.id}`) } return [ { ...board, connections: board.connections.filter((c) => c !== existingConnection) }, { action: "connection.add", boardId: event.boardId, connection: existingConnection }, ] } case "board.rename": return [{ ...board, name: event.name }, null] case "board.setAccessPolicy": return [{ ...board, accessPolicy: event.accessPolicy }, null] case "item.bootstrap": //if (board.items.length > 0) throw Error("Trying to bootstrap non-empty board") return [{ ...board, items: event.items, connections: event.connections }, null] case "item.add": if (event.items.some((a) => board.items[a.id])) { throw new Error("Adding duplicate item " + JSON.stringify(event.items)) } const itemsToAdd = event.items.reduce((acc: Record<string, Item>, item) => { if ( item.containerId && !findItem(board)(item.containerId) && !findItem(arrayToObject("id", event.items))(item.containerId) ) { // Add item but don't try to assign to a non-existing container acc[item.id] = { ...item, containerId: undefined } return acc } acc[item.id] = item return acc }, {}) const boardWithAddedItems = { ...board, items: { ...board.items, ...itemsToAdd } } const connectionsToAdd = event.connections || [] connectionsToAdd.forEach((connection) => { validateConnection(boardWithAddedItems, connection) if (board.connections.some((c) => c.id === connection.id)) { throw Error(`Connection ${connection.id} already exists on board ${board.id}`) } }) return [ { ...boardWithAddedItems, connections: [...board.connections, ...connectionsToAdd] }, { action: "item.delete", boardId: board.id, itemIds: event.items.map((i) => i.id) }, ] case "item.font.increase": return [ { ...board, items: applyFontSize(board.items, 1.1, event.itemIds), }, { ...event, action: "item.font.decrease", }, ] case "item.font.decrease": return [ { ...board, items: applyFontSize(board.items, 1 / 1.1, event.itemIds), }, { ...event, action: "item.font.increase", }, ] case "item.update": { return [ { ...board, items: updateItems(board.items, event.items), }, { action: "item.update", boardId: board.id, items: event.items.map((item) => getItem(board)(item.id)), }, ] } case "item.move": return [ moveItems(board, event), { action: "item.move", boardId: board.id, items: event.items.map((i) => { const item = getItem(board)(i.id) return { id: i.id, x: item.x, y: item.y, containerId: item.containerId } }), }, ] case "item.delete": { const idsToDelete = findItemIdsRecursively(event.itemIds, board) const [connectionsToKeep, connectionsDeleted] = _.partition( board.connections, (c) => (typeof c.from !== "string" || !idsToDelete.has(c.from)) && (typeof c.to !== "string" || !idsToDelete.has(c.to)), ) const updatedItems = { ...board.items } idsToDelete.forEach((id) => { delete updatedItems[id] }) return [ { ...board, connections: connectionsToKeep, items: updatedItems, }, { action: "item.add", boardId: board.id, items: Array.from(idsToDelete).map(getItem(board)), connections: connectionsDeleted, }, ] } case "item.front": let maxZ = 0 let maxZCount = 0 const itemsList = Object.values(board.items) for (let i of itemsList) { if (i.z > maxZ) { maxZCount = 1 maxZ = i.z } else if (i.z === maxZ) { maxZCount++ } } const isFine = (item: Item) => { return !event.itemIds.includes(item.id) || item.z === maxZ } if (maxZCount === event.itemIds.length && itemsList.every(isFine)) { // Requested items already on front return [board, null] } const updated = event.itemIds.reduce((acc: Record<string, Item>, id) => { const item = board.items[id] if (!item) { console.warn(`Warning: trying to "item.front" nonexisting item ${id} on board ${board.id}`) return acc } const u = item.type !== "container" ? { ...item, z: maxZ + 1 } : item acc[u.id] = u return acc }, {}) return [ { ...board, items: { ...board.items, ...updated, }, }, null, ] // TODO: return item.back default: console.warn("Unknown event", event) return [board, null] } } function validateConnection(board: Board, connection: Connection) { validateEndPoint(board, connection, "from") validateEndPoint(board, connection, "to") } function validateEndPoint(board: Board, connection: Connection, key: "to" | "from") { const endPoint = connection[key] if (typeof endPoint === "string") { const toItem = board.items[endPoint] if (!toItem) { throw Error(`Connection ${connection.id} refers to nonexisting item ${endPoint}`) } } } function applyFontSize(items: Record<string, Item>, factor: number, itemIds: Id[]) { const updated = itemIds.reduce((acc: Record<string, Item>, id) => { const u = items[id] && isTextItem(items[id]) ? (items[id] as TextItem) : null if (u) { acc[u.id] = { ...u, fontSize: ((u as TextItem).fontSize || 1) * factor, } } return acc }, {}) return { ...items, ...updated, } } function updateItems(current: Record<Id, Item>, updateList: Item[]): Record<Id, Item> { const updated = arrayToObject("id", updateList) const result = { ...current, ...updated } updateList.filter(isContainer).forEach((container) => { const previous = current[container.id] if (previous && !equalRect(previous, container)) { // Container shape changed -> check items Object.values(current) .filter( (i) => i.containerId === container.id || // Check all previously contained items containedBy(i, container), // Check all items inside the new bounds ) .forEach((item) => { const newContainer = maybeChangeContainer(item, result) if (newContainer?.id !== item.containerId) { result[item.id] = { ...item, containerId: newContainer ? newContainer.id : undefined } } }) } }) return result } type Move = { xDiff: number; yDiff: number; containerChanged: boolean; containerId: Id | undefined } function moveItems(board: Board, event: MoveItem) { const moves: Record<Id, Move> = {} const itemsOnBoard = board.items for (let mainItemMove of event.items) { const { id, x, y, containerId } = mainItemMove const mainItem = itemsOnBoard[id] if (mainItem === undefined) { console.warn("Moving unknown item", id) continue } const xDiff = x - mainItem.x const yDiff = y - mainItem.y for (let movedItem of Object.values(itemsOnBoard)) { const movedId = movedItem.id if (movedId === id || isContainedBy(itemsOnBoard, mainItem)(movedItem)) { const move = { xDiff, yDiff, containerChanged: movedId === id, containerId } moves[movedId] = move } } } const connectionMoves: Record<Id, Move> = {} for (let connection of board.connections) { const move = findConnectionMove(connection, moves) if (move) { connectionMoves[connection.id] = move } } let connections = board.connections.map((connection) => { const move = connectionMoves[connection.id] if (!move) return connection return { ...connection, from: moveEndPoint(connection.from, move), to: moveEndPoint(connection.to, move), controlPoints: connection.controlPoints.map((cp) => moveEndPoint(cp, move)), } as Connection }) const updatedItems = Object.entries(moves).reduce( (items, [id, move]) => { const item = items[id] const updated = { ...item, x: item.x + move.xDiff, y: item.y + move.yDiff } if (move.containerChanged) updated.containerId = move.containerId items[id] = updated return items }, { ...board.items }, ) return { ...board, items: updatedItems, connections, } } function findConnectionMove(connection: Connection, moves: Record<Id, Move>) { const endPoints = [connection.to, connection.from] let move: Move | null = null for (let endPoint of endPoints) { if (typeof endPoint === "string") { if (moves[endPoint]) { move = moves[endPoint] } else { // linked to item not being moved -> don't move return null } } } return move } function moveEndPoint(endPoint: ConnectionEndPoint, move: Move) { if (typeof endPoint === "string") { return endPoint // points to an item } const x = endPoint.x + move.xDiff const y = endPoint.y + move.yDiff return { ...endPoint, x, y } } function containedBy(a: Point, b: Rect) { return a.x > b.x && a.y > b.y && a.x < b.x + b.width && a.y < b.y + b.height }
the_stack
export declare class TerminatablePromise<T> extends Promise<T> { terminate(value: T): void } export declare interface ChainableFunction { (...params: any[]) : TerminatablePromise<any> join(promise: TerminatablePromise<unknown>) : TerminatablePromise<unknown> } export declare function forEach(collection: any, fn: Function): Generator<any, any, any>; /** * @returns array of elements matching the filter */ export declare function filter(collection: any, fn: Function): Generator<any, any, any>; /** * @returns The result of processing the reduction function on all * of the items in the array */ export declare function reduce(collection: any, fn: Function, initialValue?: any): Generator<any, any, any>; /** * Concatenate two arrays into a new array * @returns the concatenated arrays */ export declare function concat(array1: any[], array2: any[]): Generator<any, any[], any>; /** * Appends one array to another * @param array1 - the destination * @param array2 - the source * @returns returns <code>array1</code> */ export declare function append(array1: any[], array2: any[]): Generator<any, any[], any>; /** * @returns new array of mapped values */ export declare function map(collection: any, fn: Function): Generator<any, any[], any>; /** * @returns the first matching value in the array or null */ export declare function find(collection: any, fn: Function): Generator<any, any, any>; /** * @returns Index of matching element or -1 */ export declare function findIndex(array: any[], fn: Function): Generator<any, number, any>; /** * @returns true if at least one item matched the filter */ export declare function some(array: any[], fn: Function): boolean; /** * @returns true if all of the array items matched the filter */ export declare function every(array: any[], fn: Function): boolean; /** * Asynchronously stringify data into JSON * @param data - Object to store * @returns a Promise for the JSON representation of <code>data</code> */ export declare function stringifyAsync(data: any): TerminatablePromise<String>; /** * Asynchronously parse JSON into an object * @param json - the JSON to be parsed * @returns a Promise for the parsed JSON */ export declare function parseAsync(json: string): TerminatablePromise<any>; /** * Creates a generator for an array with the unique values from the * input array, the routine is supplied with a * function that determines on what the array should * be made unique. * @param {Array} array * @param {Map} [fn] - the function to determine uniqueness, if * omitted then the item itself is used * @returns {Generator<*, [], *>} */ export declare function uniqueBy(array: [], fn: Function): Generator<any, [], any> /** * Creates a generator for an object composed of keys generated from the results * of running each element of collection thru then supplied function. * The corresponding value of each key is an collection of the elements responsible * for generating the key. * * @param {Array|Object} collection * @param {Map} fn * @returns {Generator<*, {}, *>} a generator for the new object */ export declare function groupBy(collection: [] | {}, fn: Function): Generator<any, {}, any> /** * Creates an object composed of keys generated from the results * of running each element of collection thru then supplied function. * The corresponding value of each key is the last element responsible * for generating the key. * * @param {Array|Object} collection * @param {Map} fn * @returns {Generator<*, {}, *>} a generator for the new object */ export declare function keyBy(collection: []|{}, fn: Function): Generator<any, {}, any> /** * Returns a generator for the last index of an item in an array * @param array - the array to scan * @param value - the value to search for * @returns {Generator<any, number, any>} a generator that returns the last index of the item or -1 */ export declare function lastIndexOf(array: [], value: any): Generator<any, number, any> /** * Returns a generator for an index of an item in an array * @param array - the array to scan * @param value - the value to search for * @returns {Generator<any, number, any>} a generator that returns the index of the item or -1 */ export declare function indexOf(array: [], value: any): Generator<any, number, any> /** * Returns a generator returning true if an array includes a value * @param array * @param value * @returns {Generator<*, boolean, *>} */ export declare function includes(array: [], value: any): Generator<any, boolean, any>; /** * Creates a promise for an array with the unique values from the * input array, the routine is supplied with a * function that determines on what the array should * be made unique. * @param {Array} array * @param {Map} [fn] - the function to determine uniqueness, if * omitted then the item itself is used * @returns {Promise<[]>} */ export declare function uniqueByAsync(array: [], fn: Function): TerminatablePromise<[]> /** * Creates a promise for an object composed of keys generated from the results * of running each element of collection thru then supplied function. * The corresponding value of each key is an collection of the elements responsible * for generating the key. * * @param {Array|Object} collection * @param {Map} fn * @returns {Promise<{}>} a generator for the new object */ export declare function groupByAsync(collection: [] | {}, fn: Function): TerminatablePromise<{}> /** * Creates promise for an object composed of keys generated from the results * of running each element of collection thru then supplied function. * The corresponding value of each key is the last element responsible * for generating the key. * * @param {Array|Object} collection * @param {Map} fn * @returns {Promise<{}>} a generator for the new object */ export declare function keyByAsync(collection: [] | {}, fn: Function): TerminatablePromise<{}> /** * Returns a promise for the last index of an item in an array * @param array - the array to scan * @param value - the value to search for * @returns {Promise<Number>} a generator that returns the last index of the item or -1 */ export declare function lastIndexOf(array: [], value: any): TerminatablePromise<Number> /** * Returns a promise for an index of an item in an array * @param array - the array to scan * @param value - the value to search for * @returns {Promise<Number>} a generator that returns the index of the item or -1 */ export declare function indexOf(array: [], value: any): TerminatablePromise<number> /** * Returns a promise for true if an array includes a value * @param array * @param value * @returns {Promise<Boolean>} */ export declare function includes(array: [], value: any): TerminatablePromise<Boolean>; /** * Sort an array (in place) by a sorting function * @example * async function process(data) { * return await sortAsync(data, v=>v.someProperty) * } * @param array - The array to sort * @param sort - The method to sort the array * @returns a promise for the sorted array * @example * * await sortAsync(myArray, v=>v.lastName) */ export declare function sortAsync(array: any[], sort: Function): TerminatablePromise<any[]>; /** * Finds an item in an array asynchronously * @returns promise for the item found or null if no match * @example * * const firstToProcess = await findAsync(jobs, job=>job.done === false) */ export declare function findAsync(collection: []|{}, filter: Function): TerminatablePromise<any | null>; /** * Finds an item index in an array asynchronously * @returns promise for the index of the first item to pass the filter or -1 * @example * let firstItem = await findIndexAsync(jobs, job=>!!job.error) */ export declare function findIndexAsync(collection: []|{}, filter: Function): TerminatablePromise<Number>; /** * Functions the contents of an array asynchronously * @returns promise for the mapped array * @example * * const updated = await mapAsync(myItems, item=>({name: item.name, value: item.quantity * item.cost})) */ export declare function mapAsync(collection: []|{}, mapFn: Function): TerminatablePromise<[]|{}>; /** * Functions an array asynchronously * @returns promise for the filtered array * @example * const errorJobs = await filterAsync( */ export declare function filterAsync(collection: []|{}, filter: Function): TerminatablePromise<[]|{}>; /** * Performs a reduce on an array asynchronously * @returns a promise for the reduced value */ export declare function reduceAsync(array: any[], reduceFn: Function, initialValue: any): TerminatablePromise<any>; /** * Appends one array to another asynchronously * @returns a promise for destination after appending */ export declare function appendAsync(destination: any[], source: any[]): TerminatablePromise<any[]>; /** * Concatenates 2 arrays into a new array * @returns a promise for combined array */ export declare function concatAsync(array1: any[], array2: any[]): TerminatablePromise<any[]>; /** * Asynchronously loop over the elements of an array * @returns promise for the end of the operation */ export declare function forEachAsync(collection: []|{}, fn: Function): TerminatablePromise<void>; /** * Asynchronously apply an array <code>some</code> operation * returning a promise for <code>true</code> if at least * one item matches * @returns promise for true if at least one item matched the filter */ export declare function someAsync(array: any[], fn: Function): TerminatablePromise<Boolean>; /** * Asynchronously check if every element in an array matches * a predicate * @returns promise for true if all items matched the filter */ export declare function everyAsync(array: any[], fn: Function): TerminatablePromise<Boolean>; /** * Asynchronously compress a string to a base64 format * @param source - the data to compress * @returns a promise for the base64 compressed data */ export declare function compressToBase64Async(source: string): TerminatablePromise<String>; /** * Asynchronously compress a string to a utf16 string * @param source - the data to compress * @returns a promise for the utf16 compressed data */ export declare function compressToUTF16Async(source: string): TerminatablePromise<String>; /** * Asynchronously compress a string to a Uint8Array * @param source - the data to compress * @returns a promise for the Uint8Array of compressed data */ export declare function compressToUint8ArrayAsync(source: string): TerminatablePromise<Uint8Array>; /** * Asynchronously compress a string to a URI safe version * @param source - the data to compress * @returns a promise for the string of compressed data */ export declare function compressToEncodedURIComponentAsync(source: string): TerminatablePromise<String>; /** * Asynchronously compress a string of data with lz-string * @param source - the data to compress * @returns a promise for the compressed data */ export declare function compressAsync(source: string): TerminatablePromise<String>; /** * Asynchronously apply lz-string base64 remapping of a string to utf16 * @param source - the data to compress * @returns a promise for the compressed data */ export declare function base64CompressToUTF16Async(source: string): TerminatablePromise<String>; /** * Asynchronously apply lz-string base64 remapping of a string * @param source - the data to compress * @returns a promise for the compressed data */ export declare function base64CompressAsync(source: string): TerminatablePromise<String>; /** * Asynchronously compress a string to a base64 format * @param source - the data to compress * @returns a promise for the base64 compressed data */ export declare function compressToBase64Async(source: string): TerminatablePromise<String>; /** * Asynchronously decompress a string from a utf16 source * @param compressedData - the data to decompress * @returns a promise for the uncompressed data */ export declare function decompressFromUTF16Async(compressedData: string): TerminatablePromise<String>; /** * Asynchronously decompress a string from a utf16 source * @param compressedData - the data to decompress * @returns a promise for the uncompressed data */ export declare function decompressFromUint8ArrayAsync(compressedData: string): TerminatablePromise<String>; /** * Asynchronously decompress a string from a URL safe URI Component encoded source * @param compressedData - the data to decompress * @returns a promise for the uncompressed data */ export declare function decompressFromEncodedURIComponentAsync(compressedData: string): TerminatablePromise<String>; /** * Asynchronously decompress a string from a string source * @param compressedData - the data to decompress * @returns a promise for the uncompressed data */ export declare function decompressAsync(compressedData: string): TerminatablePromise<String>; /** * Asynchronously unmap base64 encoded data to a utf16 destination * @param base64Data - the data to decompress * @returns a promise for the uncompressed data */ export declare function base64decompressFromUTF16Async(base64Data: string): TerminatablePromise<String>; /** * Asynchronously unmap base64 encoded data * @param base64Data - the data to decompress * @returns a promise for the uncompressed data */ export declare function base64Decompress(base64Data: string): TerminatablePromise<String>; /** * <p> * Starts an idle time coroutine and returns a promise for its completion and * any value it might return. * </p> * <p> * You may pass a coroutine function or the result of calling such a function. The * latter helps when you must provide parameters to the coroutine. * </p> * @example * async function process() { * let answer = await run(function * () { * let total = 0 * for(let i=1; i < 10000000; i++) { * total += i * if((i % 100) === 0) yield * } * return total * }) * ... * } * * // Or * * async function process(param) { * let answer = await run(someCoroutine(param)) * } * @param coroutine - the routine to run or an iterator for an already started coroutine * @param [loopWhileMsRemains = 1 (ms)] - if less than the specified number of milliseconds remain the coroutine will continue in the next idle frame * @param [timeout = 160 (ms)] - the number of milliseconds before the coroutine will run even if the system is not idle * @returns the result of the coroutine */ export declare function run(coroutine: Function|Generator, loopWhileMsRemains?: number, timeout?: number): TerminatablePromise<any>; /** * Start an animation coroutine, the animation will continue until * you return and will be broken up between frames by using a * <code>yield</code>. * @param coroutine - The animation to run * @param [params] - Parameters to be passed to the animation function * @returns a value that will be returned to the caller * when the animation is complete. */ export declare function update(coroutine: Function|Generator, ...params: any[]): TerminatablePromise<any>; /** * Starts an idle time coroutine using an async generator - this is NOT normally required * and the performance of such routines is slower than ordinary coroutines. This is included * in case of an edge case requirement. * @param coroutine - the routine to run * @param [loopWhileMsRemains = 1 (ms)] - if less than the specified number of milliseconds remain the coroutine will continue in the next idle frame * @param [timeout = 160 (ms)] - the number of milliseconds before the coroutine will run even if the system is not idle * @returns the result of the coroutine */ export declare function runAsync(coroutine: Function|Generator, loopWhileMsRemains?: number, timeout?: number): TerminatablePromise<any>; /** * Wraps a normal function into a generator function * that <code>yield</code>s on a regular basis * @param fn - the function to be wrapped * @param [frequency = 8] - the number of times the function should be called * before performing a <code>yield</code> * @returns The wrapped yielding * version of the function passed */ export declare function yielding(fn: (...params: any[]) => any, frequency?: number): (...params: any[]) => Generator; /** * Returns a function that will execute the passed * Coroutine and return a Promise for its result. The * returned function will take any number of parameters * and pass them on to the coroutine. * @param coroutine - The coroutine to run * @returns a function that can be called to execute the coroutine * and return its result on completion */ export declare function wrapAsPromise(coroutine: ()=>Generator): Function; export declare function pipe(...functions: Array<Function>|Array<Array<Function>>) : any export declare function tap(fn: Function) : Function; export declare function branch(fn: Function) : Function; export declare function repeat(fn: Function, times: Number) : Function; export declare function call(fn: Function, ...parameters: any[]) : Function /** * Call with true to use the polyfilled version of * the idle callback, can be more stable in certain * circumstances * @param {Boolean} internal */ export declare function useInternalEngine(internal: Boolean) : void; /** * Creates a singleton executor of a generator function. * If the function is currently running it will be * terminated with the defaultValue and a new one started * @param {Function} fn - the generator function to wrap * @param {any} [defaultValue] - a value to be returned if the current execution is * terminated by a new one starting * @returns {ChainableFunction} a function to execute the * generator and return the value */ export declare function singleton(fn: Function, defaultValue?: any) : ChainableFunction
the_stack
import React, { useState, useMemo, useEffect, useRef, useCallback, } from 'react'; import { useLocation, useParams } from 'react-router-dom'; import some from 'lodash/some'; import uniq from 'lodash/uniq'; import max from 'lodash/max'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import { useTheme } from '@material-ui/core/styles'; import { ParentSize } from '@vx/responsive'; import ShareButtonGroup from 'components/ShareButtons'; import ExploreChart from './ExploreChart'; import Legend from './Legend'; import { ExploreMetric, Series } from './interfaces'; import LocationSelector from './LocationSelector'; import { getMetricLabels, getMetricByChartId, getImageFilename, getExportImageUrl, getChartUrl, getSocialQuote, getLocationNames, getExploreAutocompleteLocations, getChartSeries, getMetricName, getSeriesLabel, EXPLORE_CHART_IDS, Period, periodMap, getAllPeriodLabels, ORIGINAL_EXPLORE_METRICS, getMetricDataMeasure, getDateRange, getYFormat, getYAxisDecimalPlaces, getXTickTimeUnitForPeriod, getMaxYFromDefinition, } from './utils'; import * as Styles from './Explore.style'; import { SharedComponent, storeSharedComponentParams, useSharedComponentParams, } from 'common/sharing'; import { ScreenshotReady } from 'components/Screenshot'; import { EventCategory, EventAction, trackEvent } from 'components/Analytics'; import regions, { Region, useRegionFromParams } from 'common/regions'; import Dropdown from 'components/Explore/Dropdown/Dropdown'; import { getLocationLabel } from 'components/AutocompleteRegions'; import { ShareBlock } from 'components/Footer/Footer.style'; import { EmptyPanel } from 'components/Charts/Charts.style'; import { useChartHeightForBreakpoint } from 'common/hooks'; const MARGIN_SINGLE_LOCATION = 20; const MARGIN_STATE_CODE = 60; const MARGIN_COUNTY = 120; function trackExploreEvent(action: EventAction, label: string, value?: number) { trackEvent(EventCategory.EXPLORE, action, label, value); } function trackShare(label: string, value?: number) { trackExploreEvent(EventAction.SHARE, label, value); } function getNoDataCopy(metricName: string, locationNames: string) { return ( <p> We don't have {metricName} data for {locationNames}. </p> ); } function getMarginRight( showLabels: boolean, shortLabels: boolean, seriesList: Series[], ) { const maxLabelLength = max(seriesList.map(series => getLabelLength(series, shortLabels))) || 0; // We only show the labels when multiple locations are selected. If only // states are selected, we only need space for the state code, if at least // one county is selected, we need more space. return showLabels ? maxLabelLength > 4 ? MARGIN_COUNTY : MARGIN_STATE_CODE : MARGIN_SINGLE_LOCATION; } function getLabelLength(series: Series, shortLabel: boolean) { const label = getSeriesLabel(series, shortLabel); return label.length; } const Explore: React.FunctionComponent<{ initialFipsList: string[]; title?: string; nationalSummary?: React.ReactNode; currentMetric: ExploreMetric; setCurrentMetric: React.Dispatch<React.SetStateAction<ExploreMetric>>; }> = React.memo( ({ initialFipsList, title = 'Trends', currentMetric, setCurrentMetric, nationalSummary, }) => { const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('sm')); const isMobileXs = useMediaQuery(theme.breakpoints.down('xs')); const chartHeight = useChartHeightForBreakpoint(); const { sharedComponentId } = useParams<{ sharedComponentId?: string; }>(); // TODO (chris): Dont love the way of forcing a '' const region = useRegionFromParams(); // Originally we had share URLs like /explore/cases instead of // /explore/<sharedComponentId> and so this code allows them to keep working. if (sharedComponentId && EXPLORE_CHART_IDS.includes(sharedComponentId)) { const sharedMetric = getMetricByChartId(sharedComponentId)!; setCurrentMetric(sharedMetric); } const onSelectCurrentMetric = (newMetric: number) => { const newMetricName = metricLabels[newMetric]; setCurrentMetric(newMetric); trackExploreEvent(EventAction.SELECT, `Metric: ${newMetricName}`); }; const currentMetricName = getMetricName(currentMetric); const dataMeasure = getMetricDataMeasure(currentMetric); const yAxisDecimalPlaces = getYAxisDecimalPlaces(currentMetric); const yTickFormat = getYFormat(dataMeasure, yAxisDecimalPlaces); const yTooltipFormat = getYFormat(dataMeasure, 1); const allPeriodLabels = getAllPeriodLabels(); const initialLocations = useMemo( () => initialFipsList.map(fipsCode => regions.findByFipsCode(fipsCode)!), [initialFipsList], ); const autocompleteLocations = useMemo( () => getExploreAutocompleteLocations(initialFipsList[0]), [initialFipsList], ); const [chartSeries, setChartSeries] = useState<Series[]>([]); const [selectedLocations, setSelectedLocations] = useState<Region[]>( initialLocations, ); const [period, setPeriod] = useState<Period>(Period.ALL); const multiLocation = selectedLocations.length > 1; // TODO (chelsi) - does this need to be state? const [normalizeData, setNormalizeData] = useState( multiLocation && ORIGINAL_EXPLORE_METRICS.includes(currentMetric), ); const metricLabels = getMetricLabels(multiLocation); const dateRange = getDateRange(period); const onSelectTimePeriod = (newPeriod: Period) => { setPeriod(newPeriod); const newPeriodLabel = periodMap[newPeriod].label; trackExploreEvent(EventAction.SELECT, `Period: ${newPeriodLabel}`); }; const onChangeSelectedLocations = (newLocations: Region[]) => { const changedLocations = uniq(newLocations); const eventLabel = selectedLocations.length < changedLocations.length ? 'Adding Location' : 'Removing Location'; trackExploreEvent( EventAction.SELECT, eventLabel, changedLocations.length, ); // make sure that the current location is always selected setSelectedLocations(changedLocations); }; const exploreRef = useRef<HTMLDivElement>(null); const scrollToExplore = useCallback(() => { const scrollOffset = 200; return setTimeout(() => { if (exploreRef.current) { window.scrollTo({ left: 0, top: exploreRef.current.offsetTop - scrollOffset, behavior: 'smooth', }); } }, 200); }, [exploreRef]); const hasData = some(chartSeries, ({ data }) => data.length > 0); const hasMultipleLocations = selectedLocations.length > 1; const { pathname } = useLocation(); const marginRight = useMemo( () => getMarginRight(hasMultipleLocations, isMobileXs, chartSeries), [hasMultipleLocations, isMobileXs, chartSeries], ); const createSharedComponentId = async () => { return storeSharedComponentParams(SharedComponent.Explore, { currentMetric, normalizeData, selectedFips: selectedLocations.map(location => location.fipsCode), }); }; const maxYFromDefinition = getMaxYFromDefinition(currentMetric); const sharedParams = useSharedComponentParams(SharedComponent.Explore); useEffect(() => { const fetchSeries = () => getChartSeries(currentMetric, selectedLocations, normalizeData); fetchSeries().then(setChartSeries); }, [selectedLocations, currentMetric, normalizeData]); // Scrolls to explore if the url contains /explore (ie. if it's a share link) useEffect(() => { if (pathname.includes('/explore')) { const timeoutId = scrollToExplore(); return () => clearTimeout(timeoutId); } }, [pathname, scrollToExplore]); // if the pathname changes (ie. if navigating between location pages via compare or regionmap)- // resets metric, time period, and locations // (need to force the reset since the route doesnt change) useEffect(() => { setSelectedLocations(initialLocations); setCurrentMetric(ExploreMetric.CASES); setPeriod(Period.ALL); }, [pathname, region, initialLocations, setCurrentMetric]); // checks for shared parameters (ie. if arriving from a share link) // and sets state according to the shared params useEffect(() => { if (sharedParams) { setCurrentMetric(sharedParams.currentMetric); setNormalizeData(sharedParams.normalizeData); const locations = sharedParams.selectedFips.map( (fips: string) => regions.findByFipsCode(fips)!, ); setSelectedLocations(locations); } }, [setCurrentMetric, sharedParams]); // keeps normalizeData current with location and metric selection useEffect(() => { setNormalizeData( selectedLocations.length > 1 && ORIGINAL_EXPLORE_METRICS.includes(currentMetric), ); }, [currentMetric, selectedLocations]); const trackingLabel = hasMultipleLocations ? `Multiple Locations` : 'Single Location'; const numLocations = selectedLocations.length; const showLegend = ORIGINAL_EXPLORE_METRICS.includes(currentMetric) && numLocations === 1; // menu labels for metric, time period, and selected locations: const metricMenuLabel = metricLabels[currentMetric]; const regionsMenuLabel = selectedLocations.map(getLocationLabel).join('; '); const periodMenuLabel = allPeriodLabels[period]; const isHomepage = nationalSummary !== undefined; return ( <div ref={exploreRef}> <Styles.ExploreSectionHeader $isHomepage={isHomepage}> {title} </Styles.ExploreSectionHeader> {nationalSummary && nationalSummary} <Styles.ChartControlsContainer $isHomepage={isHomepage}> <Dropdown menuLabel="Metric" buttonSelectionLabel={metricMenuLabel} itemLabels={metricLabels} onSelect={onSelectCurrentMetric} maxWidth={250} /> <Dropdown menuLabel="Past # of days" buttonSelectionLabel={periodMenuLabel} itemLabels={allPeriodLabels} onSelect={onSelectTimePeriod} maxWidth={150} /> <LocationSelector regions={autocompleteLocations} selectedRegions={selectedLocations} onChangeSelectedRegions={onChangeSelectedLocations} maxWidth={400} regionNamesMenuLabel={regionsMenuLabel} /> </Styles.ChartControlsContainer> {selectedLocations.length > 0 && hasData && ( <Styles.ChartContainer> {/** * The width is set to zero while the parent div is rendering, the * placeholder div below prevents the page from jumping. */} <ParentSize> {({ width }) => width > 0 ? ( <ExploreChart seriesList={chartSeries} isMobile={isMobile} width={width} height={chartHeight} tooltipSubtext={`in ${getLocationNames(selectedLocations)}`} hasMultipleLocations={hasMultipleLocations} isMobileXs={isMobileXs} marginRight={marginRight} dateRange={dateRange} yTickFormat={yTickFormat} yTooltipFormat={yTooltipFormat} xTickTimeUnit={getXTickTimeUnitForPeriod(period)} maxYFromDefinition={maxYFromDefinition} /> ) : ( <div style={{ height: chartHeight }} /> ) } </ParentSize> </Styles.ChartContainer> )} {selectedLocations.length > 0 && !hasData && ( <EmptyPanel $height={chartHeight}> {getNoDataCopy( currentMetricName, getLocationNames(selectedLocations), )} <ScreenshotReady /> </EmptyPanel> )} {selectedLocations.length === 0 && ( <EmptyPanel $height={chartHeight}> <p>Please select states or counties to explore trends.</p> <ScreenshotReady /> </EmptyPanel> )} <Styles.FooterContainer> {showLegend && <Legend seriesList={chartSeries} />} <ShareBlock> <ShareButtonGroup disabled={selectedLocations.length === 0 || !hasData} imageUrl={() => createSharedComponentId().then(getExportImageUrl)} imageFilename={getImageFilename(selectedLocations, currentMetric)} url={() => createSharedComponentId().then(sharingId => getChartUrl(sharingId, region), ) } quote={getSocialQuote(selectedLocations, currentMetric)} region={region ? region : undefined} onSaveImage={() => { trackExploreEvent( EventAction.SAVE_IMAGE, trackingLabel, selectedLocations.length, ); }} onCopyLink={() => { trackExploreEvent( EventAction.COPY_LINK, trackingLabel, selectedLocations.length, ); }} onShareOnFacebook={() => trackShare(`Facebook: ${trackingLabel}`, numLocations) } onShareOnTwitter={() => trackShare(`Twitter: ${trackingLabel}`, numLocations) } /> </ShareBlock> </Styles.FooterContainer> </div> ); }, ); export default Explore;
the_stack
import objectPath from 'object-path'; import util from 'util'; import type { GraphQLFieldConfigArgumentMap, GraphQLArgumentConfig, GraphQLOutputType, GraphQLFieldConfig, GraphQLInputType, GraphQLResolveInfo, GraphQLFieldResolver, } from './graphql'; import { ObjectTypeComposer } from './ObjectTypeComposer'; import type { ObjectTypeComposerArgumentConfigMap, ObjectTypeComposerArgumentConfigMapDefinition, ObjectTypeComposerArgumentConfig, ObjectTypeComposerArgumentConfigDefinition, ObjectTypeComposerArgumentConfigAsObjectDefinition, } from './ObjectTypeComposer'; import { InputTypeComposer } from './InputTypeComposer'; import { EnumTypeComposer } from './EnumTypeComposer'; import { SchemaComposer } from './SchemaComposer'; import { deepmerge } from './utils/deepmerge'; import { clearName, inspect, mapEachKey } from './utils/misc'; import { isFunction, isString } from './utils/is'; import { filterByDotPaths } from './utils/filterByDotPaths'; import { getProjectionFromAST } from './utils/projection'; import type { ProjectionType } from './utils/projection'; import { typeByPath, TypeInPath } from './utils/typeByPath'; import { unwrapOutputTC, unwrapInputTC, replaceTC, isComposeInputType, cloneTypeTo, } from './utils/typeHelpers'; import type { ComposeOutputType, ComposeOutputTypeDefinition, ComposeNamedOutputType, ComposeNamedInputType, ComposeInputTypeDefinition, } from './utils/typeHelpers'; import type { Thunk, ThunkWithSchemaComposer, Extensions, Directive } from './utils/definitions'; import { GraphQLJSON } from './type'; import { NonNullComposer } from './NonNullComposer'; import { ListComposer } from './ListComposer'; export type ResolverKinds = 'query' | 'mutation' | 'subscription'; export type ResolverDefinition<TSource, TContext, TArgs = any> = { type?: ThunkWithSchemaComposer< | Readonly<ComposeOutputType<TContext>> | ComposeOutputTypeDefinition<TContext> | Readonly<Resolver<any, TContext, any>>, SchemaComposer<TContext> >; resolve?: ResolverRpCb<TSource, TContext, TArgs>; args?: ObjectTypeComposerArgumentConfigMapDefinition<TArgs>; name?: string; displayName?: string; kind?: ResolverKinds; description?: string; deprecationReason?: string | null; projection?: ProjectionType; parent?: Resolver<any, TContext, any>; extensions?: Extensions; directives?: Directive[]; }; export type ResolverResolveParams<TSource, TContext, TArgs = any> = { source: TSource; args: TArgs; context: TContext; info: GraphQLResolveInfo; projection: Partial<ProjectionType>; [opt: string]: any; }; export type ResolverFilterArgFn<TSource, TContext, TArgs = any> = ( query: any, value: any, resolveParams: ResolverResolveParams<TSource, TContext, TArgs> ) => any; export type ResolverFilterArgConfigDefinition<TSource, TContext, TArgs = any> = { name: string; type: ComposeInputTypeDefinition; description?: string | null | void; query?: ResolverFilterArgFn<TSource, TContext, TArgs>; filterTypeNameFallback?: string; defaultValue?: any; }; export type ResolverSortArgFn<TSource, TContext, TArgs = any> = ( resolveParams: ResolverResolveParams<TSource, TContext, TArgs> ) => any; export type ResolverSortArgConfig<TSource, TContext, TArgs = any> = { name: string; sortTypeNameFallback?: string; value: | { [key: string]: any } | ResolverSortArgFn<TSource, TContext, TArgs> | string | number | boolean | any[]; deprecationReason?: string | null; description?: string | null; }; export type ResolverWrapCb<TNewSource, TPrevSource, TContext, TNewArgs = any, TPrevArgs = any> = ( newResolver: Resolver<TNewSource, TContext, TNewArgs>, prevResolver: Resolver<TPrevSource, TContext, TPrevArgs> ) => Resolver<TNewSource, TContext, TNewArgs>; export type ResolverRpCb<TSource, TContext, TArgs = any> = ( resolveParams: ResolverResolveParams<TSource, TContext, TArgs> ) => Promise<any> | any; export type ResolverRpCbPartial<TSource, TContext, TArgs = any> = ( resolveParams: Partial<ResolverResolveParams<TSource, TContext, TArgs>> ) => Promise<any> | any; export type ResolverNextRpCb<TSource, TContext, TArgs = any> = ( next: ResolverRpCb<TSource, TContext, TArgs> ) => ResolverRpCb<TSource, TContext, TArgs>; export type ResolverDebugOpts = { showHidden?: boolean; depth?: number; colors?: boolean; }; export type ResolverMiddleware<TSource, TContext, TArgs = any> = ( resolve: (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo) => any, source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => any; /** * The most interesting class in `graphql-compose`. The main goal of `Resolver` is to keep available resolve methods for Type and use them for building relation with other types. */ export class Resolver<TSource = any, TContext = any, TArgs = any, TReturn = any> { schemaComposer: SchemaComposer<TContext>; // @ts-ignore defined in constructor via setter type: ComposeOutputType<TContext>; // @ts-ignore defined in constructor via setter args: ObjectTypeComposerArgumentConfigMap<any>; name: string; displayName: string | undefined; kind: ResolverKinds | undefined; description: string | undefined; deprecationReason: string | null | undefined; projection: ProjectionType; parent: Resolver<TSource, TContext, any> | undefined; extensions: Extensions | undefined; directives: Directive[] | undefined; resolve: ResolverRpCbPartial<TSource, TContext, TArgs> = () => Promise.resolve(); constructor( opts: ResolverDefinition<TSource, TContext, TArgs>, schemaComposer: SchemaComposer<TContext> ) { if (!(schemaComposer instanceof SchemaComposer)) { throw new Error( 'You must provide SchemaComposer instance as a second argument for `new Resolver(opts, SchemaComposer)`' ); } this.schemaComposer = schemaComposer; if (!opts.name) { throw new Error('For Resolver constructor the `opts.name` is required option.'); } this.name = opts.name; this.displayName = opts.displayName; this.parent = opts.parent; this.kind = opts.kind; this.description = opts.description; this.deprecationReason = opts.deprecationReason; this.projection = opts.projection || {}; this.extensions = opts.extensions; if (opts.type) { this.setType(opts.type); } this.setArgs(opts.args || ({} as ObjectTypeComposerArgumentConfigMapDefinition<any>)); if (opts.resolve) { this.resolve = opts.resolve as any; } if (opts.directives) { this.directives = opts.directives; } } // ----------------------------------------------- // Output type methods // ----------------------------------------------- getType(): GraphQLOutputType { if (!this.type) { return GraphQLJSON; } return this.type.getType(); } getTypeName(): string { return this.type.getTypeName(); } getTypeComposer(): ComposeNamedOutputType<TContext> { const anyTC = this.type; // Unwrap from List, NonNull and ThunkComposer // It's old logic from v1.0.0 and may be changed in future. return unwrapOutputTC(anyTC); } /** * Almost alias for `getTypeComposer`, but returns only ObjectTypeComposer. * It will throw an error if resolver has another kind of type. */ getOTC(): ObjectTypeComposer<TReturn, TContext> { const anyTC = this.getTypeComposer(); if (!(anyTC instanceof ObjectTypeComposer)) { throw new Error( `Resolver ${this.name} cannot return its output type as ObjectTypeComposer instance. ` + `Cause '${this.type.toString()}' does not instance of ${anyTC.constructor.name}.` ); } return anyTC; } setType<TNewReturn>( typeDef: ThunkWithSchemaComposer< | Readonly<ComposeOutputType<TContext>> | ComposeOutputTypeDefinition<TContext> | Readonly<Resolver<any, TContext, any>>, SchemaComposer<TContext> > ): Resolver<TSource, TContext, TArgs, TNewReturn> { const tc = this.schemaComposer.typeMapper.convertOutputTypeDefinition( typeDef, 'setType', 'Resolver' ); if (!tc) { throw new Error(`Cannot convert to ObjectType following value: ${inspect(typeDef)}`); } this.type = tc; return this as any; } // ----------------------------------------------- // Args methods // ----------------------------------------------- hasArg(argName: string): boolean { return !!this.args[argName]; } getArg(argName: string): ObjectTypeComposerArgumentConfig { if (!this.hasArg(argName)) { throw new Error( `Cannot get arg '${argName}' for resolver ${this.name}. Argument does not exist.` ); } let arg = this.args[argName]; if (isFunction(arg)) arg = arg(this.schemaComposer); if (typeof arg === 'string' || isComposeInputType(arg) || Array.isArray(arg)) { return { type: arg as any }; } return arg; } getArgConfig(argName: string): GraphQLArgumentConfig { const ac = this.getArg(argName); return { ...ac, type: ac.type.getType(), }; } getArgType(argName: string): GraphQLInputType { const ac = this.getArgConfig(argName); return ac.type; } getArgTypeName(fieldName: string): string { return this.getArg(fieldName).type.getTypeName(); } getArgs(): ObjectTypeComposerArgumentConfigMap<TArgs> { return this.args; } getArgNames(): string[] { return Object.keys(this.args); } setArgs<TNewArgs>( args: ObjectTypeComposerArgumentConfigMapDefinition<TNewArgs> ): Resolver<TSource, TContext, TNewArgs> { this.args = this.schemaComposer.typeMapper.convertArgConfigMap(args, this.name, 'Resolver'); return this as any; } setArg(argName: string, argConfig: ObjectTypeComposerArgumentConfigDefinition): this { this.args[argName] = this.schemaComposer.typeMapper.convertArgConfig( argConfig, argName, this.name, 'Resolver' ); return this; } setArgType(argName: string, typeDef: Thunk<ComposeInputTypeDefinition>): this { const ac = this.getArg(argName); const tc = this.schemaComposer.typeMapper.convertInputTypeDefinition( typeDef, argName, 'Resolver.args' ); if (!tc) { throw new Error(`Cannot create InputType from ${inspect(typeDef)}`); } ac.type = tc; return this; } extendArg( argName: string, partialArgConfig: Partial<ObjectTypeComposerArgumentConfigAsObjectDefinition> ): this { let prevArgConfig; try { prevArgConfig = this.getArgConfig(argName); } catch (e) { throw new Error( `Cannot extend arg '${argName}' in Resolver '${this.name}'. Argument does not exist.` ); } this.setArg(argName, { ...prevArgConfig, ...(partialArgConfig as any), }); return this; } addArgs(newArgs: ObjectTypeComposerArgumentConfigMapDefinition<any>): this { this.setArgs({ ...this.getArgs(), ...newArgs }); return this; } removeArg(argNameOrArray: string | string[]): this { const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; argNames.forEach((argName) => { delete this.args[argName]; }); return this; } removeOtherArgs(argNameOrArray: string | string[]): this { const keepArgNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; Object.keys(this.args).forEach((argName) => { if (keepArgNames.indexOf(argName) === -1) { delete this.args[argName]; } }); return this; } reorderArgs(names: string[]): this { const orderedArgs = {} as any; names.forEach((name) => { if (this.args[name]) { orderedArgs[name] = this.args[name]; delete this.args[name]; } }); this.args = { ...orderedArgs, ...this.args }; return this; } getArgTC(argName: string): ComposeNamedInputType<TContext> { const argType = this.getArg(argName).type; // Unwrap from List, NonNull and ThunkComposer return unwrapInputTC(argType); } /** * Alias for `getArgTC()` but returns statically checked InputTypeComposer. * If field have other type then error will be thrown. */ getArgITC(argName: string): InputTypeComposer<TContext> { const tc = this.getArgTC(argName); if (!(tc instanceof InputTypeComposer)) { throw new Error( `Resolver(${this.name}).getArgITC('${argName}') must be InputTypeComposer, but received ${tc.constructor.name}. Maybe you need to use 'getArgTC()' method which returns any type composer?` ); } return tc; } isArgNonNull(argName: string): boolean { return this.getArg(argName).type instanceof NonNullComposer; } makeArgNonNull(argNameOrArray: string | string[]): this { const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; argNames.forEach((argName) => { if (this.hasArg(argName)) { const argTC = this.getArg(argName).type; if (!(argTC instanceof NonNullComposer)) { this.setArgType(argName, new NonNullComposer(argTC)); } } }); return this; } // alias for makeArgNonNull() makeRequired(argNameOrArray: string | string[]): this { return this.makeArgNonNull(argNameOrArray); } makeArgNullable(argNameOrArray: string | string[]): this { const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; argNames.forEach((argName) => { if (this.hasArg(argName)) { const argTC = this.getArg(argName).type; if (argTC instanceof NonNullComposer) { this.setArgType(argName, argTC.ofType); } } }); return this; } makeOptional(argNameOrArray: string | string[]): this { return this.makeArgNullable(argNameOrArray); } isArgPlural(argName: string): boolean { const type = this.getArg(argName).type; return ( type instanceof ListComposer || (type instanceof NonNullComposer && type.ofType instanceof ListComposer) ); } makeArgPlural(argNameOrArray: string | string[]): this { const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; argNames.forEach((argName) => { const ac = this.args[argName]; if (ac && !(ac.type instanceof ListComposer)) { ac.type = new ListComposer(ac.type); } }); return this; } makeArgNonPlural(argNameOrArray: string | string[]): this { const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray]; argNames.forEach((argName) => { const ac = this.args[argName]; if (ac) { if (ac.type instanceof ListComposer) { ac.type = ac.type.ofType; } else if (ac.type instanceof NonNullComposer && ac.type.ofType instanceof ListComposer) { ac.type = ac.type.ofType.ofType instanceof NonNullComposer ? ac.type.ofType.ofType : new NonNullComposer(ac.type.ofType.ofType); } } }); return this; } cloneArg(argName: string, newTypeName: string): this { if (!{}.hasOwnProperty.call(this.args, argName)) { throw new Error( `Can not clone arg ${inspect(argName)} for resolver ${this.name}. Argument does not exist.` ); } const argTC = this.getArg(argName).type; const clonedTC = replaceTC(argTC, (unwrappedTC) => { if (!(unwrappedTC instanceof InputTypeComposer)) { throw new Error( `Cannot clone arg ${inspect(argName)} for resolver ${inspect(this.name)}. ` + `Argument should be InputObjectType, but received: ${inspect(unwrappedTC)}.` ); } if (!newTypeName || newTypeName !== clearName(newTypeName)) { throw new Error('You should provide new type name as second argument'); } if (newTypeName === unwrappedTC.getTypeName()) { throw new Error( `You should provide new type name. It is equal to current name: ${inspect(newTypeName)}.` ); } return unwrappedTC.clone(newTypeName); }); if (clonedTC) this.setArgType(argName, clonedTC); return this; } addFilterArg(opts: ResolverFilterArgConfigDefinition<TSource, TContext, TArgs>): this { if (!opts.name) { throw new Error('For Resolver.addFilterArg the arg name `opts.name` is required.'); } if (!opts.type) { throw new Error('For Resolver.addFilterArg the arg type `opts.type` is required.'); } const resolver = this.wrap(null, { name: 'addFilterArg' }); // get filterTC or create new one let filterITC: InputTypeComposer<any> | undefined; if (resolver.hasArg('filter')) { filterITC = resolver.getArgTC('filter') as any; } if (!(filterITC instanceof InputTypeComposer)) { if (!opts.filterTypeNameFallback || !isString(opts.filterTypeNameFallback)) { throw new Error( 'For Resolver.addFilterArg needs to provide `opts.filterTypeNameFallback: string`. ' + 'This string will be used as unique name for `filter` type of input argument. ' + 'Eg. FilterXXXXXInput' ); } filterITC = InputTypeComposer.create(opts.filterTypeNameFallback, this.schemaComposer); resolver.args.filter = { type: filterITC, }; } const { name, type, defaultValue, description } = opts; filterITC.setField(name, { type, description } as any); // default value can be written only on argConfig if (defaultValue !== undefined) { resolver.args.filter.defaultValue = resolver.args.filter.defaultValue || {}; resolver.args.filter.defaultValue[name] = defaultValue; } const resolveNext = resolver.getResolve(); const query = opts.query; if (query && isFunction(query)) { resolver.setResolve(async (resolveParams) => { const value = objectPath.get(resolveParams, ['args', 'filter', name]); if (value !== null && value !== undefined) { if (!resolveParams.rawQuery) { resolveParams.rawQuery = {}; // eslint-disable-line } await query(resolveParams.rawQuery, value, resolveParams); } return resolveNext(resolveParams); }); } return resolver as any; } addSortArg(opts: ResolverSortArgConfig<TSource, TContext, TArgs>): this { if (!opts.name) { throw new Error('For Resolver.addSortArg the `opts.name` is required.'); } if (!opts.value) { throw new Error('For Resolver.addSortArg the `opts.value` is required.'); } const resolver = this.wrap(null, { name: 'addSortArg' }); // get sortETC or create new one let sortETC: EnumTypeComposer<TContext> | undefined; if (resolver.hasArg('sort')) { sortETC = resolver.getArgTC('sort') as any; } if (!sortETC) { if (!opts.sortTypeNameFallback || !isString(opts.sortTypeNameFallback)) { throw new Error( 'For Resolver.addSortArg needs to provide `opts.sortTypeNameFallback: string`. ' + 'This string will be used as unique name for `sort` type of input argument. ' + 'Eg. SortXXXXXEnum' ); } sortETC = EnumTypeComposer.create(opts.sortTypeNameFallback, this.schemaComposer); resolver.args.sort = { type: sortETC, }; } if (!(sortETC instanceof EnumTypeComposer)) { throw new Error(`Resolver must have 'sort' arg with EnumType, but got: ${inspect(sortETC)} `); } const { name, description, deprecationReason, value } = opts; // extend sortETC with new sorting value sortETC.setField(name, { description, deprecationReason, value, }); // If sort value is computable (function), then wrap resolve method const resolveNext = resolver.getResolve(); if (isFunction(value)) { sortETC.extendField(name, { value: name }); const getValue = value as any; resolver.setResolve((resolveParams) => { const v = objectPath.get(resolveParams, ['args', 'sort']); if (v === name) { const newSortValue = getValue(resolveParams); (resolveParams.args as any).sort = newSortValue; } return resolveNext(resolveParams); }); } return resolver as any; } // ----------------------------------------------- // Resolve methods // ----------------------------------------------- getResolve(): ResolverRpCb<TSource, TContext, TArgs> { return this.resolve; } setResolve(resolve: ResolverRpCb<TSource, TContext, TArgs>): this { this.resolve = resolve as any; return this; } // ----------------------------------------------- // Wrap methods // ----------------------------------------------- /** * You may construct a new resolver with wrapped logic: * * @example * const log = []; * * const mw1 = async (resolve, source, args, context, info) => { * log.push('m1.before'); * const res = await resolve(source, args, context, info); * log.push('m1.after'); * return res; * }; * * const mw2 = async (resolve, source, args, context, info) => { * log.push('m2.before'); * const res = await resolve(source, args, context, info); * log.push('m2.after'); * return res; * }; * * const newResolver = Resolver.withMiddlewares([mw1, mw2]); * await newResolver.resolve({}); * * expect(log).toEqual([ * 'm1.before', * 'm2.before', * 'call resolve', * 'm2.after', * 'm1.after' * ]); */ withMiddlewares( middlewares: Array<ResolverMiddleware<TSource, TContext, TArgs>> ): Resolver<TSource, TContext, TArgs> { if (!Array.isArray(middlewares)) { throw new Error( `You should provide array of middlewares '(resolve, source, args, context, info) => any', but provided ${inspect( middlewares )}.` ); } let resolver = this as Resolver<TSource, TContext, TArgs>; middlewares.reverse().forEach((mw) => { let name; if (mw.name) { name = mw.name; } else if ((mw as any).constructor && mw.constructor.name) { name = mw.constructor.name; } else { name = 'middleware'; } const newResolver = this.clone({ name, parent: resolver }); const resolve = resolver.getResolve(); newResolver.setResolve((rp) => mw( (source, args, context, info) => { return resolve({ ...rp, source, args, context, info }); }, rp.source as any, rp.args as any, rp.context, rp.info ) ); resolver = newResolver as any; }); return resolver; } wrap<TNewSource, TNewArgs>( cb?: ResolverWrapCb<TNewSource, TSource, TContext, TNewArgs, TArgs> | null, newResolverOpts: Partial<ResolverDefinition<TNewSource, TContext, TNewArgs>> = {} ): Resolver<TNewSource, TContext, TNewArgs> { const prevResolver = this as Resolver<TSource, TContext, TArgs>; const newResolver = this.clone({ name: 'wrap', parent: prevResolver, ...newResolverOpts, }); if (isFunction(cb)) { const resolver = cb(newResolver, prevResolver); if (resolver) return resolver; } return newResolver; } wrapResolve( cb: ResolverNextRpCb<TSource, TContext, TArgs>, wrapperName: string = 'wrapResolve' ): Resolver<TSource, TContext, TArgs> { return this.wrap( (newResolver, prevResolver) => { const newResolve = cb(prevResolver.getResolve()); newResolver.setResolve(newResolve); return newResolver; }, { name: wrapperName } ); } wrapArgs<TNewArgs>( cb: ( prevArgs: GraphQLFieldConfigArgumentMap ) => ObjectTypeComposerArgumentConfigMapDefinition<TArgs>, wrapperName: string = 'wrapArgs' ): Resolver<TSource, TContext, TNewArgs> { return this.wrap( (newResolver, prevResolver) => { // clone prevArgs, to avoid changing args in callback const prevArgs: any = { ...prevResolver.getArgs() }; const newArgs = cb(prevArgs) || prevArgs; newResolver.setArgs(newArgs); return newResolver; }, { name: wrapperName } ); } wrapCloneArg(argName: string, newTypeName: string): Resolver<TSource, TContext, TArgs> { return this.wrap((newResolver) => newResolver.cloneArg(argName, newTypeName), { name: 'cloneFilterArg', }); } wrapType( cb: (prevType: ComposeOutputType<TContext>) => ComposeOutputTypeDefinition<TContext>, wrapperName: string = 'wrapType' ): Resolver<TSource, TContext, TArgs> { return this.wrap( (newResolver, prevResolver) => { const prevType = prevResolver.type; const newType = cb(prevType) || prevType; newResolver.setType(newType); return newResolver; }, { name: wrapperName } ); } // ----------------------------------------------- // Misc methods // ----------------------------------------------- getFieldConfig( opts: { projection?: ProjectionType; } = {} ): GraphQLFieldConfig<TSource, TContext, TArgs> { const fc: GraphQLFieldConfig<TSource, TContext, TArgs> = { type: this.getType(), args: mapEachKey(this.getArgs(), (ac) => ({ ...ac, type: ac.type.getType(), })), resolve: this.getFieldResolver(opts), }; if (this.description) fc.description = this.description; if (this.deprecationReason) fc.deprecationReason = this.deprecationReason; return fc; } getFieldResolver( opts: { projection?: ProjectionType; } = {} ): GraphQLFieldResolver<TSource, TContext, TArgs> { const resolve = this.getResolve(); return (source: TSource, args: TArgs, context: TContext, info: GraphQLResolveInfo) => { let projection = getProjectionFromAST(info); if (this.projection) { projection = deepmerge(projection, this.projection) as ProjectionType; } if (opts.projection) { projection = deepmerge(projection, opts.projection) as ProjectionType; } return resolve({ source, args, context, info, projection }); }; } getKind(): ResolverKinds | void { return this.kind; } setKind(kind: string): this { if (kind !== 'query' && kind !== 'mutation' && kind !== 'subscription') { throw new Error( `You provide incorrect value '${kind}' for Resolver.setKind method. ` + 'Valid values are: query | mutation | subscription' ); } this.kind = kind; return this; } getDescription(): string | undefined { return this.description; } setDescription(description: string | undefined): this { this.description = description; return this; } getDeprecationReason(): string | undefined | null { return this.deprecationReason; } setDeprecationReason(reason: string | undefined): this { this.deprecationReason = reason; return this; } get(path: string | string[]): TypeInPath<TContext> | void { return typeByPath(this, path); } /** * Clone this Resolver with overriding of some options. * Internally it just copies all properties. * But for `args` and `projection` it recreates objects with the same type & values (it allows to add or remove properties without affection old Resolver). */ clone<TNewSource, TNewArgs>( opts: Partial<ResolverDefinition<TNewSource, TContext, TNewArgs>> = {} ): Resolver<TNewSource, TContext, TNewArgs> { const oldOpts = {} as ResolverDefinition<TNewSource, TContext>; const self = this as Resolver<TSource, TContext, TArgs>; for (const key in self) { if (self.hasOwnProperty(key)) { (oldOpts as any)[key] = (self as any)[key]; } } oldOpts.displayName = undefined; oldOpts.args = { ...this.args }; if (this.projection) { oldOpts.projection = { ...this.projection }; } return new Resolver({ ...oldOpts, ...opts }, this.schemaComposer); } /** * Clone this resolver to another SchemaComposer. * Also will be cloned all sub-types. */ cloneTo( anotherSchemaComposer: SchemaComposer<any>, cloneMap: Map<any, any> = new Map() ): Resolver<any, any, any> { if (!anotherSchemaComposer) { throw new Error('You should provide SchemaComposer for InterfaceTypeComposer.cloneTo()'); } if (cloneMap.has(this)) return cloneMap.get(this); const cloned = new Resolver( { name: this.name, displayName: this.displayName, kind: this.kind, description: this.description, deprecationReason: this.deprecationReason, projection: { ...this.projection }, extensions: { ...this.extensions }, resolve: this.resolve, }, anotherSchemaComposer ); cloneMap.set(this, cloned); if (this.type) { cloned.type = this.type.cloneTo(anotherSchemaComposer, cloneMap) as any; } if (this.parent) { cloned.parent = this.parent.cloneTo(anotherSchemaComposer, cloneMap); } cloned.args = mapEachKey(this.args, (argConfig) => ({ ...argConfig, type: cloneTypeTo(argConfig.type, anotherSchemaComposer, cloneMap), extensions: { ...argConfig.extensions }, })) as any; return cloned; } // ----------------------------------------------- // Extensions methods // ----------------------------------------------- getExtensions(): Extensions { if (!this.extensions) { return {}; } else { return this.extensions; } } setExtensions(extensions: Extensions): this { this.extensions = extensions; return this; } extendExtensions(extensions: Extensions): this { const current = this.getExtensions(); this.setExtensions({ ...current, ...extensions, }); return this; } clearExtensions(): this { this.setExtensions({}); return this; } getExtension(extensionName: string): unknown { const extensions = this.getExtensions(); return extensions[extensionName]; } hasExtension(extensionName: string): boolean { const extensions = this.getExtensions(); return extensionName in extensions; } setExtension(extensionName: string, value: unknown): this { this.extendExtensions({ [extensionName]: value, }); return this; } removeExtension(extensionName: string): this { const extensions = { ...this.getExtensions() }; delete extensions[extensionName]; this.setExtensions(extensions); return this; } // ----------------------------------------------- // Debug methods // ----------------------------------------------- getNestedName(): string { const name = this.displayName || this.name; if (this.parent) { return `${name}(${this.parent.getNestedName()})`; } return name; } toString(colors: boolean = true): string { return util.inspect(this.toDebugStructure(false), { depth: 20, colors }).replace(/\\n/g, '\n'); } setDisplayName(name: string): this { this.displayName = name; return this; } toDebugStructure(colors: boolean = true): Record<string, any> { const info: any = { name: this.name, displayName: this.displayName, type: util.inspect(this.type, { depth: 2, colors }), args: this.args, resolve: this.resolve ? this.resolve.toString() : this.resolve, }; if (this.parent) { info.resolve = [info.resolve, { 'Parent resolver': this.parent.toDebugStructure(colors) }]; } return info; } debugExecTime(): Resolver<TSource, TContext, TArgs> { /* eslint-disable no-console */ return this.wrapResolve( (next) => async (rp) => { const name = `Execution time for ${this.getNestedName()}`; console.time(name); const res = await next(rp); console.timeEnd(name); return res; }, 'debugExecTime' ); /* eslint-enable no-console */ } debugParams( filterPaths?: string | string[] | undefined | null, opts: ResolverDebugOpts = { colors: true, depth: 5 } ): Resolver<TSource, TContext, TArgs> { /* eslint-disable no-console */ return this.wrapResolve( (next) => (rp: any) => { console.log(`ResolverResolveParams for ${this.getNestedName()}:`); const data = filterByDotPaths(rp, filterPaths, { // is hidden (use debugParams(["info"])) or debug({ params: ["info"]}) // `is hidden (use debugParams(["context.*"])) or debug({ params: ["context.*"]})`, hideFields: rp?.context && rp.context?.res && rp.context?.params && rp.context?.headers ? { // looks like context is express request, collapse it info: '[[hidden]]', context: '[[hidden]]', } : { info: '[[hidden]]', 'context.*': '[[hidden]]', }, hideFieldsNote: 'Some data was [[hidden]] to display this fields use debugParams("%fieldNames%")', }); console.dir(data, opts); return next(rp); }, 'debugParams' ); /* eslint-enable no-console */ } debugPayload( filterPaths?: string | string[] | undefined | null, opts: ResolverDebugOpts = { colors: true, depth: 5 } ): Resolver<TSource, TContext, TArgs> { /* eslint-disable no-console */ return this.wrapResolve( (next) => async (rp) => { try { const res = await next(rp); console.log(`Resolved Payload for ${this.getNestedName()}:`); if (Array.isArray(res) && res.length > 3 && !filterPaths) { console.dir( [ filterPaths ? filterByDotPaths(res[0], filterPaths) : res[0], `[debug note]: Other ${res.length - 1} records was [[hidden]]. ` + 'Use debugPayload("0 1 2 3 4") or debug({ payload: "0 1 2 3 4" }) for display this records', ], opts ); } else { console.dir(filterPaths ? filterByDotPaths(res, filterPaths) : res, opts); } return res; } catch (e) { console.log(`Rejected Payload for ${this.getNestedName()}:`); console.log(e); throw e; } }, 'debugPayload' ); /* eslint-enable no-console */ } debug( filterDotPaths?: { params?: string | string[] | undefined | null; payload?: string | string[] | undefined | null; }, opts: ResolverDebugOpts = { colors: true, depth: 2 } ): Resolver<TSource, TContext, TArgs> { return this.debugExecTime() .debugParams(filterDotPaths ? filterDotPaths.params : null, opts) .debugPayload(filterDotPaths ? filterDotPaths.payload : null, opts); } }
the_stack
import { RolloutStrategy, RolloutStrategyAttribute, RolloutStrategyAttributeConditional, RolloutStrategyFieldType } from './models'; import compareSemver from 'semver-compare'; import { Netmask } from 'netmask'; // this library is not node specific import { v3 as murmur3 } from 'murmurhash'; import { ClientContext } from './client_context'; export interface PercentageCalculator { determineClientPercentage(percentageText: string, featureId: string): number; } export class Murmur3PercentageCalculator implements PercentageCalculator { private readonly MAX_PERCENTAGE = 1000000; public determineClientPercentage(percentageText: string, featureId: string): number { const result = murmur3(percentageText + featureId); return Math.floor(result / Math.pow(2, 32) * this.MAX_PERCENTAGE); } } export class Applied { public readonly matched: boolean; public readonly value: any; constructor(matched: boolean, value: any) { this.matched = matched; this.value = value; } } export interface StrategyMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean; } export interface MatcherRepository { findMatcher(attr: RolloutStrategyAttribute): StrategyMatcher; } class FallthroughMatcher implements StrategyMatcher { // eslint-disable-next-line @typescript-eslint/no-unused-vars match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { return false; } } class BooleanMatcher implements StrategyMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { const val = 'true' === suppliedValue; if (attr.conditional === RolloutStrategyAttributeConditional.Equals) { return val === (attr.values[0].toString() === 'true'); } if (attr.conditional === RolloutStrategyAttributeConditional.NotEquals) { return val !== (attr.values[0].toString() === 'true'); } return false; } } class StringMatcher implements StrategyMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { const vals = this.attrToStringValues(attr); // tslint:disable-next-line:switch-default switch (attr.conditional) { case RolloutStrategyAttributeConditional.Equals: return vals.findIndex((v) => v === suppliedValue) >= 0; case RolloutStrategyAttributeConditional.EndsWith: return vals.findIndex((v) => suppliedValue.endsWith(v)) >= 0; case RolloutStrategyAttributeConditional.StartsWith: return vals.findIndex((v) => suppliedValue.startsWith(v)) >= 0; case RolloutStrategyAttributeConditional.Greater: return vals.findIndex((v) => suppliedValue > v) >= 0; case RolloutStrategyAttributeConditional.GreaterEquals: return vals.findIndex((v) => suppliedValue >= v) >= 0; case RolloutStrategyAttributeConditional.Less: return vals.findIndex((v) => suppliedValue < v) >= 0; case RolloutStrategyAttributeConditional.LessEquals: return vals.findIndex((v) => suppliedValue <= v) >= 0; case RolloutStrategyAttributeConditional.NotEquals: return vals.findIndex((v) => v === suppliedValue) === -1; case RolloutStrategyAttributeConditional.Includes: return vals.findIndex((v) => suppliedValue.includes(v)) >= 0; case RolloutStrategyAttributeConditional.Excludes: return vals.findIndex((v) => suppliedValue.includes(v)) === -1; case RolloutStrategyAttributeConditional.Regex: return vals.findIndex((v) => suppliedValue.match(v)) >= 0; } return false; } protected attrToStringValues(attr: RolloutStrategyAttribute): Array<string> { return attr.values.filter((v) => v != null).map((v) => v.toString()); } } class DateMatcher extends StringMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { try { const parsedDate = new Date(suppliedValue); if (parsedDate == null) { return false; } return super.match(parsedDate.toISOString().substring(0, 10), attr); } catch (e) { return false; } } protected attrToStringValues(attr: RolloutStrategyAttribute): Array<string> { return attr.values.filter((v) => v != null) .map((v) => (v instanceof Date) ? v.toISOString().substring(0, 10) : v.toString()); } } class DateTimeMatcher extends StringMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { try { const parsedDate = new Date(suppliedValue); if (parsedDate == null) { return false; } return super.match(parsedDate.toISOString().substr(0, 19) + 'Z', attr); } catch (e) { return false; } } protected attrToStringValues(attr: RolloutStrategyAttribute): Array<string> { return attr.values.filter((v) => v != null) .map((v) => (v instanceof Date) ? (v.toISOString().substr(0, 19) + 'Z') : v.toString()); } } class NumberMatcher implements StrategyMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { try { const isFloat = suppliedValue.indexOf('.') >= 0; const num = isFloat ? parseFloat(suppliedValue) : parseInt(suppliedValue, 10); const conv = (v) => isFloat ? parseFloat(v) : parseInt(v, 10); const vals = attr.values.filter((v) => v != null).map((v) => v.toString()); // tslint:disable-next-line:switch-default switch (attr.conditional) { case RolloutStrategyAttributeConditional.Equals: return vals.findIndex((v) => conv(v) === num) >= 0; case RolloutStrategyAttributeConditional.EndsWith: return vals.findIndex((v) => suppliedValue.endsWith(v)) >= 0; case RolloutStrategyAttributeConditional.StartsWith: return vals.findIndex((v) => suppliedValue.startsWith(v)) >= 0; case RolloutStrategyAttributeConditional.Greater: return vals.findIndex((v) => num > conv(v)) >= 0; case RolloutStrategyAttributeConditional.GreaterEquals: return vals.findIndex((v) => num >= conv(v)) >= 0; case RolloutStrategyAttributeConditional.Less: return vals.findIndex((v) => num < conv(v)) >= 0; case RolloutStrategyAttributeConditional.LessEquals: return vals.findIndex((v) => num <= conv(v)) >= 0; case RolloutStrategyAttributeConditional.NotEquals: return vals.findIndex((v) => conv(v) === num) === -1; case RolloutStrategyAttributeConditional.Includes: return vals.findIndex((v) => suppliedValue.includes(v)) >= 0; case RolloutStrategyAttributeConditional.Excludes: return vals.findIndex((v) => suppliedValue.includes(v)) === -1; case RolloutStrategyAttributeConditional.Regex: return vals.findIndex((v) => suppliedValue.match(v)) >= 0; } } catch (e) { return false; } return false; } } class SemanticVersionMatcher implements StrategyMatcher { match(suppliedValue: string, attr: RolloutStrategyAttribute): boolean { const vals = attr.values.filter((v) => v != null).map((v) => v.toString()); // tslint:disable-next-line:switch-default switch (attr.conditional) { case RolloutStrategyAttributeConditional.Includes: case RolloutStrategyAttributeConditional.Equals: return vals.findIndex((v) => compareSemver(suppliedValue, v) === 0) >= 0; case RolloutStrategyAttributeConditional.EndsWith: break; case RolloutStrategyAttributeConditional.StartsWith: break; case RolloutStrategyAttributeConditional.Greater: return vals.findIndex((v) => compareSemver(suppliedValue, v) > 0) >= 0; case RolloutStrategyAttributeConditional.GreaterEquals: return vals.findIndex((v) => compareSemver(suppliedValue, v) >= 0) >= 0; case RolloutStrategyAttributeConditional.Less: return vals.findIndex((v) => compareSemver(suppliedValue, v) < 0) >= 0; case RolloutStrategyAttributeConditional.LessEquals: return vals.findIndex((v) => compareSemver(suppliedValue, v) <= 0) >= 0; case RolloutStrategyAttributeConditional.NotEquals: case RolloutStrategyAttributeConditional.Excludes: return vals.findIndex((v) => compareSemver(suppliedValue, v) !== 0) >= 0; case RolloutStrategyAttributeConditional.Regex: break; } return false; } } class IPNetworkMatcher implements StrategyMatcher { match(ip: string, attr: RolloutStrategyAttribute): boolean { const vals = attr.values.filter((v) => v != null); // tslint:disable-next-line:switch-default switch (attr.conditional) { case RolloutStrategyAttributeConditional.Equals: case RolloutStrategyAttributeConditional.Includes: return vals.findIndex((v) => new Netmask(v).contains(ip)) >= 0; case RolloutStrategyAttributeConditional.NotEquals: case RolloutStrategyAttributeConditional.Excludes: return vals.findIndex((v) => new Netmask(v).contains(ip)) === -1; } return false; } } export class MatcherRegistry implements MatcherRepository { findMatcher(attr: RolloutStrategyAttribute): StrategyMatcher { // tslint:disable-next-line:switch-default switch (attr?.type) { case RolloutStrategyFieldType.String: return new StringMatcher(); case RolloutStrategyFieldType.SemanticVersion: return new SemanticVersionMatcher(); case RolloutStrategyFieldType.Number: return new NumberMatcher(); case RolloutStrategyFieldType.Date: return new DateMatcher(); case RolloutStrategyFieldType.Datetime: return new DateTimeMatcher(); case RolloutStrategyFieldType.Boolean: return new BooleanMatcher(); case RolloutStrategyFieldType.IpAddress: return new IPNetworkMatcher(); } return new FallthroughMatcher(); } } export class ApplyFeature { private readonly _percentageCalculator: PercentageCalculator; private readonly _matcherRepository: MatcherRepository; constructor(percentageCalculator?: PercentageCalculator, matcherRepository?: MatcherRepository) { this._percentageCalculator = percentageCalculator || new Murmur3PercentageCalculator(); this._matcherRepository = matcherRepository || new MatcherRegistry(); } public apply(strategies: Array<RolloutStrategy>, key: string, featureValueId: string, context: ClientContext): Applied { if (context != null && strategies != null && strategies.length > 0) { let percentage: number = null; let percentageKey: string = null; const basePercentage = new Map<string, number>(); const defaultPercentageKey = context.defaultPercentageKey(); for (const rsi of strategies) { if (rsi.percentage !== 0 && (defaultPercentageKey != null || (rsi.percentageAttributes !== undefined && rsi.percentageAttributes.length > 0))) { const newPercentageKey = this.determinePercentageKey(context, rsi.percentageAttributes); if (!basePercentage.has(newPercentageKey)) { basePercentage.set(newPercentageKey, 0); } const basePercentageVal = basePercentage.get(newPercentageKey); // if we have changed the key or we have never calculated it, calculate it and set the // base percentage to null if (percentage === null || newPercentageKey !== percentageKey) { percentageKey = newPercentageKey; percentage = this._percentageCalculator.determineClientPercentage(percentageKey, featureValueId); } const useBasePercentage = (rsi.attributes === undefined || rsi.attributes.length === 0) ? basePercentageVal : 0; // if the percentage is lower than the user's key + // id of feature value then apply it if (percentage <= (useBasePercentage + rsi.percentage)) { if (rsi.attributes != null && rsi.attributes.length > 0) { if (this.matchAttribute(context, rsi)) { return new Applied(true, rsi.value); } } else { return new Applied(true, rsi.value); } } // this was only a percentage and had no other attributes if (rsi.attributes !== undefined && rsi.attributes.length > 0) { basePercentage.set(percentageKey, basePercentage.get(percentageKey) + rsi.percentage); } } if ((rsi.percentage === 0 || rsi.percentage === undefined) && rsi.attributes !== undefined && rsi.attributes.length > 0 && this.matchAttribute(context, rsi)) { // nothing to do with a percentage return new Applied(true, rsi.value); } } } return new Applied(false, null); } private determinePercentageKey(context: ClientContext, percentageAttributes: Array<string>): string { if (percentageAttributes == null || percentageAttributes.length === 0) { return context.defaultPercentageKey(); } return percentageAttributes.filter((pa) => context.getAttr(pa, '<none>')).join('$'); } private matchAttribute(context: ClientContext, rsi: RolloutStrategy): boolean { for (const attr of rsi.attributes) { let suppliedValue = context.getAttr(attr.fieldName, null); if (suppliedValue === null && attr.fieldName.toLowerCase() === 'now') { // tslint:disable-next-line:switch-default switch (attr.type) { case RolloutStrategyFieldType.Date: suppliedValue = new Date().toISOString().substring(0, 10); break; case RolloutStrategyFieldType.Datetime: suppliedValue = new Date().toISOString(); break; } } if (attr.values == null && suppliedValue == null) { if (attr.conditional !== RolloutStrategyAttributeConditional.Equals) { return false; } continue; // skip } if (attr.values == null || suppliedValue == null) { return false; } if (!this._matcherRepository.findMatcher(attr).match(suppliedValue, attr)) { return false; } } return true; } }
the_stack
import * as template from "../../src/template"; import {Contest, Task} from "../../src/project"; import {AtCoder} from "../../src/atcoder"; import {getConfigDirectory} from "../../src/config"; import {importFsExtra} from "../../src/imports"; import {resolve} from "path"; import {promisify} from "util"; import {readFile, readdir} from "fs"; import fs_extra from "fs-extra"; import mock from "mock-fs"; import child_process from "child_process"; jest.mock("../../src/config"); jest.mock("../../src/imports"); const mock_template_cpp: template.RawTemplate = { contest: { static: [["gitignore", ".gitignore"]] }, task: { submit: "main.cpp", program: ["main.cpp"] } }; const mock_template_cpp_json = JSON.stringify(mock_template_cpp); const mock_template_ts: template.RawTemplate = { contest: { static: ["package.json", ["gitignore", ".gitignore"]], cmd: "npm install" }, task: { submit: "{TaskID}.ts", program: [["main.ts", "{TaskID}.ts"]], static: ["foo.txt", ["bar.txt", "{alphabet}_{TaskID}"], ["baz.txt", "{CONTESTID}-{index1}.txt"]], cmd: "echo $TASK_ID", testdir: "tests-{TaskLabel}" } }; const mock_template_ts_json = JSON.stringify(mock_template_ts); const mock_templates: Array<{ name: string, template: template.RawTemplate }> = [ { name: "cpp", template: mock_template_cpp }, { name: "ts", template: mock_template_ts } ]; const templates2files = (templates: Array<{ name: string, template: template.RawTemplate }>) => templates.reduce( (o, {name, template}) => ({ ...o, [name]: {"template.json": JSON.stringify(template)} }), {}); const DUMMY_CONFIG_DIRECTORY_PATH = "/config/dir/of/acc"; const DUMMY_WORKING_DIRECTORY_PATH = "/current/working/directory/to/solve/problems"; // TODO: もっと適当な場所に定義を移す const dummy_contest: Contest = { id: "aic987", title: "AtCoder Imaginary Contest 987", url: AtCoder.getContestURL("aic987") }; const dummy_task01: Task = { id: "aic987_a", label: "A", title: "This is Problem", url: AtCoder.getTaskURL("aic987", "aic987_a") }; describe("template", () => { beforeAll(async () => { // 常に同じpathを返すようにしておく // @ts-ignore: dynamically added method for test getConfigDirectory.mockResolvedValue(DUMMY_CONFIG_DIRECTORY_PATH); // dynamic import in a mocked filesystem causes errors // @ts-ignore: dynamically added method for test importFsExtra.mockResolvedValue(fs_extra); }); beforeEach(() => { // clear mock call log jest.clearAllMocks(); }); describe("validateTemplateJSON", () => { test("valid", async () => { const [valid, error] = await template.validateTemplateJSON(JSON.parse(mock_template_cpp_json)); expect(valid).toBe(true); expect(error).toBe(null); }); test("invalid", async () => { // TODO: そもそもinvalidなものはany型でなければ入れられないのでおかしい const data: any = {task: {}}; const [valid, error] = await template.validateTemplateJSON(data); expect(valid).toBe(false); expect(error).toMatchSnapshot(); }); }); describe("getTemplate", () => { test("valid template", async () => { mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { "template01": { "template.json": mock_template_cpp_json } } }); expect(await template.getTemplate("template01")).toEqual({name: "template01", ...mock_template_cpp}); mock.restore(); }); test("invalid template", async () => { mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { "template02": { /* lack of required property "task" */ "template.json": JSON.stringify({ contest: { cmd: "echo hi" } }) } } }); await expect(template.getTemplate("template02")).rejects.toThrowError(); mock.restore(); }) }); describe("getTemplates", () => { test("get all templates", async () => { const templates = []; mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: templates2files(mock_templates) }); const result = await template.getTemplates(); // restore mock before toMatchSnapshot() // Otherwise, jest cannot detect the exist snapshot and the test always passes mock.restore(); expect(result).toMatchSnapshot(); }); test("no template.json in directory", async () => { const templates = []; mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { ...templates2files(mock_templates), // add directory without template.json "non-template": { "this-is-not-template.json": JSON.stringify({ task: { submit: "main.cpp", program: ["main.cpp"] } }) } } }); const result = await template.getTemplates(); mock.restore(); // there's no template "non-template" expect(result).toMatchSnapshot(); }); test("files to be ignored", async () => { // mock console.error to avoid https://github.com/tschaub/mock-fs/issues/234 const spy = jest.spyOn(console, "error").mockImplementation(() => null); const templates = []; mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { ...templates2files(mock_templates), // unrelated files in config directory "foo.txt": "I am a text file, unrelated to templates!", "config.json": JSON.stringify({ "default-task-choice": "next" }) } }); const result = await template.getTemplates(); mock.restore(); // there's no template "non-template" expect(result).toMatchSnapshot(); spy.mockRestore(); }); test("invalid template", async () => { const templates = []; mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { ...templates2files(mock_templates), "invalid": { // add invalid template "template.json": JSON.stringify({ contest: { cmd: "echo ho" } }) } } }); // NOTE: そもそもここでエラーを出すのは正しいのか? (警告メッセージを出すなどする?) await expect(template.getTemplates()).rejects.toThrowError(); mock.restore(); }); }); describe("installContestTemplate", () => { test("overwrite static files", async () => { mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { "template01": { "template.json": mock_template_cpp_json, "gitignore": ".git/" } }, [DUMMY_WORKING_DIRECTORY_PATH]: { [dummy_contest.id]: { ".gitignore": "this .gitignore will be overwritten by installing of the template" } } }); // cd to (mocked) current directory process.chdir(DUMMY_WORKING_DIRECTORY_PATH); expect(process.cwd()).toEqual(DUMMY_WORKING_DIRECTORY_PATH); const template01 = await template.getTemplate("template01"); expect(await template01).toEqual({name: "template01", ...mock_template_cpp}); const contest_dir_path = resolve(DUMMY_WORKING_DIRECTORY_PATH, dummy_contest.id); expect(await promisify(readdir)(contest_dir_path)).toEqual([".gitignore"]); expect(await promisify(readFile)(resolve(contest_dir_path, ".gitignore"), "utf-8")).toEqual("this .gitignore will be overwritten by installing of the template"); await template.installContestTemplate(dummy_contest, template01, contest_dir_path, false); expect(await promisify(readdir)(contest_dir_path)).toEqual([".gitignore"]); expect(await promisify(readFile)(resolve(contest_dir_path, ".gitignore"), "utf-8")).toEqual(".git/"); expect(process.cwd()).toEqual(DUMMY_WORKING_DIRECTORY_PATH); mock.restore(); }); test("exec command", async () => { // mock console.error to avoid https://github.com/tschaub/mock-fs/issues/234 const spy_console_log = jest.spyOn(console, "log").mockImplementation(() => null); const spy_console_error = jest.spyOn(console, "error").mockImplementation(() => null); const spy_exec = jest.spyOn(child_process, "exec"); mock({ [DUMMY_WORKING_DIRECTORY_PATH]: { [dummy_contest.id]: {} } }); // cd to (mocked) current directory process.chdir(DUMMY_WORKING_DIRECTORY_PATH); expect(process.cwd()).toEqual(DUMMY_WORKING_DIRECTORY_PATH); const template02 = {name: "template02", contest: {cmd: "echo $CONTEST_ID"}, task: mock_template_cpp.task}; const contest_dir_path = resolve(DUMMY_WORKING_DIRECTORY_PATH, dummy_contest.id); await template.installContestTemplate(dummy_contest, template02, contest_dir_path, true); mock.restore(); expect(spy_exec).toBeCalledTimes(1); const test_env = { TEMPLATE_DIR: resolve(DUMMY_CONFIG_DIRECTORY_PATH, "template02"), CONTEST_DIR: contest_dir_path, CONTEST_ID: dummy_contest.id }; expect(spy_exec.mock.calls[0][0]).toEqual("echo $CONTEST_ID"); expect(spy_exec.mock.calls[0][1]).toEqual({env: expect.objectContaining(test_env)}); spy_console_log.mockRestore(); spy_console_error.mockRestore(); spy_exec.mockRestore(); }); }); describe("installTaskTemplate", () => { test("overwrite static files", async () => { // mock console.error to avoid https://github.com/tschaub/mock-fs/issues/234 const spy_console_log = jest.spyOn(console, "log").mockImplementation(() => null); const spy_console_error = jest.spyOn(console, "error").mockImplementation(() => null); mock({ [DUMMY_CONFIG_DIRECTORY_PATH]: { "template02": { "template.json": mock_template_ts_json, "gitignore": ".git/", "main.ts": "/* do nothing */", "foo.txt": "FOO", "bar.txt": "BAR", "baz.txt": "BAZ" } }, [DUMMY_WORKING_DIRECTORY_PATH]: { [dummy_contest.id]: { [dummy_task01.id]: { "foo.txt": "foo", "bar.txt": "bar" } }, ".gitignore": "this .gitignore will be overwritten by installing of the template" } }); // cd to (mocked) current directory process.chdir(DUMMY_WORKING_DIRECTORY_PATH); expect(process.cwd()).toEqual(DUMMY_WORKING_DIRECTORY_PATH); const template02 = await template.getTemplate("template02"); expect(await template02).toEqual({name: "template02", ...mock_template_ts}); const contest_dir_path = resolve(DUMMY_WORKING_DIRECTORY_PATH, dummy_contest.id); const task_dir_path = resolve(DUMMY_WORKING_DIRECTORY_PATH, dummy_contest.id, dummy_task01.id); expect((await promisify(readdir)(task_dir_path)).sort()).toEqual(["foo.txt", "bar.txt"].sort()); expect(await promisify(readFile)(resolve(task_dir_path, "foo.txt"), "utf-8")).toEqual("foo"); expect(await promisify(readFile)(resolve(task_dir_path, "bar.txt"), "utf-8")).toEqual("bar"); await template.installTaskTemplate({task: dummy_task01, contest: dummy_contest, index: 0, template: template02}, {contest: contest_dir_path, task: task_dir_path}); expect((await promisify(readdir)(task_dir_path)).sort()).toEqual(["aic987_a.ts", "foo.txt", "bar.txt", "a_aic987_a", "AIC987-1.txt"].sort()); expect(await promisify(readFile)(resolve(task_dir_path, "aic987_a.ts"), "utf-8")).toEqual("/* do nothing */"); expect(await promisify(readFile)(resolve(task_dir_path, "foo.txt"), "utf-8")).toEqual("FOO"); expect(await promisify(readFile)(resolve(task_dir_path, "bar.txt"), "utf-8")).toEqual("bar"); expect(await promisify(readFile)(resolve(task_dir_path, "a_aic987_a"), "utf-8")).toEqual("BAR"); expect(await promisify(readFile)(resolve(task_dir_path, "AIC987-1.txt"), "utf-8")).toEqual("BAZ"); expect(process.cwd()).toEqual(DUMMY_WORKING_DIRECTORY_PATH); mock.restore(); spy_console_log.mockRestore(); spy_console_error.mockRestore(); }); }); });
the_stack
import Web3 from 'web3'; import RewardPoolABI from '../../contracts/abi/v0.8.7/reward-pool'; import { Contract, ContractOptions } from 'web3-eth-contract'; import { getAddress } from '../../contracts/addresses'; import { AbiItem, fromWei, toWei } from 'web3-utils'; import { signRewardSafe, signSafeTx, createEIP1271VerifyingData } from '../utils/signing-utils'; import { getSDK } from '../version-resolver'; import { getConstant, ZERO_ADDRESS } from '../constants'; import BN from 'bn.js'; import ERC20ABI from '../../contracts/abi/erc-20'; import ERC677ABI from '../../contracts/abi/erc-677'; import { gasEstimate, executeTransaction, getNextNonceFromEstimate, Operation } from '../utils/safe-utils'; import { isTransactionHash, TransactionOptions, waitForSubgraphIndexWithTxnReceipt } from '../utils/general-utils'; import { TransactionReceipt } from 'web3-core'; import GnosisSafeABI from '../../contracts/abi/gnosis-safe'; export interface Proof { rootHash: string; paymentCycle: number; tokenAddress: string; payee: string; proofArray: string[]; timestamp: string; blockNumber: number; rewardProgramId: string; amount: BN; leaf: string; } export interface Leaf { rewardProgramId: string; paymentCycleNumber: number; validFrom: number; validTo: number; tokenType: number; payee: string; transferData: string; } export interface TokenTransferDetail { token: string; amount: BN; } export interface FullLeaf extends Partial<TokenTransferDetail>, Leaf {} const DEFAULT_PAGE_SIZE = 1000000; export interface RewardTokenBalance { rewardProgramId?: string; tokenAddress: string; balance: BN; } export type WithSymbol<T extends Proof | RewardTokenBalance> = T & { tokenSymbol: string; }; export default class RewardPool { private rewardPool: Contract | undefined; constructor(private layer2Web3: Web3) {} async getCurrentPaymentCycle(): Promise<number> { return 2; } async getBalance(address: string, rewardProgramId?: string, tokenAddress?: string): Promise<BN> { const unclaimedProofs = await this.getProofs(address, rewardProgramId, tokenAddress, false); return unclaimedProofs.reduce((total, { amount }) => { return total.add(amount); }, new BN('0')); } async isClaimed(leaf: string): Promise<boolean> { return (await this.getRewardPool()).methods.claimed(leaf).call(); } async isValid(leaf: string, proofArray: string[]): Promise<boolean> { return (await this.getRewardPool()).methods.valid(leaf, proofArray).call(); } // TOTAL balance of reward pool -- cumulative across reward program async getBalanceForPool(tokenAddress: string): Promise<string> { let rewardPoolAddress = await getAddress('rewardPool', this.layer2Web3); const tokenContract = new this.layer2Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress); return await tokenContract.methods.balanceOf(rewardPoolAddress).call(); } async rewardTokensAvailable(rewardProgramId?: string, address?: string): Promise<string[]> { let tallyServiceURL = await getConstant('tallyServiceURL', this.layer2Web3); let url = new URL(`${tallyServiceURL}/reward-tokens/`); if (rewardProgramId) { url.searchParams.append('reward_program_id', rewardProgramId); } if (address) { url.searchParams.append('payee', address); } let options = { method: 'GET', headers: { 'Content-Type': 'application/json', }, }; let response = await fetch(url.toString(), options); if (!response?.ok) { throw new Error(await response.text()); } let json = await response.json(); return json['tokenAddresses']; } async getProofs( address: string, rewardProgramId?: string, tokenAddress?: string, knownClaimed?: boolean, offset?: number, limit?: number ): Promise<WithSymbol<Proof>[]> { let tallyServiceURL = await getConstant('tallyServiceURL', this.layer2Web3); let url = new URL(`${tallyServiceURL}/merkle-proofs/${address}`); if (rewardProgramId) { url.searchParams.append('reward_program_id', rewardProgramId); } if (tokenAddress) { url.searchParams.append('token_address', tokenAddress); } let knownClaimedStr = knownClaimed ? knownClaimed.toString() : 'false'; url.searchParams.append('known_claimed', knownClaimedStr); if (offset) { url.searchParams.append('offset', offset.toString()); } url.searchParams.append('limit', limit ? limit.toString() : DEFAULT_PAGE_SIZE.toString()); let options = { method: 'GET', headers: { 'Content-Type': 'application/json', }, }; let response = await fetch(url.toString(), options); let json = await response.json(); if (!response?.ok) { throw new Error(await response.text()); } return json['results'].map((o: any) => { return { ...o, amount: new BN(o.amount.toString()), }; }); } async rewardTokenBalance( address: string, tokenAddress: string, rewardProgramId?: string ): Promise<RewardTokenBalance> { let balance = await this.getBalance(address, rewardProgramId, tokenAddress); return { rewardProgramId, tokenAddress, balance, }; } async rewardTokenBalances(address: string, rewardProgramId?: string): Promise<WithSymbol<RewardTokenBalance>[]> { const unclaimedProofs = await this.getProofs(address, rewardProgramId, undefined, false); let tokenBalances = unclaimedProofs.map((o: Proof) => { return { tokenAddress: o.tokenAddress, rewardProgramId: o.rewardProgramId, balance: new BN(o.amount), }; }); return this.addTokenSymbol(aggregateBalance(tokenBalances)); } async addRewardTokens(txnHash: string): Promise<TransactionReceipt>; async addRewardTokens( safeAddress: string, rewardProgramId: string, tokenAddress: string, amount: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async addRewardTokens( safeAddressOrTxnHash: string, rewardProgramId?: string, tokenAddress?: string, amount?: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (isTransactionHash(safeAddressOrTxnHash)) { let txnHash = safeAddressOrTxnHash; return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash); } let safeAddress = safeAddressOrTxnHash; if (!rewardProgramId) { throw new Error('rewardProgramId must be provided'); } if (!tokenAddress) { throw new Error('tokenAddress must be provided'); } if (!amount) { throw new Error('amount must be provided'); } let rewardManager = await getSDK('RewardManager', this.layer2Web3); if (!(await rewardManager.isRewardProgram(rewardProgramId))) { throw new Error('reward program does not exist'); } let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0]; let token = new this.layer2Web3.eth.Contract(ERC677ABI as AbiItem[], tokenAddress); let symbol = await token.methods.symbol().call(); let balance = new BN(await token.methods.balanceOf(safeAddress).call()); let weiAmount = new BN(toWei(amount)); if (balance.lt(weiAmount)) { throw new Error( `Safe does not have enough balance add reward tokens. The reward token ${tokenAddress} balance of the safe ${safeAddress} is ${fromWei( balance )}, the total amount necessary to add reward tokens is ${fromWei(weiAmount)} ${symbol} + a small amount for gas` ); } let payload = await this.getAddRewardTokensPayload(rewardProgramId, tokenAddress, weiAmount); let estimate = await gasEstimate( this.layer2Web3, safeAddress, tokenAddress, '0', payload, Operation.CALL, tokenAddress ); let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; if (nonce == null) { nonce = getNextNonceFromEstimate(estimate); if (typeof onNonce === 'function') { onNonce(nonce); } } let gnosisTxn = await executeTransaction( this.layer2Web3, safeAddress, tokenAddress, payload, Operation.CALL, estimate, nonce, await signSafeTx(this.layer2Web3, safeAddress, tokenAddress, payload, estimate, nonce, from) ); if (typeof onTxnHash === 'function') { await onTxnHash(gnosisTxn.ethereumTx.txHash); } return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, gnosisTxn.ethereumTx.txHash); } async claim(txnHash: string): Promise<TransactionReceipt>; async claim( safeAddress: string, leaf: string, proofArray: string[], acceptPartialClaim?: boolean, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async claim( safeAddressOrTxnHash: string, leaf?: string, proofArray?: string[], acceptPartialClaim?: boolean, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (isTransactionHash(safeAddressOrTxnHash)) { let txnHash = safeAddressOrTxnHash; return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash); } let safeAddress = safeAddressOrTxnHash; if (!proofArray) { //proofArray can be empty e.g reward only for single rewardee throw new Error('proof must be provided'); } if (!leaf) { throw new Error('leaf must be provided'); } let { rewardProgramId, payee, token, amount }: FullLeaf = this.decodeLeaf(leaf) as FullLeaf; if (!rewardProgramId) { throw new Error('rewardProgramId must be provided'); } if (!token) { throw new Error('token must be provided'); } if (!amount) { throw new Error('amount must be provided'); } let rewardManager = await getSDK('RewardManager', this.layer2Web3); if (!(await rewardManager.isRewardProgram(rewardProgramId))) { throw new Error('reward program does not exist'); } if (!(await rewardManager.isValidRewardSafe(safeAddress, rewardProgramId))) { throw new Error('reward safe is not valid'); } let rewardSafeOwner = await rewardManager.getRewardSafeOwner(safeAddress); if (rewardSafeOwner != payee) { throw new Error('payee is not owner of the reward safe'); } if (!(await this.isValid(leaf, proofArray))) { throw new Error('proof is not valid'); } if (await this.isClaimed(leaf)) { throw new Error('reward has been claimed'); } let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0]; let weiAmount = new BN(amount); let rewardPoolBalanceForRewardProgram = (await this.balance(rewardProgramId, token)).balance; if (weiAmount.gt(rewardPoolBalanceForRewardProgram)) { if (acceptPartialClaim) { // acceptPartialClaim means: if reward pool balance is less than amount, // rewardee is willing sacrifice full reward and accept the entire reward pool balance weiAmount = rewardPoolBalanceForRewardProgram; } else { throw new Error( `Insufficient funds inside reward pool for reward program. The reward program ${rewardProgramId} has balance equals ${fromWei( rewardPoolBalanceForRewardProgram.toString() )} but user is asking for ${amount}` ); } } if (!(rewardSafeOwner == from)) { throw new Error( `Reward safe owner is NOT the signer of transaction. The owner of reward safe ${safeAddress} is ${rewardSafeOwner}, but the signer is ${from}` ); } let rewardPoolAddress = await getAddress('rewardPool', this.layer2Web3); let payload = (await this.getRewardPool()).methods.claim(leaf, proofArray, acceptPartialClaim).encodeABI(); let estimate = await gasEstimate( this.layer2Web3, safeAddress, rewardPoolAddress, '0', payload, Operation.CALL, token ); let gasCost = new BN(estimate.safeTxGas).add(new BN(estimate.baseGas)).mul(new BN(estimate.gasPrice)); if (weiAmount.lt(gasCost)) { throw new Error( `Rewards claimed does not have enough to cover the gas cost. The amount to be claimed is ${fromWei( weiAmount )}, the gas cost is ${fromWei(gasCost)}` ); } let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; if (nonce == null) { nonce = getNextNonceFromEstimate(estimate); if (typeof onNonce === 'function') { onNonce(nonce); } } let fullSignature = await signRewardSafe( this.layer2Web3, rewardPoolAddress, 0, payload, Operation.CALL, estimate, token, ZERO_ADDRESS, nonce, rewardSafeOwner, safeAddress, await getAddress('rewardManager', this.layer2Web3) ); let eip1271Data = createEIP1271VerifyingData( this.layer2Web3, rewardPoolAddress, '0', payload, Operation.CALL.toString(), estimate.safeTxGas, estimate.baseGas, estimate.gasPrice, token, ZERO_ADDRESS, nonce.toString() ); let gnosisTxn = await executeTransaction( this.layer2Web3, safeAddress, rewardPoolAddress, payload, Operation.CALL, estimate, nonce, fullSignature, eip1271Data ); if (typeof onTxnHash === 'function') { await onTxnHash(gnosisTxn.ethereumTx.txHash); } return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, gnosisTxn.ethereumTx.txHash); } async recoverTokens(txnHash: string): Promise<TransactionReceipt>; async recoverTokens( safeAddress: string, rewardProgramId: string, tokenAddress: string, amount?: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async recoverTokens( safeAddressOrTxnHash: string, rewardProgramId?: string, tokenAddress?: string, amount?: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (isTransactionHash(safeAddressOrTxnHash)) { let txnHash = safeAddressOrTxnHash; return waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash); } let safeAddress = safeAddressOrTxnHash; if (!rewardProgramId) { throw new Error('rewardProgramId is required'); } if (!tokenAddress) { throw new Error('tokenAddress is required'); } let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; let from = contractOptions?.from ?? (await this.layer2Web3.eth.getAccounts())[0]; let rewardPoolAddress = await getAddress('rewardPool', this.layer2Web3); let rewardPoolBalanceForRewardProgram = (await this.balance(rewardProgramId, tokenAddress)).balance; let rewardManager = await getSDK('RewardManager', this.layer2Web3); if (!(await rewardManager.isRewardProgram(rewardProgramId))) { throw new Error('reward program does not exist'); } if (!((await rewardManager.getRewardProgramAdmin(rewardProgramId)) == from)) { throw new Error('signer is not reward program admin'); } let safe = new this.layer2Web3.eth.Contract(GnosisSafeABI as AbiItem[], safeAddress); const safeOwner = (await safe.methods.getOwners().call())[0]; if (!(safeOwner == from)) { throw new Error('signer is not safe owner'); } let weiAmount = amount ? new BN(toWei(amount)) : rewardPoolBalanceForRewardProgram; if (rewardPoolBalanceForRewardProgram.lt(weiAmount)) { throw new Error( `Insufficient funds inside reward pool for reward program. The amount to be claimed is ${amount}, but the balance is the reward pool is ${fromWei(rewardPoolBalanceForRewardProgram).toString()}` ); } let payload = (await this.getRewardPool()).methods .recoverTokens(rewardProgramId, tokenAddress, weiAmount) .encodeABI(); let estimate = await gasEstimate( this.layer2Web3, safeAddress, rewardPoolAddress, '0', payload, Operation.CALL, tokenAddress ); let gasCost = new BN(estimate.safeTxGas).add(new BN(estimate.baseGas)).mul(new BN(estimate.gasPrice)); if (weiAmount.lt(gasCost)) { throw new Error( `Funds recovered does not have enough to cover the gas cost. The amount to be recovered is ${amount}, the gas cost is ${fromWei( gasCost )}` ); } if (nonce == null) { nonce = getNextNonceFromEstimate(estimate); if (typeof onNonce === 'function') { onNonce(nonce); } } let gnosisResult = await executeTransaction( this.layer2Web3, safeAddress, rewardPoolAddress, payload, Operation.CALL, estimate, nonce, await signSafeTx(this.layer2Web3, safeAddress, rewardPoolAddress, payload, estimate, nonce, from) ); let txnHash = gnosisResult.ethereumTx.txHash; if (typeof onTxnHash === 'function') { await onTxnHash(txnHash); } return await waitForSubgraphIndexWithTxnReceipt(this.layer2Web3, txnHash); } async balances(rewardProgramId: string): Promise<WithSymbol<RewardTokenBalance>[]> { const tokensAvailable = await this.rewardTokensAvailable(rewardProgramId); let promises = tokensAvailable.map((tokenAddress) => { return this.balance(rewardProgramId, tokenAddress); }); let rewardTokenBalance = await Promise.all(promises); return this.addTokenSymbol(rewardTokenBalance); } async balance(rewardProgramId: string, tokenAddress: string): Promise<RewardTokenBalance> { let balance: string = await (await this.getRewardPool()).methods .rewardBalance(rewardProgramId, tokenAddress) .call(); return { rewardProgramId, tokenAddress, balance: new BN(balance), }; } async address(): Promise<string> { return await getAddress('rewardPool', this.layer2Web3); } async addTokenSymbol<T extends Proof | RewardTokenBalance>(arrWithTokenAddress: T[]): Promise<WithSymbol<T>[]> { const tokenAddresses = [...new Set(arrWithTokenAddress.map((item) => item.tokenAddress))]; const tokenMapping = await this.tokenSymbolMapping(tokenAddresses); return arrWithTokenAddress.map((o) => { return { ...o, tokenSymbol: tokenMapping[o.tokenAddress], }; }); } async tokenSymbolMapping(tokenAddresses: string[]): Promise<any> { let o = {}; let assets = await getSDK('Assets', this.layer2Web3); await Promise.all( tokenAddresses.map(async (tokenAddress: string) => { let { symbol } = await assets.getTokenInfo(tokenAddress); o = { ...o, [tokenAddress]: symbol, }; }) ); return o; } private decodeLeaf(leaf: string): FullLeaf { let outerObj = this.layer2Web3.eth.abi.decodeParameters( [ { type: 'address', name: 'rewardProgramId' }, { type: 'uint256', name: 'paymentCycleNumber' }, { type: 'uint256', name: 'validFrom' }, { type: 'uint256', name: 'validTo' }, { type: 'uint256', name: 'tokenType' }, { type: 'address', name: 'payee' }, { type: 'bytes', name: 'transferData' }, ], leaf ) as Leaf; let transferDataObj = this.decodeTransferData(outerObj.tokenType, outerObj.transferData); if (this.hasTokenTransferDetail(transferDataObj)) { return { ...outerObj, ...transferDataObj }; } else { return outerObj; } } private hasTokenTransferDetail(o: any): o is TokenTransferDetail { return 'token' in o && 'amount' in o; } private decodeTransferData(tokenType: number, transferData: string): TokenTransferDetail | string { if (tokenType == 0) { // Default data return transferData; } else if ( // ERC677 / ERC20 tokenType == 1 || // ERC721 (NFT) tokenType == 2 ) { return this.layer2Web3.eth.abi.decodeParameters( [ { type: 'address', name: 'token' }, { type: 'uint256', name: 'amount' }, ], transferData ) as TokenTransferDetail; } else { throw new Error('Unknown tokenType'); } } private async getAddRewardTokensPayload(rewardProgramId: string, tokenAddress: string, amount: BN): Promise<string> { let token = new this.layer2Web3.eth.Contract(ERC677ABI as AbiItem[], tokenAddress); let rewardPoolAddress = await getAddress('rewardPool', this.layer2Web3); let data = this.layer2Web3.eth.abi.encodeParameters(['address'], [rewardProgramId]); return token.methods.transferAndCall(rewardPoolAddress, amount, data).encodeABI(); } private async getRewardPool(): Promise<Contract> { if (this.rewardPool) { return this.rewardPool; } this.rewardPool = new this.layer2Web3.eth.Contract( RewardPoolABI as AbiItem[], await getAddress('rewardPool', this.layer2Web3) ); return this.rewardPool; } } const aggregateBalance = (arr: RewardTokenBalance[]): RewardTokenBalance[] => { let output: RewardTokenBalance[] = []; arr.forEach(function (item) { let existing = output.filter(function (v) { return v.rewardProgramId == item.rewardProgramId && v.tokenAddress == item.tokenAddress; }); if (existing.length) { var existingIndex = output.indexOf(existing[0]); output[existingIndex].balance = output[existingIndex].balance.add(item.balance); } else { output.push(item); } }); return output; };
the_stack
import { ArgumentNullError, ConnectionMessage, ConnectionOpenResponse, ConnectionState, CreateNoDashGuid, Deferred, Events, IAudioSource, IAudioStreamNode, IConnection, IDetachable, IEventSource, IStreamChunk, MessageType, PlatformEvent, Promise, PromiseHelper, PromiseResult, } from "../../common/Exports"; import { AuthInfo, IAuthentication } from "./IAuthentication"; import { IConnectionFactory } from "./IConnectionFactory"; import { ConnectingToServiceEvent, ListeningStartedEvent, RecognitionCompletionStatus, RecognitionEndedEvent, RecognitionStartedEvent, RecognitionTriggeredEvent, SpeechDetailedPhraseEvent, SpeechEndDetectedEvent, SpeechFragmentEvent, SpeechHypothesisEvent, SpeechRecognitionEvent, SpeechRecognitionResultEvent, SpeechSimplePhraseEvent, SpeechStartDetectedEvent, } from "./RecognitionEvents"; import { RecognitionMode, RecognizerConfig, SpeechResultFormat } from "./RecognizerConfig"; import { ServiceTelemetryListener } from "./ServiceTelemetryListener.Internal"; import { SpeechConnectionMessage } from "./SpeechConnectionMessage.Internal"; import { IDetailedSpeechPhrase, ISimpleSpeechPhrase, ISpeechEndDetectedResult, ISpeechFragment, ISpeechStartDetectedResult, } from "./SpeechResults"; export class Recognizer { private authentication: IAuthentication; private connectionFactory: IConnectionFactory; private audioSource: IAudioSource; private recognizerConfig: RecognizerConfig; private speechConfigConnectionId: string; private connectionFetchPromise: Promise<IConnection>; private connectionId: string; private authFetchEventId: string; public constructor( authentication: IAuthentication, connectionFactory: IConnectionFactory, audioSource: IAudioSource, recognizerConfig: RecognizerConfig) { if (!authentication) { throw new ArgumentNullError("authentication"); } if (!connectionFactory) { throw new ArgumentNullError("connectionFactory"); } if (!audioSource) { throw new ArgumentNullError("audioSource"); } if (!recognizerConfig) { throw new ArgumentNullError("recognizerConfig"); } this.authentication = authentication; this.connectionFactory = connectionFactory; this.audioSource = audioSource; this.recognizerConfig = recognizerConfig; } public get AudioSource(): IAudioSource { return this.audioSource; } public Recognize = (onEventCallback: (event: SpeechRecognitionEvent) => void, speechContextJson?: string): Promise<boolean> => { const requestSession = new RequestSession(this.audioSource.Id(), onEventCallback); requestSession.ListenForServiceTelemetry(this.audioSource.Events); return this.audioSource .Attach(requestSession.AudioNodeId) .ContinueWithPromise<boolean>((result: PromiseResult<IAudioStreamNode>) => { if (result.IsError) { requestSession.OnAudioSourceAttachCompleted(null, true, result.Error); throw new Error(result.Error); } else { requestSession.OnAudioSourceAttachCompleted(result.Result, false); } const audioNode = result.Result; this.FetchConnection(requestSession) .OnSuccessContinueWith((connection: IConnection) => { const messageRetrievalPromise = this.ReceiveMessage(connection, requestSession); const messageSendPromise = this.SendSpeechConfig(requestSession.RequestId, connection, this.recognizerConfig.SpeechConfig.Serialize()) .OnSuccessContinueWithPromise((_: boolean) => { return this.SendSpeechContext(requestSession.RequestId, connection, speechContextJson) .OnSuccessContinueWithPromise((_: boolean) => { return this.SendAudio(requestSession.RequestId, connection, audioNode, requestSession); }); }); const completionPromise = PromiseHelper.WhenAll([messageRetrievalPromise, messageSendPromise]); completionPromise.On((r: boolean) => { requestSession.Dispose(); this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry()); }, (error: string) => { requestSession.Dispose(error); this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry()); }); return completionPromise; }); return requestSession.CompletionPromise; }); } private FetchConnection = (requestSession: RequestSession, isUnAuthorized: boolean = false): Promise<IConnection> => { if (this.connectionFetchPromise) { if (this.connectionFetchPromise.Result().IsError || this.connectionFetchPromise.Result().Result.State() === ConnectionState.Disconnected) { this.connectionId = null; this.connectionFetchPromise = null; return this.FetchConnection(requestSession); } else { requestSession.OnPreConnectionStart(this.authFetchEventId, this.connectionId); requestSession.OnConnectionEstablishCompleted(200); requestSession.ListenForServiceTelemetry(this.connectionFetchPromise.Result().Result.Events); return this.connectionFetchPromise; } } this.authFetchEventId = CreateNoDashGuid(); this.connectionId = CreateNoDashGuid(); requestSession.OnPreConnectionStart(this.authFetchEventId, this.connectionId); const authPromise = isUnAuthorized ? this.authentication.FetchOnExpiry(this.authFetchEventId) : this.authentication.Fetch(this.authFetchEventId); this.connectionFetchPromise = authPromise .ContinueWithPromise((result: PromiseResult<AuthInfo>) => { if (result.IsError) { requestSession.OnAuthCompleted(true, result.Error); throw new Error(result.Error); } else { requestSession.OnAuthCompleted(false); } const connection = this.connectionFactory.Create(this.recognizerConfig, result.Result, this.connectionId); requestSession.ListenForServiceTelemetry(connection.Events); return connection.Open().OnSuccessContinueWithPromise((response: ConnectionOpenResponse) => { if (response.StatusCode === 200) { requestSession.OnConnectionEstablishCompleted(response.StatusCode); return PromiseHelper.FromResult(connection); } else if (response.StatusCode === 403 && !isUnAuthorized) { return this.FetchConnection(requestSession, true); } else { requestSession.OnConnectionEstablishCompleted(response.StatusCode, response.Reason); return PromiseHelper.FromError<IConnection>(`Unable to contact server. StatusCode: ${response.StatusCode}, Reason: ${response.Reason}`); } }); }); return this.connectionFetchPromise; } private ReceiveMessage = (connection: IConnection, requestSession: RequestSession): Promise<boolean> => { return connection .Read() .OnSuccessContinueWithPromise((message: ConnectionMessage) => { const connectionMessage = SpeechConnectionMessage.FromConnectionMessage(message); if (connectionMessage.RequestId.toLowerCase() === requestSession.RequestId.toLowerCase()) { switch (connectionMessage.Path.toLowerCase()) { case "turn.start": requestSession.OnServiceTurnStartResponse(JSON.parse(connectionMessage.TextBody)); break; case "speech.startDetected": requestSession.OnServiceSpeechStartDetectedResponse(JSON.parse(connectionMessage.TextBody)); break; case "speech.hypothesis": requestSession.OnServiceSpeechHypothesisResponse(JSON.parse(connectionMessage.TextBody)); break; case "speech.fragment": requestSession.OnServiceSpeechFragmentResponse(JSON.parse(connectionMessage.TextBody)); break; case "speech.enddetected": requestSession.OnServiceSpeechEndDetectedResponse(JSON.parse(connectionMessage.TextBody)); break; case "speech.phrase": if (this.recognizerConfig.IsContinuousRecognition) { // For continuous recognition telemetry has to be sent for every phrase as per spec. this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry()); } if (this.recognizerConfig.Format === SpeechResultFormat.Simple) { requestSession.OnServiceSimpleSpeechPhraseResponse(JSON.parse(connectionMessage.TextBody)); } else { requestSession.OnServiceDetailedSpeechPhraseResponse(JSON.parse(connectionMessage.TextBody)); } break; case "turn.end": requestSession.OnServiceTurnEndResponse(); return PromiseHelper.FromResult(true); default: break; } } return this.ReceiveMessage(connection, requestSession); }); } private SendSpeechConfig = (requestId: string, connection: IConnection, speechConfigJson: string) => { if (speechConfigJson && this.connectionId !== this.speechConfigConnectionId) { this.speechConfigConnectionId = this.connectionId; return connection .Send(new SpeechConnectionMessage( MessageType.Text, "speech.config", requestId, "application/json", speechConfigJson)); } return PromiseHelper.FromResult(true); } private SendSpeechContext = (requestId: string, connection: IConnection, speechContextJson: string) => { if (speechContextJson) { return connection .Send(new SpeechConnectionMessage( MessageType.Text, "speech.context", requestId, "application/json", speechContextJson)); } return PromiseHelper.FromResult(true); } private SendTelemetryData = (requestId: string, connection: IConnection, telemetryData: string) => { return connection .Send(new SpeechConnectionMessage( MessageType.Text, "telemetry", requestId, "application/json", telemetryData)); } private SendAudio = ( requestId: string, connection: IConnection, audioStreamNode: IAudioStreamNode, requestSession: RequestSession): Promise<boolean> => { // NOTE: Home-baked promises crash ios safari during the invocation // of the error callback chain (looks like the recursion is way too deep, and // it blows up the stack). The following construct is a stop-gap that does not // bubble the error up the callback chain and hence circumvents this problem. // TODO: rewrite with ES6 promises. const deferred = new Deferred<boolean>(); const readAndUploadCycle = (_: boolean) => { audioStreamNode.Read().On( (audioStreamChunk: IStreamChunk<ArrayBuffer>) => { // we have a new audio chunk to upload. if (requestSession.IsSpeechEnded) { // If service already recognized audio end then dont send any more audio deferred.Resolve(true); return; } const payload = (audioStreamChunk.IsEnd) ? null : audioStreamChunk.Buffer; const uploaded = connection.Send( new SpeechConnectionMessage( MessageType.Binary, "audio", requestId, null, payload)); if (!audioStreamChunk.IsEnd) { uploaded.OnSuccessContinueWith(readAndUploadCycle); } else { // the audio stream has been closed, no need to schedule next // read-upload cycle. deferred.Resolve(true); } }, (error: string) => { if (requestSession.IsSpeechEnded) { // For whatever reason, Reject is used to remove queue subscribers inside // the Queue.DrainAndDispose invoked from DetachAudioNode down blow, which // means that sometimes things can be rejected in normal circumstances, without // any errors. deferred.Resolve(true); // TODO: remove the argument, it's is completely meaningless. } else { // Only reject, if there was a proper error. deferred.Reject(error); } }); }; readAndUploadCycle(true); return deferred.Promise(); } } // tslint:disable-next-line:max-classes-per-file class RequestSession { private isDisposed: boolean = false; private serviceTelemetryListener: ServiceTelemetryListener; private detachables: IDetachable[] = new Array<IDetachable>(); private requestId: string; private audioSourceId: string; private audioNodeId: string; private audioNode: IAudioStreamNode; private authFetchEventId: string; private connectionId: string; private serviceTag: string; private isAudioNodeDetached: boolean = false; private isCompleted: boolean = false; private onEventCallback: (event: SpeechRecognitionEvent) => void; private requestCompletionDeferral: Deferred<boolean>; constructor(audioSourceId: string, onEventCallback: (event: SpeechRecognitionEvent) => void) { this.audioSourceId = audioSourceId; this.onEventCallback = onEventCallback; this.requestId = CreateNoDashGuid(); this.audioNodeId = CreateNoDashGuid(); this.requestCompletionDeferral = new Deferred<boolean>(); this.serviceTelemetryListener = new ServiceTelemetryListener(this.requestId, this.audioSourceId, this.audioNodeId); this.OnEvent(new RecognitionTriggeredEvent(this.RequestId, this.audioSourceId, this.audioNodeId)); } public get RequestId(): string { return this.requestId; } public get AudioNodeId(): string { return this.audioNodeId; } public get CompletionPromise(): Promise<boolean> { return this.requestCompletionDeferral.Promise(); } public get IsSpeechEnded(): boolean { return this.isAudioNodeDetached; } public get IsCompleted(): boolean { return this.isCompleted; } public ListenForServiceTelemetry(eventSource: IEventSource<PlatformEvent>): void { this.detachables.push(eventSource.AttachListener(this.serviceTelemetryListener)); } public OnAudioSourceAttachCompleted = (audioNode: IAudioStreamNode, isError: boolean, error?: string): void => { this.audioNode = audioNode; if (isError) { this.OnComplete(RecognitionCompletionStatus.AudioSourceError, error); } else { this.OnEvent(new ListeningStartedEvent(this.requestId, this.audioSourceId, this.audioNodeId)); } } public OnPreConnectionStart = (authFetchEventId: string, connectionId: string): void => { this.authFetchEventId = authFetchEventId; this.connectionId = connectionId; this.OnEvent(new ConnectingToServiceEvent(this.requestId, this.authFetchEventId, this.connectionId)); } public OnAuthCompleted = (isError: boolean, error?: string): void => { if (isError) { this.OnComplete(RecognitionCompletionStatus.AuthTokenFetchError, error); } } public OnConnectionEstablishCompleted = (statusCode: number, reason?: string): void => { if (statusCode === 200) { this.OnEvent(new RecognitionStartedEvent(this.RequestId, this.audioSourceId, this.audioNodeId, this.authFetchEventId, this.connectionId)); return; } else if (statusCode === 403) { this.OnComplete(RecognitionCompletionStatus.UnAuthorized, reason); } else { this.OnComplete(RecognitionCompletionStatus.ConnectError, reason); } } public OnServiceTurnStartResponse = (response: ITurnStartResponse): void => { if (response && response.context && response.context.serviceTag) { this.serviceTag = response.context.serviceTag; } } public OnServiceSpeechStartDetectedResponse = (result: ISpeechStartDetectedResult): void => { this.OnEvent(new SpeechStartDetectedEvent(this.RequestId, result)); } public OnServiceSpeechHypothesisResponse = (result: ISpeechFragment): void => { this.OnEvent(new SpeechHypothesisEvent(this.RequestId, result)); } public OnServiceSpeechFragmentResponse = (result: ISpeechFragment): void => { this.OnEvent(new SpeechFragmentEvent(this.RequestId, result)); } public OnServiceSpeechEndDetectedResponse = (result: ISpeechEndDetectedResult): void => { this.DetachAudioNode(); this.OnEvent(new SpeechEndDetectedEvent(this.RequestId, result)); } public OnServiceSimpleSpeechPhraseResponse = (result: ISimpleSpeechPhrase): void => { this.OnEvent(new SpeechSimplePhraseEvent(this.RequestId, result)); } public OnServiceDetailedSpeechPhraseResponse = (result: IDetailedSpeechPhrase): void => { this.OnEvent(new SpeechDetailedPhraseEvent(this.RequestId, result)); } public OnServiceTurnEndResponse = (): void => { this.OnComplete(RecognitionCompletionStatus.Success); } public OnConnectionError = (error: string): void => { this.OnComplete(RecognitionCompletionStatus.UnknownError, error); } public Dispose = (error?: string): void => { if (!this.isDisposed) { // we should have completed by now. If we did not its an unknown error. this.OnComplete(RecognitionCompletionStatus.UnknownError, error); this.isDisposed = true; for (const detachable of this.detachables) { detachable.Detach(); } this.serviceTelemetryListener.Dispose(); } } public GetTelemetry = (): string => { return this.serviceTelemetryListener.GetTelemetry(); } private OnComplete = (status: RecognitionCompletionStatus, error?: string): void => { if (!this.isCompleted) { this.isCompleted = true; this.DetachAudioNode(); this.OnEvent(new RecognitionEndedEvent(this.RequestId, this.audioSourceId, this.audioNodeId, this.authFetchEventId, this.connectionId, this.serviceTag, status, error ? error : "")); } } private DetachAudioNode = (): void => { if (!this.isAudioNodeDetached) { this.isAudioNodeDetached = true; if (this.audioNode) { this.audioNode.Detach(); } } } private OnEvent = (event: SpeechRecognitionEvent): void => { this.serviceTelemetryListener.OnEvent(event); Events.Instance.OnEvent(event); if (this.onEventCallback) { this.onEventCallback(event); } } } interface ITurnStartResponse { context: ITurnStartContext; } interface ITurnStartContext { serviceTag: string; }
the_stack
import { crypto } from "bitcoinjs-lib"; import { pointCompress, pointAddScalar } from "tiny-secp256k1"; import semver from "semver"; import { getXpubComponents, hardenedPathOf, pathArrayToString, pathStringToArray, pubkeyFromXpub, } from "./bip32"; import { BufferReader, BufferWriter } from "./buffertools"; import type { CreateTransactionArg } from "./createTransaction"; import type { AddressFormat } from "./getWalletPublicKey"; import { hashPublicKey } from "./hashPublicKey"; import { AppClient as Client } from "./newops/appClient"; import { createKey, WalletPolicy } from "./newops/policy"; import { extract } from "./newops/psbtExtractor"; import { finalize } from "./newops/psbtFinalizer"; import { psbtIn, PsbtV2 } from "./newops/psbtv2"; import { serializeTransaction } from "./serializeTransaction"; import type { Transaction } from "./types"; import { HASH_SIZE, OP_CHECKSIG, OP_DUP, OP_EQUAL, OP_EQUALVERIFY, OP_HASH160, } from "./constants"; import { AppAndVersion } from "./getAppAndVersion"; const newSupportedApps = ["Bitcoin", "Bitcoin Test"]; export function canSupportApp(appAndVersion: AppAndVersion): boolean { return ( newSupportedApps.includes(appAndVersion.name) && semver.major(appAndVersion.version) >= 2 ); } /** * This class implements the same interface as BtcOld (formerly * named Btc), but interacts with Bitcoin hardware app version 2+ * which uses a totally new APDU protocol. This new * protocol is documented at * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md * * Since the interface must remain compatible with BtcOld, the methods * of this class are quite clunky, because it needs to adapt legacy * input data into the PSBT process. In the future, a new interface should * be developed that exposes PSBT to the outer world, which would render * a much cleaner implementation. */ export default class BtcNew { constructor(private client: Client) {} /** * This is a new method that allow users to get an xpub at a standard path. * Standard paths are described at * https://github.com/LedgerHQ/app-bitcoin-new/blob/master/doc/bitcoin.md#description * * This boils down to paths (N=0 for Bitcoin, N=1 for Testnet): * M/44'/N'/x'/** * M/48'/N'/x'/y'/** * M/49'/N'/x'/** * M/84'/N'/x'/** * M/86'/N'/x'/** * * The method was added because of added security in the hardware app v2+. The * new hardware app will allow export of any xpub up to and including the * deepest hardened key of standard derivation paths, whereas the old app * would allow export of any key. * * This caused an issue for callers of this class, who only had * getWalletPublicKey() to call which means they have to constuct xpub * themselves: * * Suppose a user of this class wants to create an account xpub on a standard * path, M/44'/0'/Z'. The user must get the parent key fingerprint (see BIP32) * by requesting the parent key M/44'/0'. The new app won't allow that, because * it only allows exporting deepest level hardened path. So the options are to * allow requesting M/44'/0' from the app, or to add a new function * "getWalletXpub". * * We opted for adding a new function, which can greatly simplify client code. */ async getWalletXpub({ path, xpubVersion, }: { path: string; xpubVersion: number; }): Promise<string> { const pathElements: number[] = pathStringToArray(path); const xpub = await this.client.getExtendedPubkey(false, pathElements); const xpubComponents = getXpubComponents(xpub); if (xpubComponents.version != xpubVersion) { throw new Error( `Expected xpub version ${xpubVersion} doesn't match the xpub version from the device ${xpubComponents.version}` ); } return xpub; } /** * This method returns a public key, a bitcoin address, and and a chaincode * for a specific derivation path. * * Limitation: If the path is not a leaf node of a standard path, the address * will be the empty string "", see this.getWalletAddress() for details. */ async getWalletPublicKey( path: string, opts?: { verify?: boolean; format?: AddressFormat; } ): Promise<{ publicKey: string; bitcoinAddress: string; chainCode: string; }> { const pathElements: number[] = pathStringToArray(path); const xpub = await this.client.getExtendedPubkey(false, pathElements); const display = opts?.verify ?? false; const address = await this.getWalletAddress( pathElements, accountTypeFrom(opts?.format ?? "legacy"), display ); const components = getXpubComponents(xpub); const uncompressedPubkey = Buffer.from( pointCompress(components.pubkey, false) ); return { publicKey: uncompressedPubkey.toString("hex"), bitcoinAddress: address, chainCode: components.chaincode.toString("hex"), }; } /** * Get an address for the specified path. * * If display is true, we must get the address from the device, which would require * us to determine WalletPolicy. This requires two *extra* queries to the device, one * for the account xpub and one for master key fingerprint. * * If display is false we *could* generate the address ourselves, but chose to * get it from the device to save development time. However, it shouldn't take * too much time to implement local address generation. * * Moreover, if the path is not for a leaf, ie accountPath+/X/Y, there is no * way to get the address from the device. In this case we have to create it * ourselves, but we don't at this time, and instead return an empty ("") address. */ private async getWalletAddress( pathElements: number[], accountType: AccountType, display: boolean ): Promise<string> { const accountPath = hardenedPathOf(pathElements); if (accountPath.length + 2 != pathElements.length) { return ""; } const accountXpub = await this.client.getExtendedPubkey(false, accountPath); const masterFingerprint = await this.client.getMasterFingerprint(); const policy = new WalletPolicy( accountType, createKey(masterFingerprint, accountPath, accountXpub) ); const changeAndIndex = pathElements.slice(-2, pathElements.length); return this.client.getWalletAddress( policy, Buffer.alloc(32, 0), changeAndIndex[0], changeAndIndex[1], display ); } /** * Build and sign a transaction. See Btc.createPaymentTransactionNew for * details on how to use this method. * * This method will convert the legacy arguments, CreateTransactionArg, into * a psbt which is finally signed and finalized, and the extracted fully signed * transaction is returned. */ async createPaymentTransactionNew( arg: CreateTransactionArg ): Promise<string> { if (arg.inputs.length == 0) { throw Error("No inputs"); } const psbt = new PsbtV2(); const accountType = accountTypeFromArg(arg); if (arg.lockTime) { // The signer will assume locktime 0 if unset psbt.setGlobalFallbackLocktime(arg.lockTime); } psbt.setGlobalInputCount(arg.inputs.length); psbt.setGlobalPsbtVersion(2); psbt.setGlobalTxVersion(2); // The master fingerprint is needed when adding BIP32 derivation paths on // the psbt. const masterFp = await this.client.getMasterFingerprint(); let accountXpub = ""; let accountPath: number[] = []; for (let i = 0; i < arg.inputs.length; i++) { const pathElems: number[] = pathStringToArray(arg.associatedKeysets[i]); if (accountXpub == "") { // We assume all inputs belong to the same account so we set // the account xpub and path based on the first input. accountPath = pathElems.slice(0, -2); accountXpub = await this.client.getExtendedPubkey(false, accountPath); } await this.setInput( psbt, i, arg.inputs[i], pathElems, accountType, masterFp ); } const outputsConcat = Buffer.from(arg.outputScriptHex, "hex"); const outputsBufferReader = new BufferReader(outputsConcat); const outputCount = outputsBufferReader.readVarInt(); psbt.setGlobalOutputCount(outputCount); const changeData = await this.outputScriptAt( accountPath, accountType, arg.changePath ); // If the caller supplied a changePath, we must make sure there actually is // a change output. If no change output found, we'll throw an error. let changeFound = !changeData; for (let i = 0; i < outputCount; i++) { const amount = Number(outputsBufferReader.readUInt64()); const outputScript = outputsBufferReader.readVarSlice(); psbt.setOutputAmount(i, amount); psbt.setOutputScript(i, outputScript); // We won't know if we're paying to ourselves, because there's no // information in arg to support multiple "change paths". One exception is // if there are multiple outputs to the change address. const isChange = changeData && outputScript.equals(changeData?.script); if (isChange) { changeFound = true; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const changePath = pathStringToArray(arg.changePath!); const pubkey = changeData.pubkey; if (accountType == AccountType.p2pkh) { psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); } else if (accountType == AccountType.p2wpkh) { psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); } else if (accountType == AccountType.p2wpkhWrapped) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion psbt.setOutputRedeemScript(i, changeData.redeemScript!); psbt.setOutputBip32Derivation(i, pubkey, masterFp, changePath); } else if (accountType == AccountType.p2tr) { psbt.setOutputTapBip32Derivation(i, pubkey, [], masterFp, changePath); } } } if (!changeFound) { throw new Error( "Change script not found among outputs! " + changeData?.script.toString("hex") ); } const key = createKey(masterFp, accountPath, accountXpub); const p = new WalletPolicy(accountType, key); await this.signPsbt(psbt, p); finalize(psbt); const serializedTx = extract(psbt); return serializedTx.toString("hex"); } /** * Calculates an output script along with public key and possible redeemScript * from a path and accountType. The accountPath must be a prefix of path. * * @returns an object with output script (property "script"), redeemScript (if * wrapped p2wpkh), and pubkey at provided path. The values of these three * properties depend on the accountType used. */ private async outputScriptAt( accountPath: number[], accountType: AccountType, path: string | undefined ): Promise< { script: Buffer; redeemScript?: Buffer; pubkey: Buffer } | undefined > { if (!path) return undefined; const pathElems = pathStringToArray(path); // Make sure path is in our account, otherwise something fishy is probably // going on. for (let i = 0; i < accountPath.length; i++) { if (accountPath[i] != pathElems[i]) { throw new Error( `Path ${path} not in account ${pathArrayToString(accountPath)}` ); } } const xpub = await this.client.getExtendedPubkey(false, pathElems); let pubkey = pubkeyFromXpub(xpub); if (accountType == AccountType.p2tr) { pubkey = pubkey.slice(1); } const script = outputScriptOf(pubkey, accountType); return { ...script, pubkey }; } /** * Adds relevant data about an input to the psbt. This includes sequence, * previous txid, output index, spent UTXO, redeem script for wrapped p2wpkh, * public key and its derivation path. */ private async setInput( psbt: PsbtV2, i: number, input: [ Transaction, number, string | null | undefined, number | null | undefined ], pathElements: number[], accountType: AccountType, masterFP: Buffer ): Promise<void> { const inputTx = input[0]; const spentOutputIndex = input[1]; const redeemScript = input[2]; const sequence = input[3]; if (sequence) { psbt.setInputSequence(i, sequence); } const inputTxBuffer = serializeTransaction(inputTx, true); const inputTxid = crypto.hash256(inputTxBuffer); const xpubBase58 = await this.client.getExtendedPubkey(false, pathElements); const pubkey = pubkeyFromXpub(xpubBase58); if (!inputTx.outputs) throw Error("Missing outputs array in transaction to sign"); const spentOutput = inputTx.outputs[spentOutputIndex]; if (accountType == AccountType.p2pkh) { psbt.setInputNonWitnessUtxo(i, inputTxBuffer); psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); } else if (accountType == AccountType.p2wpkh) { psbt.setInputNonWitnessUtxo(i, inputTxBuffer); psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); } else if (accountType == AccountType.p2wpkhWrapped) { psbt.setInputNonWitnessUtxo(i, inputTxBuffer); psbt.setInputBip32Derivation(i, pubkey, masterFP, pathElements); if (!redeemScript) { throw new Error("Missing redeemScript for p2wpkhWrapped input"); } const expectedRedeemScript = createRedeemScript(pubkey); if (redeemScript != expectedRedeemScript.toString("hex")) { throw new Error("Unexpected redeemScript"); } psbt.setInputRedeemScript(i, expectedRedeemScript); psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); } else if (accountType == AccountType.p2tr) { const xonly = pubkey.slice(1); psbt.setInputTapBip32Derivation(i, xonly, [], masterFP, pathElements); psbt.setInputWitnessUtxo(i, spentOutput.amount, spentOutput.script); } psbt.setInputPreviousTxId(i, inputTxid); psbt.setInputOutputIndex(i, spentOutputIndex); } /** * This implements the "Signer" role of the BIP370 transaction signing * process. * * It ssks the hardware device to sign the a psbt using the specified wallet * policy. This method assumes BIP32 derived keys are used for all inputs, see * comment in-line. The signatures returned from the hardware device is added * to the appropriate input fields of the PSBT. */ private async signPsbt( psbt: PsbtV2, walletPolicy: WalletPolicy ): Promise<void> { const sigs: Map<number, Buffer> = await this.client.signPsbt( psbt, walletPolicy, Buffer.alloc(32, 0) ); sigs.forEach((v, k) => { // Note: Looking at BIP32 derivation does not work in the generic case, // since some inputs might not have a BIP32-derived pubkey. const pubkeys = psbt.getInputKeyDatas(k, psbtIn.BIP32_DERIVATION); let pubkey; if (pubkeys.length != 1) { // No legacy BIP32_DERIVATION, assume we're using taproot. pubkey = psbt.getInputKeyDatas(k, psbtIn.TAP_BIP32_DERIVATION); if (pubkey.length == 0) { throw Error(`Missing pubkey derivation for input ${k}`); } psbt.setInputTapKeySig(k, v); } else { pubkey = pubkeys[0]; psbt.setInputPartialSig(k, pubkey, v); } }); } } enum AccountType { p2pkh = "pkh(@0)", p2wpkh = "wpkh(@0)", p2wpkhWrapped = "sh(wpkh(@0))", p2tr = "tr(@0)", } function createRedeemScript(pubkey: Buffer): Buffer { const pubkeyHash = hashPublicKey(pubkey); return Buffer.concat([Buffer.from("0014", "hex"), pubkeyHash]); } /** * Generates a single signature scriptPubKey (output script) from a public key. * This is done differently depending on account type. * * If accountType is p2tr, the public key must be a 32 byte x-only taproot * pubkey, otherwise it's expected to be a 33 byte ecdsa compressed pubkey. */ function outputScriptOf( pubkey: Buffer, accountType: AccountType ): { script: Buffer; redeemScript?: Buffer } { const buf = new BufferWriter(); const pubkeyHash = hashPublicKey(pubkey); let redeemScript: Buffer | undefined; if (accountType == AccountType.p2pkh) { buf.writeSlice(Buffer.of(OP_DUP, OP_HASH160, HASH_SIZE)); buf.writeSlice(pubkeyHash); buf.writeSlice(Buffer.of(OP_EQUALVERIFY, OP_CHECKSIG)); } else if (accountType == AccountType.p2wpkhWrapped) { redeemScript = createRedeemScript(pubkey); const scriptHash = hashPublicKey(redeemScript); buf.writeSlice(Buffer.of(OP_HASH160, HASH_SIZE)); buf.writeSlice(scriptHash); buf.writeUInt8(OP_EQUAL); } else if (accountType == AccountType.p2wpkh) { buf.writeSlice(Buffer.of(0, HASH_SIZE)); buf.writeSlice(pubkeyHash); } else if (accountType == AccountType.p2tr) { const outputKey = getTaprootOutputKey(pubkey); buf.writeSlice(Buffer.of(0x51, 32)); // push1, pubkeylen buf.writeSlice(outputKey); } return { script: buf.buffer(), redeemScript }; } function accountTypeFrom(addressFormat: AddressFormat): AccountType { if (addressFormat == "legacy") return AccountType.p2pkh; if (addressFormat == "p2sh") return AccountType.p2wpkhWrapped; if (addressFormat == "bech32") return AccountType.p2wpkh; if (addressFormat == "bech32m") return AccountType.p2tr; throw new Error("Unsupported address format " + addressFormat); } function accountTypeFromArg(arg: CreateTransactionArg): AccountType { if (arg.additionals.includes("bech32m")) return AccountType.p2tr; if (arg.additionals.includes("bech32")) return AccountType.p2wpkh; if (arg.segwit) return AccountType.p2wpkhWrapped; return AccountType.p2pkh; } /* The following two functions are copied from wallet-btc and adapted. They should be moved to a library to avoid code reuse. */ function hashTapTweak(x: Buffer): Buffer { // hash_tag(x) = SHA256(SHA256(tag) || SHA256(tag) || x), see BIP340 // See https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#specification const h = crypto.sha256(Buffer.from("TapTweak", "utf-8")); return crypto.sha256(Buffer.concat([h, h, x])); } /** * Calculates a taproot output key from an internal key. This output key will be * used as witness program in a taproot output. The internal key is tweaked * according to recommendation in BIP341: * https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_ref-22-0 * * @param internalPubkey A 32 byte x-only taproot internal key * @returns The output key */ function getTaprootOutputKey(internalPubkey: Buffer): Buffer { if (internalPubkey.length != 32) { throw new Error("Expected 32 byte pubkey. Got " + internalPubkey.length); } // A BIP32 derived key can be converted to a schnorr pubkey by dropping // the first byte, which represent the oddness/evenness. In schnorr all // pubkeys are even. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#public-key-conversion const evenEcdsaPubkey = Buffer.concat([Buffer.of(0x02), internalPubkey]); const tweak = hashTapTweak(internalPubkey); // Q = P + int(hash_TapTweak(bytes(P)))G const outputEcdsaKey = Buffer.from(pointAddScalar(evenEcdsaPubkey, tweak)); // Convert to schnorr. const outputSchnorrKey = outputEcdsaKey.slice(1); // Create address return outputSchnorrKey; }
the_stack
import { bind, cloneDeep, defaults, each, keys, uniqueId } from 'lodash'; import { AsyncSubject, BehaviorSubject, Observable, Subject, Subscription } from 'rxjs'; import { CompositeDisposable, IDisposable } from 'ts-disposables'; import { QueueProcessor } from '../helpers/QueueProcessor'; import { CommandContext } from '../contexts/CommandContext'; import { RequestContext } from '../contexts/RequestContext'; import { ResponseContext } from '../contexts/ResponseContext'; import { IDriverOptions, IOmnisharpClientStatus, IReactiveClientOptions, IReactiveDriver } from '../enums'; import { DriverState } from '../enums'; import { event, getInternalValue, reference, request, response, setEventOrResponse } from '../helpers/decorators'; import { getPreconditions } from '../helpers/preconditions'; import { isDeferredCommand, isNormalCommand, isPriorityCommand } from '../helpers/prioritization'; import * as OmniSharp from '../omnisharp-server'; import { createObservable } from '../operators/create'; import { ensureClientOptions } from '../options'; export class ReactiveClient implements IReactiveDriver, IDisposable { private _driver: IReactiveDriver; private _requestStream = new Subject<RequestContext<any>>(); private _responseStream = new Subject<ResponseContext<any, any>>(); private _responseStreams = new Map<string, Subject<ResponseContext<any, any>>>(); private _statusStream: Observable<IOmnisharpClientStatus>; private _errorStream = new Subject<CommandContext<any>>(); private _uniqueId = uniqueId('client'); private _lowestIndexValue = 0; private _observe: ReactiveClientEvents; private _disposable = new CompositeDisposable(); private _options: IReactiveClientOptions & IDriverOptions; private _fixups: ((action: string, request: any, options?: OmniSharp.RequestOptions) => void)[] = []; private _eventsStream = new Subject<OmniSharp.Stdio.Protocol.EventPacket>(); private _events = this._eventsStream.asObservable(); private _stateStream = new BehaviorSubject<DriverState>(DriverState.Disconnected); private _state = this._stateStream.asObservable(); private _queue: QueueProcessor<Observable<ResponseContext<any, any>>>; public get uniqueId() { return this._uniqueId; } public get id() { return this._driver.id; } public get serverPath() { return this._driver.serverPath; } public get projectPath() { return this._driver.projectPath; } public get events(): Observable<OmniSharp.Stdio.Protocol.EventPacket> { return this._events; } public get currentState() { return this._stateStream.getValue(); } public get state(): Observable<DriverState> { return this._state; } public get outstandingRequests() { return this._currentRequests.size; } private _currentRequests = new Set<RequestContext<any>>(); public get status(): Observable<IOmnisharpClientStatus> { return this._statusStream; } public get requests(): Observable<RequestContext<any>> { return <Observable<RequestContext<any>>><any>this._requestStream; } public get responses(): Observable<ResponseContext<any, any>> { return this._responseStream; } public get errors(): Observable<CommandContext<any>> { return <Observable<CommandContext<any>>><any>this._errorStream; } public get observe(): ReactiveClientEvents { return this._observe; } public constructor(_options: Partial<IReactiveClientOptions>) { _options.driver = _options.driver || ((options: IDriverOptions) => { // tslint:disable-next-line:no-require-imports const item = require('../drivers/StdioDriver'); const driverFactory = item[keys(item)[0]]; return new driverFactory(this._options); }); this._options = <any>defaults(_options, <Partial<IDriverOptions>>{ projectPath: '', onState: bind(this._stateStream.next, this._stateStream), onEvent: bind(this._eventsStream.next, this._eventsStream), onCommand: packet => { const response = new ResponseContext(new RequestContext(this._uniqueId, packet.Command, {}, {}, 'command'), packet.Body); this._getResponseStream(packet.Command).next(response); }, }); ensureClientOptions(this._options); this._queue = new QueueProcessor<Observable<ResponseContext<any, any>>>(this._options.concurrency, bind(this._handleResult, this)); this._resetDriver(); const getStatusValues = () => <IOmnisharpClientStatus>({ state: this._driver.currentState, outgoingRequests: this.outstandingRequests, hasOutgoingRequests: this.outstandingRequests > 0, }); const status = Observable.merge( <Observable<any>><any>this._requestStream, <Observable<any>><any>this._responseStream); this._statusStream = status .map(getStatusValues) .distinctUntilChanged() .debounceTime(100) .share(); this._observe = new ReactiveClientEvents(this); if (this._options.debug) { this._disposable.add(this._responseStream.subscribe(context => { // log our complete response time this._eventsStream.next({ Event: 'log', Body: { Message: `/${context.command} ${context.responseTime}ms (round trip)`, LogLevel: 'INFORMATION', }, Seq: -1, Type: 'log', }); })); } } public getCurrentRequests() { const response: { command: string; sequence: string; silent: boolean; request: any; duration: number; }[] = []; this._currentRequests.forEach(request => { response.push({ command: request.command, sequence: cloneDeep(request.sequence), request: request.request, silent: request.silent, duration: Date.now() - request.time.getTime(), }); }); return response; } public dispose() { if (this._disposable.isDisposed) { return; } this.disconnect(); this._disposable.dispose(); } public log(message: string, logLevel?: string) { // log our complete response time this._eventsStream.next({ Event: 'log', Body: { Message: message, LogLevel: logLevel ? logLevel.toUpperCase() : 'INFORMATION', }, Seq: -1, Type: 'log', }); } public connect() { // Currently connecting if (this.currentState >= DriverState.Downloading && this.currentState <= DriverState.Connected) { return; } // Bootstrap plugins here this._currentRequests.clear(); this._driver.connect(); } public disconnect() { this._driver.disconnect(); } public request<TRequest, TResponse>(action: string, request?: TRequest, options?: OmniSharp.RequestOptions): Observable<TResponse> { const conditions = getPreconditions(action); if (conditions) { each(conditions, x => x(request)); } if (!options) { options = <OmniSharp.RequestOptions>{}; } // Handle disconnected requests if (this.currentState !== DriverState.Connected && this.currentState !== DriverState.Error) { return this.state .filter(z => z === DriverState.Connected) .take(1) .switchMap(z => { return this.request<TRequest, TResponse>(action, request, options); }); } const context = new RequestContext(this._uniqueId, action, request!, options); this._currentRequests.add(context); this._requestStream.next(context); const response = this._queue.enqueue(context); // By default the request will only be made if the response is subscribed to... // This is a breaking change for clients, potentially a very big one, so this subscribe // avoids the problem for the moment response.subscribe(); return <Observable<TResponse>><any>response; } public registerFixup(func: (action: string, request: any, options?: OmniSharp.RequestOptions) => void) { this._fixups.push(func); } private _handleResult(context: RequestContext<any>): Observable<ResponseContext<any, any>> { const responseStream = this._getResponseStream(context.command); return this._driver.request<any, any>(context.command, context.request) .do(data => { responseStream.next(new ResponseContext(context, data)); }, error => { this._errorStream.next(new CommandContext(context.command, error)); responseStream.next(new ResponseContext(context, null, true)); this._currentRequests.delete(context); }, () => { this._currentRequests.delete(context); }); } private _resetDriver() { if (this._driver) { this._disposable.remove(this._driver); this._driver.dispose(); } const { driver } = this._options; this._driver = driver(this._options); this._disposable.add(this._driver); return this._driver; } private _getResponseStream(key: string) { key = key.toLowerCase(); if (!this._responseStreams.has(key)) { const subject = new Subject<ResponseContext<any, any>>(); subject.subscribe({ next: bind(this._responseStream.next, this._responseStream), }); this._responseStreams.set(key, subject); return subject; } return this._responseStreams.get(key)!; } private _fixup<TRequest>(action: string, request: TRequest, options?: OmniSharp.RequestOptions) { each(this._fixups, f => f(action, request, options)); } } // tslint:disable-next-line:interface-name no-empty-interface export interface ReactiveClient extends OmniSharp.Api.V2 { } // tslint:disable-next-line:max-classes-per-file export class ReactiveClientEvents { public constructor( private _client: ReactiveClient) { } public get uniqueId() { return this._client.uniqueId; } public listen(key: string): Observable<any> { const value = getInternalValue(this, key); if (!value) { return setEventOrResponse(this, key); } return value; } } // tslint:disable-next-line:interface-name no-empty-interface export interface ReactiveClientEvents extends OmniSharp.Events.V2, OmniSharp.Events { /*readonly*/ events: Observable<OmniSharp.Stdio.Protocol.EventPacket>; /*readonly*/ commands: Observable<OmniSharp.Stdio.Protocol.ResponsePacket>; /*readonly*/ state: Observable<DriverState>; /*readonly*/ status: Observable<IOmnisharpClientStatus>; /*readonly*/ requests: Observable<RequestContext<any>>; /*readonly*/ responses: Observable<ResponseContext<any, any>>; /*readonly*/ errors: Observable<CommandContext<any>>; } reference(ReactiveClientEvents.prototype, 'events', 'events'); reference(ReactiveClientEvents.prototype, 'commands', 'commands'); reference(ReactiveClientEvents.prototype, 'state', 'state'); reference(ReactiveClientEvents.prototype, 'status', 'status'); reference(ReactiveClientEvents.prototype, 'requests', 'requests'); reference(ReactiveClientEvents.prototype, 'responses', 'responses'); reference(ReactiveClientEvents.prototype, 'errors', 'errors'); // <#GENERATED /> request(ReactiveClient.prototype, 'getteststartinfo'); request(ReactiveClient.prototype, 'runtest'); request(ReactiveClient.prototype, 'autocomplete'); request(ReactiveClient.prototype, 'changebuffer'); request(ReactiveClient.prototype, 'codecheck'); request(ReactiveClient.prototype, 'codeformat'); request(ReactiveClient.prototype, 'diagnostics'); request(ReactiveClient.prototype, 'close'); request(ReactiveClient.prototype, 'open'); request(ReactiveClient.prototype, 'filesChanged'); request(ReactiveClient.prototype, 'findimplementations'); request(ReactiveClient.prototype, 'findsymbols'); request(ReactiveClient.prototype, 'findusages'); request(ReactiveClient.prototype, 'fixusings'); request(ReactiveClient.prototype, 'formatAfterKeystroke'); request(ReactiveClient.prototype, 'formatRange'); request(ReactiveClient.prototype, 'getcodeactions'); request(ReactiveClient.prototype, 'gotodefinition'); request(ReactiveClient.prototype, 'gotofile'); request(ReactiveClient.prototype, 'gotoregion'); request(ReactiveClient.prototype, 'highlight'); request(ReactiveClient.prototype, 'currentfilemembersasflat'); request(ReactiveClient.prototype, 'currentfilemembersastree'); request(ReactiveClient.prototype, 'metadata'); request(ReactiveClient.prototype, 'navigatedown'); request(ReactiveClient.prototype, 'navigateup'); request(ReactiveClient.prototype, 'packagesearch'); request(ReactiveClient.prototype, 'packagesource'); request(ReactiveClient.prototype, 'packageversion'); request(ReactiveClient.prototype, 'rename'); request(ReactiveClient.prototype, 'runcodeaction'); request(ReactiveClient.prototype, 'signatureHelp'); request(ReactiveClient.prototype, 'gettestcontext'); request(ReactiveClient.prototype, 'typelookup'); request(ReactiveClient.prototype, 'updatebuffer'); request(ReactiveClient.prototype, 'project'); request(ReactiveClient.prototype, 'projects'); request(ReactiveClient.prototype, 'checkalivestatus'); request(ReactiveClient.prototype, 'checkreadystatus'); request(ReactiveClient.prototype, 'stopserver'); response(ReactiveClientEvents.prototype, 'getteststartinfo', '/v2/getteststartinfo'); response(ReactiveClientEvents.prototype, 'runtest', '/v2/runtest'); response(ReactiveClientEvents.prototype, 'autocomplete', '/autocomplete'); response(ReactiveClientEvents.prototype, 'changebuffer', '/changebuffer'); response(ReactiveClientEvents.prototype, 'codecheck', '/codecheck'); response(ReactiveClientEvents.prototype, 'codeformat', '/codeformat'); response(ReactiveClientEvents.prototype, 'diagnostics', '/diagnostics'); response(ReactiveClientEvents.prototype, 'close', '/close'); response(ReactiveClientEvents.prototype, 'open', '/open'); response(ReactiveClientEvents.prototype, 'filesChanged', '/filesChanged'); response(ReactiveClientEvents.prototype, 'findimplementations', '/findimplementations'); response(ReactiveClientEvents.prototype, 'findsymbols', '/findsymbols'); response(ReactiveClientEvents.prototype, 'findusages', '/findusages'); response(ReactiveClientEvents.prototype, 'fixusings', '/fixusings'); response(ReactiveClientEvents.prototype, 'formatAfterKeystroke', '/formatAfterKeystroke'); response(ReactiveClientEvents.prototype, 'formatRange', '/formatRange'); response(ReactiveClientEvents.prototype, 'getcodeactions', '/v2/getcodeactions'); response(ReactiveClientEvents.prototype, 'gotodefinition', '/gotodefinition'); response(ReactiveClientEvents.prototype, 'gotofile', '/gotofile'); response(ReactiveClientEvents.prototype, 'gotoregion', '/gotoregion'); response(ReactiveClientEvents.prototype, 'highlight', '/highlight'); response(ReactiveClientEvents.prototype, 'currentfilemembersasflat', '/currentfilemembersasflat'); response(ReactiveClientEvents.prototype, 'currentfilemembersastree', '/currentfilemembersastree'); response(ReactiveClientEvents.prototype, 'metadata', '/metadata'); response(ReactiveClientEvents.prototype, 'navigatedown', '/navigatedown'); response(ReactiveClientEvents.prototype, 'navigateup', '/navigateup'); response(ReactiveClientEvents.prototype, 'packagesearch', '/packagesearch'); response(ReactiveClientEvents.prototype, 'packagesource', '/packagesource'); response(ReactiveClientEvents.prototype, 'packageversion', '/packageversion'); response(ReactiveClientEvents.prototype, 'rename', '/rename'); response(ReactiveClientEvents.prototype, 'runcodeaction', '/v2/runcodeaction'); response(ReactiveClientEvents.prototype, 'signatureHelp', '/signatureHelp'); response(ReactiveClientEvents.prototype, 'gettestcontext', '/gettestcontext'); response(ReactiveClientEvents.prototype, 'typelookup', '/typelookup'); response(ReactiveClientEvents.prototype, 'updatebuffer', '/updatebuffer'); response(ReactiveClientEvents.prototype, 'project', '/project'); response(ReactiveClientEvents.prototype, 'projects', '/projects'); response(ReactiveClientEvents.prototype, 'checkalivestatus', '/checkalivestatus'); response(ReactiveClientEvents.prototype, 'checkreadystatus', '/checkreadystatus'); response(ReactiveClientEvents.prototype, 'stopserver', '/stopserver'); event(ReactiveClientEvents.prototype, 'projectAdded'); event(ReactiveClientEvents.prototype, 'projectChanged'); event(ReactiveClientEvents.prototype, 'projectRemoved'); event(ReactiveClientEvents.prototype, 'error'); event(ReactiveClientEvents.prototype, 'diagnostic'); event(ReactiveClientEvents.prototype, 'msBuildProjectDiagnostics'); event(ReactiveClientEvents.prototype, 'packageRestoreStarted'); event(ReactiveClientEvents.prototype, 'packageRestoreFinished'); event(ReactiveClientEvents.prototype, 'unresolvedDependencies');
the_stack
import * as vscode from 'vscode'; import {CoqLanguageServer} from './CoqLanguageServer'; interface TriggerSnippet { label:string, insertText: string, completion?: vscode.CompletionItem[], detail?: string, } type Snippet = string | {label: string, insertText: string, documentation?: string}; function snippetSentence(item: Snippet) : vscode.CompletionItem { if(typeof item === 'string') { const result = new vscode.CompletionItem(item,vscode.CompletionItemKind.Snippet); result.insertText = item + "."; return result; } else { const result = new vscode.CompletionItem(item.label,vscode.CompletionItemKind.Snippet); result.insertText = item.insertText; result.documentation = item.documentation as string; // vscode needs to provide stricter types in its API... return result; } } const optionsSnippetsRaw = [ "Asymmetric Patterns", "Atomic Load", "Automatic Coercions Import", "Automatic Introduction", "Boolean Equality Schemes", "Bracketing Last Introduction Pattern", "Subproofs Case Analysis Schemes", "Compat Notations", "Congruence Depth", "Congruence Verbose", "Contextual Implicit", "Debug Auto", "Debug Eauto", "Debug Rakam", "Debug Tactic Unification", "Debug Trivial", "Debug Unification", "Decidable Equality Schemes", "Default Clearing Used Hypotheses", "Default Goal Selector", "Default Proof Mode", "Default Proof Using", "Default Timeout", "Dependent Propositions Elimination", "Discriminate Introduction", "Dump Bytecode", "Elimination Schemes", "Equality Scheme", "Extraction Auto Inline", "Extraction Conservative Types", "Extraction File Comment", "Extraction Flag", "Extraction Keep Singleton", "Extraction Optimize", "Extraction Safe Implicits", "Extraction Type Expand", "Firstorder Depth", "Hide Obligations", "Implicit Arguments", "Info Auto", "Info Eauto", "Info Level", "Info Trivial", "Injection L2 Rpattern Order", "Injection On Proofs", "Inline Level", "Intuition Iff Unfolding", "Intuition Negation Unfolding", "Kernel Term Sharing", "Keyed Unification", "Loose Hint Behavior", "Maximal Implicit Insertion", "Nonrecursive Elimination Schemes", "Parsing Explicit", "Primitive Projections", "Printing All", "Printing Coercions", "Printing Depth", "Printing Existential Instances", "Printing Implicit", "Printing Implicit Defensive", "Printing Matching", "Printing Notations", "Printing Primitive Projection Compatibility", "Printing Primitive Projection Parameters", "Printing Projections", "Printing Records", "Printing Synth", "Printing Universes", "Printing Width", "Printing Wildcard", "Program Mode", "Proof Using Clear Unused", "Record Elimination Schemes", "Regular Subst Tactic", "Reversible Pattern Implicit", "Rewriting Schemes", "Short Module Printing", "Shrink Obligations", "Simpl Is Cbn", "Standard Proposition Elimination Names", "Strict Implicit", "Strict Proofs", "Strict Universe Declaration", "Strongly Strict Implicit", "Suggest Proof Using", "Tactic Compat Context", "Tactic Evars Pattern Unification", "Transparent Obligations", "Typeclass Resolution After Apply", "Typeclass Resolution For Conversion", "Typeclasses Debug", "Typeclasses Dependency Order", "Typeclasses Depth", "Typeclasses Modulo Eta", "Typeclasses Strict Resolution", "Typeclasses Unique Instances", "Typeclasses Unique Solutions", "Universal Lemma Under Conjunction", "Universe Minimization To Set", "Universe Polymorphism", "Verbose Compat Notations" ]; const optionsSnippets = [ ...optionsSnippetsRaw, "Hyps Limit", "Bullet Behavior", ].map(snippetSentence);; const setOptionsSnippets = [ ...optionsSnippetsRaw, {label: "Hyps Limit", insertText: "Hyps Limit {{num}}."}, 'Bullet Behavior "None"', 'Bullet Behavior "Strict Subproofs"', ].map(snippetSentence); const printSnippets = [ "All", {label: "All Dependencies", insertText: "All Dependencies {{qualid}}."}, {label: "Assumptions", insertText: "Assumptions {{qualid}}."}, "Canonical Projections", "Classes", {label: "Coercion Paths", insertText: "Coercion Paths {{class1}} {{class2}}."}, "Coercions", "Extraction Inline", "Fields", "Grammar constr", "Grammar pattern", "Graph", {label: "Hint", insertText: "Hint {{ident}}."}, "Hint *", {label: "HintDb", insertText: "HintDb {{ident}}."}, {label: "Implicit", insertText: "HintDb {{qualid}}."}, "Libraries", "LoadPath", {label: "Ltac", insertText: "Ltac {{qualid}}."}, "ML Modules", "ML Path", {label: "Module", insertText: "Module {{ident}}."}, {label: "Module Type", insertText: "Module Type {{ident}}."}, {label: "Opaque Dependencies", insertText: "Opaque Dependencies {{qualid}}."}, "Options", "Rings", {label: "Scope", insertText: "Scope {{scope}}."}, "Scopes", {label: "Section", insertText: "Section {{ident}}."}, "Sorted Universes", {label: "Sorted Universes (filename)", insertText: "Sorted Universes {{filename}}."}, "Strategies", {label: "Strategy", insertText: "Strategy {{qualid}}."}, "Table Printing If", "Table Printing Let", "Tables", {label: "Term", insertText: "Term {{qualid}}."}, {label: "Transparent Dependencies", insertText: "Transparent Dependencies {{qualid}}."}, "Universes", {label: "Universes (filename)", insertText: "Universes {{filename}}."}, "Visibility", ].map(snippetSentence); const showSnippets = [ {label: "(num)", insertText: " {{num}}.", documentation: "Displays only the num-th subgoal"}, "Script", "Proof", "Conjecturest", "Intro", "Intros", "Existentials", "Universes", ].map(snippetSentence); const hintSnippets = [ {label: "(definition)", insertText: " {{definition}}."}, {label: "Constructors", insertText: "Constructors {{idents …}}."}, {label: 'Cut', insertText: 'Cut "{{regexp}}".'}, {label: 'Extern', insertText: 'Extern {{num}} {{optional-pattern}} => {{tactic}}.'}, {label: 'Immediate', insertText: 'Immediate {{term}}.'}, {label: 'Mode', insertText: 'Mode {{(+|-)*}} {{qualid}}.'}, {label: 'Opaque', insertText: 'Opaque {{qualid}}.'}, {label: 'Resolve', insertText: 'Resolve {{term}}.'}, {label: 'Rewrite', insertText: 'Rewrite {{terms …}} : {{idents …}}.'}, {label: 'Rewrite ->', insertText: 'Rewrite -> {{terms …}} : {{idents …}}.'}, {label: 'Rewrite <-', insertText: 'Rewrite <- {{terms …}} : {{idents …}}.'}, {label: 'Transparent', insertText: 'Transparent {{qualid}}.'}, {label: 'Unfold', insertText: 'Unfold {{qualid}}.'}, 'Mode', 'Proof', 'Conjecturest', 'Intro', 'Intros', 'Existentials', 'Universes', ].map(snippetSentence); const triggerSnippets : TriggerSnippet[] = [ {label: "Set...", insertText: "Set ", completion: setOptionsSnippets, detail: "Set coqtop options"}, {label: "Unset...", insertText: "Unset ", completion: optionsSnippets, detail: "Unset coqtop options"}, {label: "Local Set...", insertText: "Local Set ", completion: setOptionsSnippets}, {label: "Global Unset...", insertText: "Global Unset ", completion: optionsSnippets}, {label: "Test...", insertText: "Test ", completion: optionsSnippets}, {label: "Print...", insertText: "Print ", completion: printSnippets}, {label: "Show...", insertText: "Show ", completion: showSnippets}, {label: "Hint...", insertText: "Hint ", completion: hintSnippets}, {label: "Arguments", insertText: "Arguments {{qualid}} {{possibly_bracketed_idents …}}."}, {label: "Local Arguments", insertText: "Local Arguments {{qualid}} {{possibly_bracketed_idents …}}."}, {label: "Global Arguments", insertText: "Global Arguments {{qualid}} {{possibly_bracketed_idents …}}."}, ]; let triggerRegexp : RegExp; function getTriggerSnippet(str: string) : TriggerSnippet|null { const match = triggerRegexp.exec(str); if(match && match.length > 1) { match.shift(); const triggerIdx = match.findIndex((v) => v!==undefined) return triggerSnippets[triggerIdx]; } else return null; } function getTriggerCompletions(prefix: string) { const triggerCompletions = new vscode.CompletionList( triggerSnippets .filter((trigger) => { return trigger.insertText.startsWith(prefix); }) .map((trigger) => { const item = new vscode.CompletionItem(trigger.label); item.insertText = trigger.insertText; item.detail = trigger.detail as string; // vscode needs to update its API if(trigger.completion) item.command = { command: "editor.action.triggerSuggest", title: "Trigger Suggest", arguments: [vscode.window.activeTextEditor] } return item; }), true); return triggerCompletions; } export function setupSnippets(subscriptions: vscode.Disposable[]) { triggerRegexp = RegExp(`\\s*(?:${triggerSnippets.map((v) => "(" + escapeRegExp(v.insertText) + ")").join('|')})\\s*$`); const triggerTerminators = triggerSnippets.map((trigger) => trigger.insertText[trigger.insertText.length-1]); // Set-Options snippets are registered manually because coq.json snippets // don't currently provide a nice interaction. subscriptions.push(vscode.languages.registerCompletionItemProvider('coq', { provideCompletionItems: async (doc, pos, token) => { try { const prefix = await CoqLanguageServer.getInstance().getPrefixText(doc.uri.toString(),pos,token); if(prefix === "") return []; const trigger = getTriggerSnippet(prefix); if(trigger) return trigger.completion; else return getTriggerCompletions(prefix.trim()); } catch(err) { return []; } } }, ...triggerTerminators)); // const qedCompletion = new vscode.CompletionItem("Qed.", vscode.CompletionItemKind.Snippet); // const definedCompletion = new vscode.CompletionItem("Defined.", vscode.CompletionItemKind.Snippet); // const admittedCompletion = new vscode.CompletionItem("Admitted.", vscode.CompletionItemKind.Snippet); // const outdentCompletions = [qedCompletion, definedCompletion, admittedCompletion]; // subscriptions.push(vscode.languages.registerCompletionItemProvider('coq', { // provideCompletionItems: async (doc, pos, token) => { // try { // const line = doc.lineAt(pos.line); // // outdent the text // const indentSize = getIndentSize(doc); // const insertLine = {command: "editor.action.insertLineAfter", arguments: [], title: "insert line"}; // const outdentRange = new vscode.Range(line.lineNumber, Math.max(0,line.firstNonWhitespaceCharacterIndex-indentSize), line.lineNumber, line.firstNonWhitespaceCharacterIndex); // const outdent = new vscode.TextEdit(outdentRange, ''); // outdentCompletions.forEach(o => { // o.additionalTextEdits = [outdent]; // o.command = insertLine; // }); // return outdentCompletions; // } catch(err) { // return []; // } // } // })); } // function getIndentSize(doc: vscode.TextDocument) : number { // let editor = vscode.window.activeTextEditor; // if(editor && editor.document.uri === doc.uri) // return editor.options.insertSpaces ? +editor.options.tabSize : 1; // editor = vscode.window.visibleTextEditors.find((e) => e.document.uri === doc.uri); // if(editor && editor.document.uri === doc.uri) // return editor.options.insertSpaces ? +editor.options.tabSize : 1; // else // return 0; // } /** see: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex */ function escapeRegExp(str : string) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }
the_stack
import BoxClient from '../box-client'; import urlPath from '../util/url-path'; // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- type CollaborationRole = any /* FIXME */; type ItemType = 'folder' | string /* FIXME */; // ------------------------------------------------------------------------------ // Private // ------------------------------------------------------------------------------ const BASE_PATH = '/collaborations'; // ------------------------------------------------------------------------------ // Public // ------------------------------------------------------------------------------ /** * Simple manager for interacting with all 'Collaboration' endpoints and actions. * * @constructor * @param {BoxClient} client - The Box API Client that is responsible for making calls to the API * @returns {void} */ class Collaborations { client: BoxClient; constructor(client: BoxClient) { this.client = client; } /** * Requests a collaboration object with a given ID. * * API Endpoint: '/collaborations/:collaborationID' * Method: GET * * @param {string} collaborationID - Box ID of the collaboration being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the collaboration information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the collaboration object */ get( collaborationID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, collaborationID); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Gets a user's pending collaborations * * API Endpoint: '/collaborations' * Method: GET * * @param {Function} [callback] - Called with a collection of pending collaborations if successful * @returns {Promise<Object>} A promise resolving to the collection of pending collaborations */ getPending(callback?: Function) { var params = { qs: { status: 'pending', }, }; return this.client.wrapWithDefaultHandler(this.client.get)( BASE_PATH, params, callback ); } /** * Update some information about a given collaboration. * * API Endpoint: '/collaborations/:collaborationID' * Method: PUT * * @param {string} collaborationID - Box ID of the collaboration being requested * @param {Object} updates - Fields of the collaboration to be updated * @param {Function} [callback] - Passed the updated collaboration information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the updated collaboration object */ update( collaborationID: string, updates: Record<string, any>, callback?: Function ) { var params = { body: updates, }; var apiPath = urlPath(BASE_PATH, collaborationID); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Update the status of a pending collaboration. * * API Endpoint: '/collaborations/:collaborationID' * Method: PUT * * @param {string} collaborationID - Box ID of the collaboration being requested * @param {string} newStatus - The new collaboration status ('accepted'/'rejected') * @param {Function} [callback] - Passed the updated collaboration information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the accepted collaboration object */ respondToPending( collaborationID: string, newStatus: string, callback?: Function ) { var options = { status: newStatus, }; return this.update(collaborationID, options, callback); } /** * Invite a collaborator to a folder. You'll have to create the 'accessible_by' input object * yourself, but the method allows for multiple types of collaborator invites. See * {@link http://developers.box.com/docs/#collaborations-add-a-collaboration} for formatting * help. * * API Endpoint: '/collaborations * Method: POST * * @param {Object} accessibleBy - The accessible_by object expected by the API * @param {string} itemID - Box ID of the item to which the user should be invited * @param {CollaborationRole} role - The role which the invited collaborator should have * @param {Object} [options] - Optional parameters for the collaboration * @param {ItemType} [options.type=folder] - Type of object to be collaborated * @param {boolean} [options.notify] - Determines if the user or group will receive email notifications * @param {boolean} [options.can_view_path] - Whether view path collaboration feature is enabled or not * @param {Function} [callback] - Called with the new collaboration if successful * @returns {Promise<Object>} A promise resolving to the created collaboration object */ create( accessibleBy: Record<string, any>, itemID: string, role: CollaborationRole, options?: | { type?: ItemType; notify?: boolean; can_view_path?: boolean; } | Function, callback?: Function ) { var defaultOptions = { type: 'folder', }; if (typeof options === 'function') { callback = options; options = {}; } options = Object.assign({}, defaultOptions, options); var params: { body: Record<string, any>; qs?: Record<string, any>; } = { body: { item: { type: options.type, id: itemID, }, accessible_by: accessibleBy, role, }, }; if (typeof options.can_view_path === 'boolean') { params.body.can_view_path = options.can_view_path; } if (typeof options.notify === 'boolean') { params.qs = { notify: options.notify, }; } return this.client.wrapWithDefaultHandler(this.client.post)( BASE_PATH, params, callback ); } /** * Invite a user to collaborate on an item via their user ID. * * API Endpoint: '/collaborations * Method: POST * * @param {int} userID - The ID of the user you'll invite as a collaborator * @param {string} itemID - Box ID of the item to which the user should be invited * @param {CollaborationRole} role - The role which the invited collaborator should have * @param {Object} [options] - Optional parameters for the collaboration * @param {ItemType} [options.type=folder] - Type of object to be collaborated * @param {boolean} [options.notify] - Determines if the user will receive email notifications * @param {boolean} [options.can_view_path] - Whether view path collaboration feature is enabled or not * @param {Function} [callback] - Called with the new collaboration if successful * @returns {Promise<Object>} A promise resolving to the created collaboration object */ createWithUserID( userID: number, itemID: string, role: CollaborationRole, options?: | { type?: ItemType; notify?: boolean; can_view_path?: boolean; } | Function, callback?: Function ) { if (typeof options === 'function') { callback = options; options = {}; } var accessibleBy = { type: 'user', id: userID, }; return this.create(accessibleBy, itemID, role, options, callback); } /** * Invite a user to collaborate on an item via their user login email address. * * API Endpoint: '/collaborations * Method: POST * * @param {string} email - The collaborator's email address * @param {string} itemID - Box ID of the item to which the user should be invited * @param {CollaborationRole} role - The role which the invited collaborator should have * @param {Object} [options] - Optional parameters for the collaboration * @param {ItemType} [options.type=folder] - Type of object to be collaborated * @param {boolean} [options.notify] - Determines if the user will receive email notifications * @param {boolean} [options.can_view_path] - Whether view path collaboration feature is enabled or not * @param {Function} [callback] - Called with the new collaboration if successful * @returns {Promise<Object>} A promise resolving to the created collaboration object */ createWithUserEmail( email: string, itemID: string, role: CollaborationRole, options?: | { type?: ItemType; notify?: boolean; can_view_path?: boolean; } | Function, callback?: Function ) { if (typeof options === 'function') { callback = options; options = {}; } var accessibleBy = { type: 'user', login: email, }; return this.create(accessibleBy, itemID, role, options, callback); } /** * Invite a group to collaborate on an item via their group ID. * * API Endpoint: '/collaborations * Method: POST * * @param {int} groupID - The ID of the group you'll invite as a collaborator * @param {string} itemID - Box ID of the item to which the group should be invited * @param {CollaborationRole} role - The role which the invited collaborator should have * @param {Object} [options] - Optional parameters for the collaboration * @param {ItemType} [options.type=folder] - Type of object to be collaborated * @param {boolean} [options.notify] - Determines if the group will receive email notifications * @param {boolean} [options.can_view_path] - Whether view path collaboration feature is enabled or not * @param {Function} [callback] - Called with the new collaboration if successful * @returns {Promise<Object>} A promise resolving to the created collaboration object */ createWithGroupID( groupID: number, itemID: string, role: CollaborationRole, options?: | { type?: ItemType; notify?: boolean; can_view_path?: boolean; } | Function, callback?: Function ) { if (typeof options === 'function') { callback = options; options = {}; } var accessibleBy = { type: 'group', id: groupID, }; return this.create(accessibleBy, itemID, role, options, callback); } /** * Delete a given collaboration. * * API Endpoint: '/collaborations/:collaborationID' * Method: DELETE * * @param {string} collaborationID - Box ID of the collaboration being requested * @param {Function} [callback] - Empty response body passed if successful. * @returns {Promise<void>} A promise resolving to nothing */ delete(collaborationID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, collaborationID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } } /** * @module box-node-sdk/lib/managers/collaborations * @see {@Link Collaborations} */ export = Collaborations;
the_stack
import bowser from 'bowser'; import { isClient, isServer } from '../../executionEnvironment'; import { userHasCkCollaboration } from "../../betas"; import { forumTypeSetting } from "../../instanceSettings"; import { getSiteUrl } from '../../vulcan-lib/utils'; import { mongoFind, mongoAggregate } from '../../mongoQueries'; import { userOwns, userCanDo, userIsMemberOf } from '../../vulcan-users/permissions'; import { useEffect, useState } from 'react'; import { getBrowserLocalStorage } from '../../../components/async/localStorageHandlers'; // Get a user's display name (not unique, can take special characters and spaces) export const userGetDisplayName = (user: UsersMinimumInfo|DbUser|null): string => { if (!user) { return ""; } else { return forumTypeSetting.get() === 'AlignmentForum' ? (user.fullName || user.displayName) : (user.displayName || getUserName(user)) || "" } }; // Get a user's username (unique, no special characters or spaces) export const getUserName = function(user: UsersMinimumInfo|DbUser|null): string|null { try { if (user?.username) return user.username; } catch (error) { console.log(error); // eslint-disable-line } return null; }; export const userOwnsAndInGroup = (group: string) => { return (user: DbUser, document: HasUserIdType): boolean => { return userOwns(user, document) && userIsMemberOf(user, group) } } export const userIsSharedOn = (currentUser: DbUser|UsersMinimumInfo|null, document: PostsList|DbPost): boolean => { if (!currentUser) return false; return document.shareWithUsers?.includes(currentUser._id) || document.coauthorStatuses?.findIndex(({ userId }) => userId === currentUser._id) >= 0; } export const userCanCollaborate = (currentUser: UsersCurrent|null, document: PostsList): boolean => { return userHasCkCollaboration(currentUser) && userIsSharedOn(currentUser, document) } export const userCanEditUsersBannedUserIds = (currentUser: DbUser|null, targetUser: DbUser): boolean => { if (userCanDo(currentUser,"posts.moderate.all")) { return true } if (!currentUser || !targetUser) { return false } return !!( userCanDo(currentUser,"posts.moderate.own") && targetUser.moderationStyle ) } const postHasModerationGuidelines = post => { // Because of a bug in Vulcan that doesn't adequately deal with nested fields // in document validation, we check for originalContents instead of html here, // which causes some problems with empty strings, but should overall be fine return post.moderationGuidelines?.originalContents || post.moderationStyle } export const userCanModeratePost = (user: UsersProfile|DbUser|null, post?: PostsBase|DbPost|null): boolean => { if (userCanDo(user,"posts.moderate.all")) { return true } if (!user || !post) { return false } // Users who can moderate their personal posts can moderate any post that // meets all of the following: // 1) they own // 2) has moderation guidelins // 3) is not on the frontpage if ( userCanDo(user, "posts.moderate.own.personal") && userOwns(user, post) && postHasModerationGuidelines(post) && !post.frontpageDate ) { return true } // Users who can moderate all of their own posts (even those on the frontpage) // can moderate any post that meets all of the following: // 1) they own // 2) has moderation guidelines // We have now checked all the possible conditions for posting, if they fail // this, check they cannot moderate this post return !!( userCanDo(user,"posts.moderate.own") && userOwns(user, post) && postHasModerationGuidelines(post) ) } export const userCanModerateComment = (user: UsersProfile|DbUser|null, post: PostsBase|DbPost|null , tag: TagBasicInfo|DbTag|null, comment: CommentsList|DbComment) => { if (!user || !comment) { return false; } if (post) { if (userCanModeratePost(user, post)) return true if (userOwns(user, comment) && !comment.directChildrenCount) return true return false } else if (tag) { if (userIsMemberOf(user, "sunshineRegiment")) { return true; } else if (userOwns(user, comment) && !comment.directChildrenCount) { return true } else { return false } } else { return false } } export const userCanCommentLock = (user: UsersCurrent|DbUser|null, post: PostsBase|DbPost|null): boolean => { if (userCanDo(user,"posts.commentLock.all")) { return true } if (!user || !post) { return false } return !!( userCanDo(user,"posts.commentLock.own") && userOwns(user, post) ) } export const userIsBannedFromPost = (user: UsersMinimumInfo|DbUser, post: PostsDetails|DbPost, postAuthor: PostsAuthors_user|DbUser|null): boolean => { if (!post) return false; return !!( post.bannedUserIds?.includes(user._id) && postAuthor && userOwns(postAuthor, post) ) } export const userIsBannedFromAllPosts = (user: UsersCurrent|DbUser, post: PostsDetails|DbPost, postAuthor: PostsAuthors_user|DbUser|null): boolean => { return !!( // @ts-ignore FIXME: Not enforcing that the fragment includes bannedUserIds postAuthor?.bannedUserIds?.includes(user._id) && // @ts-ignore FIXME: Not enforcing that the fragment includes user.groups userCanDo(postAuthor, 'posts.moderate.own') && postAuthor && userOwns(postAuthor, post) ) } export const userIsBannedFromAllPersonalPosts = (user: UsersCurrent|DbUser, post: PostsDetails|DbPost, postAuthor: PostsAuthors_user|DbUser|null): boolean => { return !!( // @ts-ignore FIXME: Not enforcing that the fragment includes bannedUserIds postAuthor?.bannedPersonalUserIds?.includes(user._id) && // @ts-ignore FIXME: Not enforcing that the fragment includes user.groups userCanDo(postAuthor, 'posts.moderate.own.personal') && postAuthor && userOwns(postAuthor, post) ) } export const userIsAllowedToComment = (user: UsersCurrent|DbUser|null, post: PostsDetails|DbPost, postAuthor: PostsAuthors_user|DbUser|null): boolean => { if (!user) { return false } if (user.deleted) { return false } if (!post) { return true } if (userIsBannedFromPost(user, post, postAuthor)) { return false } if (userIsBannedFromAllPosts(user, post, postAuthor)) { return false } if (userIsBannedFromAllPersonalPosts(user, post, postAuthor) && !post.frontpageDate) { return false } if (post.commentsLocked) { return false } return true } export const userBlockedCommentingReason = (user: UsersCurrent|DbUser|null, post: PostsDetails|DbPost, postAuthor: PostsAuthors_user|null): string => { if (!user) { return "Can't recognize user" } if (userIsBannedFromPost(user, post, postAuthor)) { return "This post's author has blocked you from commenting." } if (userIsBannedFromAllPosts(user, post, postAuthor)) { return "This post's author has blocked you from commenting." } if (userIsBannedFromAllPersonalPosts(user, post, postAuthor)) { return "This post's author has blocked you from commenting on any of their personal blog posts." } if (post.commentsLocked) { return "Comments on this post are disabled." } return "You cannot comment at this time" } // Return true if the user's account has at least one verified email address. export const userEmailAddressIsVerified = (user: UsersCurrent|DbUser|null): boolean => { // EA Forum does not do its own email verification if (forumTypeSetting.get() === 'EAForum') { return true } if (!user || !user.emails) return false; for (let email of user.emails) { if (email && email.verified) return true; } return false; }; export const userHasEmailAddress = (user: UsersCurrent|DbUser|null): boolean => { return !!(user?.emails && user.emails.length > 0); } export function getUserEmail (user: UsersCurrent | DbUser): string | undefined { return user.email || user.emails?.[0]?.address } // Replaces Users.getProfileUrl from the vulcan-users package. export const userGetProfileUrl = (user: DbUser|UsersMinimumInfo|AlgoliaUser|null, isAbsolute=false): string => { if (!user) return ""; if (user.slug) { return userGetProfileUrlFromSlug(user.slug, isAbsolute); } else { return ""; } } export const userGetProfileUrlFromSlug = (userSlug: string, isAbsolute=false): string => { if (!userSlug) return ""; const prefix = isAbsolute ? getSiteUrl().slice(0,-1) : ''; return `${prefix}/users/${userSlug}`; } const clientRequiresMarkdown = (): boolean => { if (isClient && window && window.navigator && window.navigator.userAgent) { return (bowser.mobile || bowser.tablet) } return false } export const userUseMarkdownPostEditor = (user: UsersCurrent|null): boolean => { if (clientRequiresMarkdown()) { return true } if (!user) { return false; } return user.markDownPostEditor } export const userCanEdit = (currentUser, user) => { return userOwns(currentUser, user) || userCanDo(currentUser, 'users.edit.all') } interface UserLocation { lat: number, lng: number, loading: boolean, known: boolean, } // Return the current user's location, as a latitude-longitude pair, plus the boolean field `known`. // If `known` is false, the lat/lng are invalid placeholders. // If the user is logged in, we try to return the location specified in their account settings. export const userGetLocation = (currentUser: UsersCurrent|DbUser|null): { lat: number, lng: number, known: boolean } => { const placeholderLat = 37.871853; const placeholderLng = -122.258423; const currentUserLat = currentUser && currentUser.mongoLocation && currentUser.mongoLocation.coordinates[1] const currentUserLng = currentUser && currentUser.mongoLocation && currentUser.mongoLocation.coordinates[0] if (currentUserLat && currentUserLng) { return {lat: currentUserLat, lng: currentUserLng, known: true} } return {lat: placeholderLat, lng: placeholderLng, known: false} } /** * Return the current user's location, by checking a few places. * * If the user is logged in, the location specified in their account settings is used first. * If the user is not logged in, then no location is available for server-side rendering, * but we can check if we've already saved a location in their browser's local storage. * * If we've failed to get a location for the user, finally try to get a location * client-side using the browser geolocation API. * (This won't necessarily work, since not all browsers and devices support it, and it requires user permission.) * This step is skipped if the "dontAsk" flag is set, to be less disruptive to the user * (for example, on the forum homepage). * * @param {UsersCurrent|DbUser|null} currentUser - The user we are checking. * @param {boolean} dontAsk - Flag that prevents us from asking the user for their browser's location. * * @returns {Object} locationData * @returns {number} locationData.lat - The user's latitude. * @returns {number} locationData.lng - The user's longitude. * @returns {boolean} locationData.loading - Indicates that we might have a known location later. * @returns {boolean} locationData.known - If false, then we're returning the default location instead of the user's location. * @returns {string} locationData.label - The string description of the location (ex: Cambridge, MA, USA). * @returns {Function} locationData.setLocationData - Function to set the location directly. */ export const useUserLocation = (currentUser: UsersCurrent|DbUser|null, dontAsk?: boolean): { lat: number, lng: number, loading: boolean, known: boolean, label: string, setLocationData: Function } => { // default is Berkeley, CA const placeholderLat = 37.871853 const placeholderLng = -122.258423 const defaultLocation = {lat: placeholderLat, lng: placeholderLng, loading: false, known: false, label: null} const currentUserLat = currentUser && currentUser.mongoLocation && currentUser.mongoLocation.coordinates[1] const currentUserLng = currentUser && currentUser.mongoLocation && currentUser.mongoLocation.coordinates[0] const [locationData, setLocationData] = useState(() => { if (currentUserLat && currentUserLng) { // First return a location from the user profile, if set return {lat: currentUserLat, lng: currentUserLng, loading: false, known: true, label: currentUser?.location} } else if (isServer) { // If there's no location in the user profile, we may still be able to get // a location from the browser--but not in SSR. return {lat: placeholderLat, lng: placeholderLng, loading: true, known: false, label: null} } else { // If we're on the browser, and the user isn't logged in, see if we saved it in local storage const ls = getBrowserLocalStorage() if (!currentUser && ls) { try { const lsLocation = JSON.parse(ls.getItem('userlocation')) if (lsLocation) { return {...lsLocation, loading: false} } } catch(e) { // eslint-disable-next-line no-console console.error(e) } } // If we couldn't get it from local storage, we'll try to get a location using the browser // geolocation API. This is not always available. if (!dontAsk && typeof window !== 'undefined' && typeof navigator !== 'undefined' && navigator && navigator.geolocation) { return {lat: placeholderLat, lng: placeholderLng, loading: true, known: false, label: null} } } return defaultLocation }) useEffect(() => { // if we don't yet have a location for the user and we're on the browser, // try to get the browser location if ( !dontAsk && !locationData.known && !isServer && typeof window !== 'undefined' && typeof navigator !== 'undefined' && navigator && navigator.geolocation ) { navigator.geolocation.getCurrentPosition((position) => { if (position && position.coords) { const navigatorLat = position.coords.latitude const navigatorLng = position.coords.longitude // label (location name) needs to be filled in by the caller setLocationData({lat: navigatorLat, lng: navigatorLng, loading: false, known: true, label: ''}) } else { setLocationData(defaultLocation) } }, (error) => { setLocationData(defaultLocation) } ) } //No exhaustive deps because this is supposed to run only on mount //eslint-disable-next-line react-hooks/exhaustive-deps }, []) return {...locationData, setLocationData} } // utility function for checking how much karma a user is supposed to have export const userGetAggregateKarma = async (user: DbUser): Promise<number> => { const posts = (await mongoFind("Posts", {userId:user._id})).map(post=>post._id) const comments = (await mongoFind("Comments", {userId:user._id})).map(comment=>comment._id) const documentIds = [...posts, ...comments] return (await mongoAggregate("Votes", [ {$match: { documentId: {$in:documentIds}, userId: {$ne: user._id}, cancelled: false }}, {$group: { _id: null, totalPower: { $sum: '$power' }}}, ]))[0].totalPower; } export const userGetPostCount = (user: UsersMinimumInfo|DbUser): number => { if (forumTypeSetting.get() === 'AlignmentForum') { return user.afPostCount; } else { return user.postCount; } } export const userGetCommentCount = (user: UsersMinimumInfo|DbUser): number => { if (forumTypeSetting.get() === 'AlignmentForum') { return user.afCommentCount; } else { return user.commentCount; } }
the_stack
import { types } from "@algo-builder/runtime"; import { ERRORS, tx as webTx, types as wtypes } from "@algo-builder/web"; import algosdk, { decodeSignedTransaction, encodeAddress, makeAssetCreateTxn, Transaction } from "algosdk"; import { assert } from "chai"; import { isArray } from "lodash"; import sinon from 'sinon'; import { TextEncoder } from "util"; import { executeTransaction } from "../../src"; import { DeployerDeployMode, DeployerRunMode } from "../../src/internal/deployer"; import { DeployerConfig } from "../../src/internal/deployer_cfg"; import { ConfirmedTxInfo, Deployer } from "../../src/types"; import { expectBuilderError, expectBuilderErrorAsync } from "../helpers/errors"; import { mkEnv } from "../helpers/params"; import { useFixtureProject, useFixtureProjectCopy } from "../helpers/project"; import { aliceAcc, bobAcc } from "../mocks/account"; import { mockAssetInfo, mockGenesisInfo, mockLsig, mockSuggestedParam } from "../mocks/tx"; import { AlgoOperatorDryRunImpl } from "../stubs/algo-operator"; describe("Note in TxParams", () => { const encoder = new TextEncoder(); const note = "Hello Algob!"; const noteb64 = "asdisaddas"; it("Both notes given", () => { const result = webTx.encodeNote(note, noteb64); assert.deepEqual(result, encoder.encode(noteb64), "noteb64 not encoded"); }); it("Only note given", () => { const result = webTx.encodeNote(note, undefined); assert.deepEqual(result, encoder.encode(note), "note not encoded"); }); it("Only noteb64 given", () => { const result = webTx.encodeNote(undefined, noteb64); assert.deepEqual(result, encoder.encode(noteb64), "noteb64 not encoded"); }); }); function mkASA (): wtypes.ASADef { return { total: 1, decimals: 1, unitName: 'ASA', defaultFrozen: false }; } function stubAlgodGenesisAndTxParams (algodClient: algosdk.Algodv2): void { sinon.stub(algodClient, "getTransactionParams") .returns({ do: async () => mockSuggestedParam } as ReturnType<algosdk.Algodv2['getTransactionParams']>); sinon.stub(algodClient, "genesis") .returns({ do: async () => mockGenesisInfo } as ReturnType<algosdk.Algodv2['genesis']>); } describe("Opt-In to ASA", () => { useFixtureProject("config-project"); let deployer: Deployer; let execParams: wtypes.OptInASAParam; let algod: AlgoOperatorDryRunImpl; let expected: ConfirmedTxInfo; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployerCfg.asaDefs = { silver: mkASA() }; deployer = new DeployerDeployMode(deployerCfg); await deployer.deployASA("silver", { creator: deployer.accounts[0] }); execParams = { type: wtypes.TransactionType.OptInASA, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: 1 }; stubAlgodGenesisAndTxParams(algod.algodClient); expected = { 'confirmed-round': 1, 'asset-index': 1, 'application-index': 1, 'global-state-delta': "string", 'local-state-delta': "string" }; }); afterEach(() => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("should opt-in to asa using asset id as number", async () => { const res = await executeTransaction(deployer, execParams); assert.deepEqual(res, expected); }); it("Should fail if asset name is passed but not found in checkpoints", async () => { execParams.assetID = "unknown"; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParams), ERRORS.BUILTIN_TASKS.DEPLOYER_ASA_NOT_DEFINED, "unknown" ); }); it("Should set asset id to asset id of asset name passed", async () => { execParams.assetID = "silver"; const res = await executeTransaction(deployer, execParams); assert.deepEqual(res, expected); }); }); describe("ASA modify fields", () => { useFixtureProject("config-project"); let deployer: Deployer; let execParams: wtypes.ModifyAssetParam; let algod: AlgoOperatorDryRunImpl; let assetFields: wtypes.AssetModFields; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployer = new DeployerDeployMode(deployerCfg); assetFields = { manager: "", clawback: bobAcc.addr }; execParams = { type: wtypes.TransactionType.ModifyAsset, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: 1, fields: assetFields }; stubAlgodGenesisAndTxParams(algod.algodClient); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); /** * Verifies correct asset fields are sent to network * @param rawTxns rawTxns Signed transactions in Uint8Array */ function checkTx (rawTxns: Uint8Array | Uint8Array[]): Promise<ConfirmedTxInfo> { if (isArray(rawTxns)) { // verify here if group tx } else { const tx: Transaction = decodeSignedTransaction(rawTxns).txn; // Verify if fields are set correctly assert.isUndefined(tx.assetManager); assert.isUndefined(tx.assetReserve); assert.equal(encodeAddress(tx.assetFreeze.publicKey), mockAssetInfo.params.freeze); assert.equal(encodeAddress(tx.assetClawback.publicKey), assetFields.clawback); } (algod.sendAndWait as sinon.SinonStub).restore(); return algod.sendAndWait(rawTxns); } it("Should set fields, freeze is not sent, therefore it should be picked from assetInfo", async () => { // Manager should be set to ""(sent as undefined to network) // Clawback should be updated sinon.stub(algod, "sendAndWait").callsFake(checkTx); await executeTransaction(deployer, execParams); }); }); describe("Delete ASA and SSC", () => { useFixtureProjectCopy("stateful"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployerCfg.asaDefs = { silver: mkASA() }; deployer = new DeployerDeployMode(deployerCfg); await deployer.deployASA("silver", { creator: deployer.accounts[0] }); stubAlgodGenesisAndTxParams(algod.algodClient); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("Should delete ASA, and set delete boolean in ASAInfo", async () => { const execParams: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: "silver" }; await executeTransaction(deployer, execParams); const res = deployer.getASAInfo("silver"); assert.equal(res.deleted, true); }); it("Should delete ASA If asset index is used, instead of asset name", async () => { const execParams: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: 1 }; await executeTransaction(deployer, execParams); const res = deployer.getASAInfo("silver"); assert.equal(res.deleted, true); }); it("Should not fail if ASA is not in checkpoints", async () => { const execParams: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: 2 }; await executeTransaction(deployer, execParams); }); it("Should delete SSC, set delete boolean in latest SSCInfo", async () => { const flags: types.AppDeploymentFlags = { sender: bobAcc, localBytes: 1, localInts: 1, globalBytes: 1, globalInts: 1 }; const info = await deployer.deployApp("approval.teal", "clear.teal", flags, {}); const execParams: wtypes.AppCallsParam = { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, appID: info.appID }; await executeTransaction(deployer, execParams); const res = deployer.getApp("approval.teal", "clear.teal"); assert.isDefined(res); if (res) assert.equal(res.deleted, true); }); it("Should not fail if SSC is not in checkpoints", async () => { const execParams: wtypes.AppCallsParam = { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, appID: 23 }; await executeTransaction(deployer, execParams); }); }); describe("Delete ASA and SSC transaction flow(with functions and executeTransaction)", () => { useFixtureProject("stateful"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; let appID: number; let assetID: number; const assetName = "silver"; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployerCfg.asaDefs = { silver: mkASA() }; deployer = new DeployerDeployMode(deployerCfg); stubAlgodGenesisAndTxParams(algod.algodClient); // deploy and delete asset const asaInfo = await deployer.deployASA(assetName, { creator: deployer.accounts[0] }); assetID = asaInfo.assetIndex; const execParams: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, assetID: 1 }; await executeTransaction(deployer, execParams); // deploy and delete app const flags: types.AppDeploymentFlags = { sender: bobAcc, localBytes: 1, localInts: 1, globalBytes: 1, globalInts: 1 }; const info = await deployer.deployApp("approval.teal", "clear.teal", flags, {}); appID = info.appID; const execParam: wtypes.AppCallsParam = { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, payFlags: {}, fromAccount: bobAcc, appID: info.appID }; await executeTransaction(deployer, execParam); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("should throw error with opt-in asa functions, if asa exist and deleted", async () => { await expectBuilderErrorAsync( async () => await deployer.optInAccountToASA(assetName, 'acc-name-1', {}), ERRORS.GENERAL.ASSET_DELETED ); await expectBuilderErrorAsync( async () => await deployer.optInLsigToASA(assetName, mockLsig, {}), ERRORS.GENERAL.ASSET_DELETED ); }); it("should pass with opt-in asa functions, if asa doesn't exist in checkpoint", async () => { await deployer.optInAccountToASA('23', 'acc-name-1', {}); await deployer.optInLsigToASA('233212', mockLsig, {}); }); it("should throw error with opt-in ssc functions, if ssc exist and deleted", async () => { await expectBuilderErrorAsync( async () => await deployer.optInAccountToApp(bobAcc, appID, {}, {}), ERRORS.GENERAL.APP_DELETED ); await expectBuilderErrorAsync( async () => await deployer.optInLsigToApp(appID, mockLsig, {}, {}), ERRORS.GENERAL.APP_DELETED ); }); it("should pass with opt-in ssc functions, if ssc doesn't exist in checkpoint", async () => { await deployer.optInAccountToApp(bobAcc, 122, {}, {}); await deployer.optInLsigToApp(12223, mockLsig, {}, {}); }); it("should throw error with update ssc function, if ssc exist and deleted", async () => { await expectBuilderErrorAsync( async () => await deployer.updateApp(bobAcc, {}, appID, "approval.teal", "clear.teal", {}), ERRORS.GENERAL.APP_DELETED ); }); it("should pass with update ssc functions, if ssc doesn't exist in checkpoint", async () => { await deployer.updateApp(bobAcc, {}, 123, "approval.teal", "clear.teal", {}); }); it("should fail if user tries to opt-in through execute tx", async () => { const execParam: wtypes.OptInASAParam = { type: wtypes.TransactionType.OptInASA, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should fail if user tries to modify through execute tx", async () => { const execParam: wtypes.ModifyAssetParam = { type: wtypes.TransactionType.ModifyAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID, fields: {} }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should fail if user tries to freeze through execute tx", async () => { const execParam: wtypes.FreezeAssetParam = { type: wtypes.TransactionType.FreezeAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID, freezeTarget: "acc-name-1", freezeState: true }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should fail if user tries to revoke through execute tx", async () => { const execParam: wtypes.RevokeAssetParam = { type: wtypes.TransactionType.RevokeAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID, recipient: bobAcc.addr, revocationTarget: "target", amount: 1000 }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should fail if user tries to destroy through execute tx", async () => { const execParam: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should fail if user tries to transfer asa through execute tx", async () => { const execParam: wtypes.AssetTransferParam = { type: wtypes.TransactionType.TransferAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: assetID, toAccountAddr: aliceAcc.addr, amount: 12 }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.ASSET_DELETED ); }); it("should pass if user tries to opt-out through execute tx", async () => { const execParam: wtypes.AssetTransferParam = { type: wtypes.TransactionType.TransferAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: { closeRemainderTo: bobAcc.addr }, assetID: assetID, toAccountAddr: aliceAcc.addr, amount: 12 }; await executeTransaction(deployer, execParam); }); it("should throw error if user tries to delete deleted app", async () => { const execParam: wtypes.AppCallsParam = { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.APP_DELETED ); }); it("should throw error if user tries to update deleted app", async () => { const execParam: wtypes.UpdateAppParam = { type: wtypes.TransactionType.UpdateApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID, newApprovalProgram: "approval.teal", newClearProgram: "clear.teal" }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.APP_DELETED ); }); it("should throw error if user tries to call deleted app", async () => { const execParam: wtypes.AppCallsParam = { type: wtypes.TransactionType.CallApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.APP_DELETED ); }); it("should throw error if user tries to opt-in deleted app", async () => { const execParam: wtypes.AppCallsParam = { type: wtypes.TransactionType.OptInToApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.APP_DELETED ); }); it("should pass if user tries to opt-out deleted app", async () => { const execParam: wtypes.AppCallsParam = { type: wtypes.TransactionType.CloseApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID }; await expectBuilderErrorAsync( async () => await executeTransaction(deployer, execParam), ERRORS.GENERAL.APP_DELETED ); const execParams: wtypes.AppCallsParam = { type: wtypes.TransactionType.ClearApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: appID }; await executeTransaction(deployer, execParams); }); it("should pass if user tries delete app that doesn't exist in checkpoint", async () => { const execParam: wtypes.DestroyAssetParam = { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: 123 }; await executeTransaction(deployer, execParam); }); it("should pass if user tries delete (asset + app) that doesn't exist in checkpoint", async () => { const txGroup: wtypes.ExecParams[] = [ { type: wtypes.TransactionType.DestroyAsset, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, assetID: 123 }, { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, payFlags: {}, appID: 12213 } ]; await executeTransaction(deployer, txGroup); }); }); describe("Deploy, Delete transactions test in run mode", () => { useFixtureProject("stateful"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; let deployerCfg: DeployerConfig; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); deployerCfg = new DeployerConfig(env, algod); deployerCfg.asaDefs = { silver: mkASA() }; deployer = new DeployerRunMode(deployerCfg); stubAlgodGenesisAndTxParams(algod.algodClient); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("should deploy asa in run mode", async () => { const execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployASA, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, asaName: 'silver', payFlags: {} }; await executeTransaction(deployer, execParams); // should not be stored in checkpoint if in run mode expectBuilderError( () => deployer.getASAInfo('silver'), ERRORS.BUILTIN_TASKS.DEPLOYER_ASA_NOT_DEFINED ); }); it("should deploy application in run mode", async () => { const execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {} }; await executeTransaction(deployer, execParams); // should not be stored in checkpoint if in run mode assert.isUndefined(deployer.getApp("approval.teal", "clear.teal")); }); it("should deploy application in deploy mode and save info by name", async () => { deployer = new DeployerDeployMode(deployerCfg); const execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {}, appName: "dao-app" }; await executeTransaction(deployer, execParams); // able to retrieve info by "appName" assert.isDefined(deployer.getAppByName("dao-app")); // do note that traditional way doesn't work if appName is passed assert.isUndefined(deployer.getApp("approval.teal", "clear.teal")); }); it("should delete application in run mode", async () => { deployer = new DeployerDeployMode(deployerCfg); let execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {} }; const appInfo = await executeTransaction(deployer, execParams); deployer = new DeployerRunMode(deployerCfg); execParams = { type: wtypes.TransactionType.DeleteApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, appID: appInfo['application-index'], payFlags: {} }; await executeTransaction(deployer, execParams); const res = deployer.getApp("approval.teal", "clear.teal"); assert.isDefined(res); assert.equal(res?.deleted, false); }); }); describe("Update transaction test in run mode", () => { useFixtureProject("stateful"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; let deployerCfg: DeployerConfig; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); deployerCfg = new DeployerConfig(env, algod); deployer = new DeployerRunMode(deployerCfg); stubAlgodGenesisAndTxParams(algod.algodClient); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("should update in run mode", async () => { let execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {} }; const appInfo = await executeTransaction(deployer, execParams); // should not be stored in checkpoint if in run mode assert.isUndefined(deployer.getApp("approval.teal", "clear.teal")); execParams = { type: wtypes.TransactionType.UpdateApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, appID: appInfo['application-index'], newApprovalProgram: "approval.teal", newClearProgram: "clear.teal", payFlags: {} }; await executeTransaction(deployer, execParams); // should not be stored in checkpoint if in run mode assert.isUndefined(deployer.getApp("approval.teal", "clear.teal")); }); it("deploy in deploy mode, update in run mode", async () => { deployer = new DeployerDeployMode(deployerCfg); let execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {} }; await executeTransaction(deployer, execParams); const appInfo = deployer.getApp("approval.teal", "clear.teal"); assert.isDefined(appInfo); deployer = new DeployerRunMode(deployerCfg); execParams = { type: wtypes.TransactionType.UpdateApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, appID: appInfo?.appID as number, newApprovalProgram: "approval.teal", newClearProgram: "clear.teal", payFlags: {} }; await executeTransaction(deployer, execParams); assert.deepEqual(appInfo, deployer.getApp("approval.teal", "clear.teal")); }); it("deploy in run mode, update in deploy mode", async () => { let execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, approvalProgram: "approval.teal", clearProgram: "clear.teal", localInts: 1, localBytes: 1, globalInts: 1, globalBytes: 1, payFlags: {} }; const appInfo = await executeTransaction(deployer, execParams); assert.isUndefined(deployer.getApp("approval.teal", "clear.teal")); deployer = new DeployerDeployMode(deployerCfg); execParams = { type: wtypes.TransactionType.UpdateApp, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, appID: appInfo['application-index'], newApprovalProgram: "approval.teal", newClearProgram: "clear.teal", payFlags: {} }; await executeTransaction(deployer, execParams); // checkpoint is stored for the update assert.isDefined(deployer.getApp("approval.teal", "clear.teal")); }); }); describe("Deploy ASA without asa.yaml", () => { useFixtureProject("config-project"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployerCfg.asaDefs = { silver: mkASA() }; deployer = new DeployerDeployMode(deployerCfg); stubAlgodGenesisAndTxParams(algod.algodClient); }); afterEach(async () => { (algod.algodClient.getTransactionParams as sinon.SinonStub).restore(); (algod.algodClient.genesis as sinon.SinonStub).restore(); }); it("should deploy asa without asa.yaml", async () => { const exp = { total: 10000, decimals: 0, defaultFrozen: false, unitName: "SLV", url: "url", metadataHash: "12312442142141241244444411111133", note: "note" }; const execParams: wtypes.ExecParams = { type: wtypes.TransactionType.DeployASA, sign: wtypes.SignType.SecretKey, fromAccount: bobAcc, asaName: 'silver-1', asaDef: exp, payFlags: {} }; await executeTransaction(deployer, execParams); const res = deployer.getASAInfo("silver-1"); assert.isDefined(res); assert.deepEqual(res.assetDef, exp); }); }); describe("SDK Transaction object", () => { useFixtureProject("config-project"); let deployer: Deployer; let algod: AlgoOperatorDryRunImpl; beforeEach(async () => { const env = mkEnv("network1"); algod = new AlgoOperatorDryRunImpl(); const deployerCfg = new DeployerConfig(env, algod); deployer = new DeployerDeployMode(deployerCfg); stubAlgodGenesisAndTxParams(algod.algodClient); }); it("should sign and send transaction", async () => { const tx = makeAssetCreateTxn( bobAcc.addr, mockSuggestedParam.fee, mockSuggestedParam.firstRound, mockSuggestedParam.lastRound, undefined, mockSuggestedParam.genesisHash, mockSuggestedParam.genesisID, 1e6, 0, false, undefined, undefined, undefined, undefined, "UM", "ASM", undefined ); const transaction: wtypes.TransactionAndSign = { transaction: tx, sign: { sign: wtypes.SignType.SecretKey, fromAccount: bobAcc } }; const res = await executeTransaction(deployer, transaction); assert.isDefined(res); assert.equal(res["confirmed-round"], 1); assert.equal(res["asset-index"], 1); }); });
the_stack
module Kiwi.Time { /** * The Clock class offers a way of tracking time within a game. * When creating a new Clock you should NOT directly instantiate this class * but instead use the addClock method on a ClockManager. * - The MasterClock is a property of the Kiwi.Time.Manager class and tracks * real world time in milliseconds elapsed since the application started. * This happens automatically and there is no need to do anything to set * this up. * - An instance of a clock is used to track time in arbitrary units * (milliseconds by default) * - A clock can be started, paused, unpaused and stopped. Once stopped, * re-starting the clock again will reset it. It can also have its time * scale freely transformed. * - Any number of timers can be attached to a clock. See the Kiwi.Time.Timer * class for timer details. * - If the clock is paused, any timers attached to the clock will take this * into account and not continue to fire events until the clock is * unpaused. (Note that this is not the same as pausing timers, which can * be done manually and needs to be undone manually.) * - Animations and TweenManagers can use any Clock. * * @class Clock * @namespace Kiwi.Time * @constructor * @param manager {ClockManager} ClockManager that this clock belongs to * @param master {Kiwi.Time.MasterClock} MasterClock that this is getting * the time in relation to * @param name {String} Name of the clock * @param [units=1000] {Number} Units that this clock is to operate in * per second * @return {Kiwi.Time.Clock} This Clock object */ export class Clock { constructor (manager:Kiwi.Time.ClockManager, master: Kiwi.Time.MasterClock, name: string, units: number = 1000) { this.manager = manager; this.master = master; this.name = name; this.units = units; this.timers = []; if (this.units < 1) { this.units = 1; } this._lastMasterElapsed = this.master.elapsed(); this._currentMasterElapsed = this.master.elapsed(); } /** * The type of object that this is * @method objType * @return {String} "Clock" * @public */ public objType() { return "Clock"; } /** * Collection of Timer objects using this clock * @property timers * @type Timer[] * @private */ private timers: Kiwi.Time.Timer[]; /** * Time the clock was first started relative to the master clock * @property _timeFirstStarted * @type Number * @default null * @private */ private _timeFirstStarted: number = null; /** * Number of clock units elapsed since the clock was first started * @method elapsedSinceFirstStarted * @return {Number} Number of clock units elapsed * @public */ public elapsedSinceFirstStarted(): number { return (this._timeLastStarted) ? (this.master.elapsed() - this._timeFirstStarted) / this.units : null; } /** * Most recent time the clock was started relative to the master clock * @property _timeLastStarted * @type Number * @default null * @private */ private _timeLastStarted: number = null; /** * Most recent time the clock was started relative to the master clock * @method started * @return {Number} Milliseconds * @public */ public started(): number { return this._timeLastStarted; } /** * Rate at which time passes on this clock. * 1 is normal speed. 1.5 is faster. 0 is no speed. -1 is backwards. * This mostly affects timers, animations and tweens. * @property timeScale * @type number * @default 1.0 * @public * @since 1.2.0 */ public timeScale: number = 1.0; /** * Clock units elapsed since the clock was most recently started, * not including paused time. * @property _elapsed * @type number * @private * @since 1.2.0 */ private _elapsed: number = 0; /** * Master time on last frame * @property _lastMasterElapsed * @type number * @private * @since 1.2.0 */ private _lastMasterElapsed: number; /** * Master time on current frame * @property _currentMasterElapsed * @type number * @private * @since 1.2.0 */ private _currentMasterElapsed: number; /** * Rate of time passage, as modified by time scale and frame rate. * Under ideal conditions this should be 1. * If the frame rate drops, this will rise. Multiply transformations * by rate to get smooth change over time. * @property rate * @type number * @public * @since 1.2.0 */ public rate: number = 1; /** * Maximum frame duration. If a frame takes longer than this to render, * the clock will only advance this far, in effect slowing down time. * If this value is 0 or less, it will not be checked and frames can * take any amount of time to render. * @property _maxFrameDuration * @type number * @default -1 * @private */ private _maxFrameDuration: number = -1; /** * Maximum frame duration. If a frame takes longer than this to render, * the clock will only advance this far, in effect slowing down time. * If this value is 0 or less, it will not be checked and frames can * take any amount of time to render. * @property maxFrameDuration * @type number * @default -1 * @public */ public get maxFrameDuration(): number { return this._maxFrameDuration; } public set maxFrameDuration( value: number ) { this._maxFrameDuration = value; } /** * Number of clock units elapsed since the clock was most recently * started (not including time spent paused) * @method elapsed * @return {Number} Number of clock units * @public */ public elapsed(): number { return this._elapsed; } /** * Time the clock was most recently stopped relative to the * master clock. * @property _timeLastStopped * @type Number * @default null * @private */ private _timeLastStopped: number = null; /** * Number of clock units elapsed since the clock was most recently * stopped. * @method elapsedSinceLastStopped * @return {Number} Number of clock units * @public */ public elapsedSinceLastStopped(): number { return (this._timeLastStarted) ? (this.master.elapsed() - this._timeLastStopped) / this.units : null; } /** * Time the clock was most receently paused relative to the * master clock. * @property _timeLastPaused * @private * @type Number * @default null * @private */ private _timeLastPaused: number = null; /** * Number of clock units elapsed since the clock was most recently paused. * @method elapsedSinceLastPaused * @return {Number} Number of clock units * @public */ public elapsedSinceLastPaused(): number { return (this._timeLastStarted) ? (this.master.elapsed() - this._timeLastPaused) / this.units : null; } /** * Time the clock was most recently unpaused relative to the * master clock. * @property _timeLastUnpaused * @private * @type Number * @default null * @private */ private _timeLastUnpaused: number = null; /** * Number of clock units elapsed since the clock was most recently * unpaused. * @method elapsedSinceLastUnpaused * @return {Number} Number of clock units * @public */ public elapsedSinceLastUnpaused(): number { return (this._timeLastStarted) ? (this.master.elapsed() - this._timeLastUnpaused) / this.units : null; } /** * Total number of milliseconds the clock has been paused * since it was last started * @property _totalPaused * @private * @type Number * @default 0 * @private */ private _totalPaused: number = 0; /** * Whether the clock is in a running state * @property _isRunning * @type boolean * @default false * @private */ private _isRunning: boolean = false; /** * Check if the clock is currently running * @method isRunning * @return {boolean} `true` if running * @public */ public isRunning(): boolean { return this._isRunning; } /** * Whether the clock is in a stopped state * @property _isStopped * @type boolean * @default true * @private */ private _isStopped: boolean = true; /** * Check if the clock is in the stopped state * @method isStopped * @return {boolean} `true` if stopped * @public */ public isStopped(): boolean { return this._isStopped; } /** * Whether the clock is in a paused state * @property _isPaused * @type boolean * @default false * @private */ private _isPaused: boolean = false; /** * Check if the clock is in the paused state * @method isPaused * @return {boolean} `true` if paused * @public */ public isPaused(): boolean { return this._isPaused; } /** * Internal reference to the state of the elapsed timer * @property _elapsedState * @type Number * @private */ private _elapsedState: number = Kiwi.Time.Clock._RUNNING; /** * Time manager that this clock belongs to * @property manager * @type ClockManager * @public */ public manager: Kiwi.Time.ClockManager = null; /** * Master clock from which time is derived * @property master * @type Kiwi.Time.MasterClock * @public */ public master: Kiwi.Time.MasterClock = null; /** * The time it takes for the time to update. Using this you can calculate the fps. * @property delta * @type number * @since 1.3.0 * @readOnly * @public */ public delta: number = 0; /** * Name of the clock * @property name * @type string * @public */ public name: string = null; /** * Number of milliseconds counted as one unit of time by the clock * @property units * @type Number * @default 0 * @public */ public units: number = 0; /** * Constant indicating that the Clock is running * (and has not yet been paused and resumed) * @property _RUNNING * @static * @type number * @default 0 * @private */ private static _RUNNING: number = 0; /** * Constant indicating that the Clock is paused * @property _PAUSED * @static * @type number * @default 1 * @private */ private static _PAUSED: number = 1; /** * Constant indicating that the Clock is running * (and has been paused then resumed) * @property _RESUMED * @static * @type number * @default 2 * @private */ private static _RESUMED: number = 2; /** * Constant indicating that the Clock is stopped * @property _STOPPED * @static * @type number * @default 3 * @private */ private static _STOPPED: number = 3; /** * Add an existing Timer to the Clock. * @method addTimer * @param timer {Timer} Timer object instance to be added to this Clock * @return {Kiwi.Time.Clock} This Clock object * @public */ public addTimer(timer: Timer): Clock { this.timers.push(timer); return this; } /** * Create a new Timer and add it to this Clock. * @method createTimer * @param name {string} Name of the Timer (must be unique on this Clock) * @param [delay=1] {Number} Number of clock units to wait between * firing events * @param [repeatCount=0] {Number} Number of times to repeat the Timer * (default 0) * @param [start=true] {Boolean} If the timer should start * @return {Kiwi.Time.Timer} The newly created Timer * @public */ public createTimer(name: string, delay: number = 1, repeatCount: number = 0, start: boolean=true): Timer { this.timers.push(new Timer(name, this, delay, repeatCount)); if (start === true) { this.timers[this.timers.length - 1].start(); } return this.timers[this.timers.length - 1]; } /** * Remove a Timer from this Clock based on either the Timer object * or its name. * @method removeTimer * @param [timer=null] {Timer} Timer object you wish to remove. * If you wish to delete by Timer Name set this to null. * @param [timerName=''] {string} Name of the Timer object to remove * @return {boolean} `true` if the Timer was successfully removed * @public */ public removeTimer(timer: Timer = null, timerName:string = ""): boolean { var index; // Timer object given? if ( timer !== null ) { index = this.timers.indexOf( timer ); if ( index !== -1 ) { this.timers.splice( index, 1 ); return true; } } else if ( timerName !== "" ) { for ( index = 0; index < this.timers.length; index++ ) { if ( this.timers[ index ].name === timerName ) { this.timers.splice( index, 1 ); return true; } } } return false; } /** * Check if the Timer already exists on this Clock. * @method checkExists * @param name {string} Name of the Timer * @return {boolean} `true` if the Timer exists * @public */ public checkExists(name: string): boolean { if (this.timers[name]) { return true; } else { return false; } } /** * Stop all timers attached to the clock. * @method stopAllTimers * @return {Clock} This Clock object * @public */ public stopAllTimers(): Clock { for (var i = 0; i < this.timers.length; i++) { this.timers[i].stop(); } return this; } /** * Convert a number to milliseconds based on clock units. * @method toMilliseconds * @param time {number} Seconds * @return {Number} Milliseconds * @public */ public convertToMilliseconds(time: number): number { return time * this.units; } /** * Update all Timers linked to this Clock. * @method update * @public */ public update() { var frameLength = this._currentMasterElapsed - this._lastMasterElapsed; if ( this._maxFrameDuration > 0 ) { frameLength = Math.min( frameLength, this._maxFrameDuration ); } for (var i = 0; i < this.timers.length; i++) { this.timers[i].update(); } // Compute difference between last master value and this // If clock is running, add that value to the current time this._lastMasterElapsed = this._currentMasterElapsed; this._currentMasterElapsed = this.master.elapsed(); this.delta = 0; if ( this._elapsedState === Kiwi.Time.Clock._RUNNING || this._elapsedState === Kiwi.Time.Clock._RESUMED ) { // Scale that difference by timeScale. Set "rate" as per running type this.delta = this.timeScale * frameLength / this.units; this._elapsed += this.delta; this.rate = this.timeScale * frameLength / this.master.idealDelta; } else if ( this._elapsedState === Kiwi.Time.Clock._PAUSED ) { this._totalPaused += frameLength; this.rate = 0; } else if ( this._elapsedState === Kiwi.Time.Clock._STOPPED ) { this.rate = 0; } } /** * Start the clock. This resets the clock and starts it running. * @method start * @return {Clock} This Clock object * @public */ public start(): Clock { this._timeLastStarted = this.master.elapsed(); this._totalPaused = 0; if (!this._timeFirstStarted) { this._timeFirstStarted = this._timeLastStarted; } this._isRunning = true; this._isPaused = false; this._isStopped = false; this._elapsedState = Kiwi.Time.Clock._RUNNING; this._elapsed = 0; this._lastMasterElapsed = this.master.elapsed(); this._currentMasterElapsed = this.master.elapsed(); return this; } /** * Pause the clock. This can only be paused if it is already running. * @method pause * @return {Kiwi.Time.Clock} This Clock object * @public */ public pause(): Clock { if (this._isRunning === true) { this._timeLastPaused = this.master.elapsed(); this._isRunning = false; this._isPaused = true; this._isStopped = false; this._elapsedState = Kiwi.Time.Clock._PAUSED; } return this; } /** * Resume the clock. This can only be resumed if it is already paused. * @method resume * @return {Kiwi.Time.Clock} This Clock object * @public */ public resume(): Clock { if (this._isPaused === true) { this._timeLastUnpaused = this.master.elapsed(); this._totalPaused += this._timeLastUnpaused - this._timeLastPaused; this._isRunning = true; this._isPaused = false; this._isStopped = false; this._elapsedState = Kiwi.Time.Clock._RESUMED; } return this; } /** * Stop the clock. This can only be stopped if it is already running * or is paused. * @method stop * @return {Kiwi.Time.Clock} This Clock object * @public */ public stop(): Clock { if (this._isStopped === false) { this._timeLastStopped = this.master.elapsed(); if (this._isPaused === true) { this._totalPaused += this._timeLastStopped - this._timeLastPaused; } this._isRunning = false; this._isPaused = false; this._isStopped = true; this._elapsedState = Kiwi.Time.Clock._STOPPED; } return this; } /** * Return a string representation of this object. * @method toString * @return {string} String representation of the instance * @public */ public toString(): string { return "[{Clock (name=" + this.name + " units=" + this.units + " running=" + this._isRunning + ")}]"; } /** * Set a function to execute after a certain time interval. * Emulates `window.setTimeout`, except attached to a `Kiwi.Time.Clock`. * This allows you to pause and manipulate time, and the timeout will * respect the clock on which it is created. * * No `clearTimeout` is provided; you should use `Kiwi.Time.Timer` * functions to achieve further control. * * Any parameters after `context` will be passed as parameters to the * callback function. Note that you must specify `context` in order for * this to work. You may specify `null`, in which case it will default * to the global scope `window`. * * @method setTimeout * @param callback {function} Function to execute * @param timeout {number} Milliseconds before execution * @param [context] {object} Object to be `this` for the callback * @return {Kiwi.Time.Timer} Kiwi.Time.Timer object which can be used * to further manipulate the timer * @public */ public setTimeout( callback, timeout: number, context, ...args ): Timer { var clock = this, timer = this.createTimer( "timeoutTimer", timeout / this.units ); if ( !context ) { context = this; } timer.createTimerEvent( TimerEvent.TIMER_STOP, function() { callback.apply( context, args ); clock.removeTimer( timer ); }, context ); timer.start(); return timer; } /** * Set a function to repeatedly execute at fixed time intervals. * Emulates `window.setInterval`, except attached to a `Kiwi.Time.Clock`. * This allows you to pause and manipulate time, and the timeout will * respect the clock on which it is created. * * No `clearInterval` is provided; you should use `Kiwi.Time.Timer` * functions to achieve further control. * * Any parameters after `context` will be passed as parameters to the * callback function. Note that you must specify `context` in order for * this to work. You may specify `null`, in which case it will default * to the global scope `window`. * * @method setInterval * @param callback {function} Function to execute * @param timeout {number} Milliseconds between executions * @param [context=window] {object} Object to be `this` for the callback * @return {Kiwi.Time.Timer} Kiwi.Time.Timer object * which can be used to further manipulate the timer * @public */ public setInterval( callback, timeout: number, context, ...args ): Timer { var timer = this.createTimer( "intervalTimer", timeout / this.units, -1 ); if ( !context ) { context = this; } timer.createTimerEvent( TimerEvent.TIMER_COUNT, function() { callback.apply( context, args ); }, context ); timer.start(); return timer; } } }
the_stack
import { OrderErrorCode, OrderEventsEmailsEnum, OrderEventsEnum, FulfillmentStatus, PaymentChargeStatusEnum, OrderStatus, OrderAction, JobStatusEnum } from "./../../types/globalTypes"; // ==================================================== // GraphQL mutation operation: OrderLineDiscountDelete // ==================================================== export interface OrderLineDiscountDelete_orderLineDiscountDelete_errors { __typename: "OrderError"; code: OrderErrorCode; field: string | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_metadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_privateMetadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_billingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_billingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderLineDiscountDelete_orderLineDiscountDelete_order_billingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_events_relatedOrder { __typename: "Order"; id: string; number: string | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_events_user { __typename: "User"; id: string; email: string; firstName: string; lastName: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_events_lines_orderLine { __typename: "OrderLine"; id: string; productName: string; variantName: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_events_lines { __typename: "OrderEventOrderLineObject"; quantity: number | null; orderLine: OrderLineDiscountDelete_orderLineDiscountDelete_order_events_lines_orderLine | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_events { __typename: "OrderEvent"; id: string; amount: number | null; shippingCostsIncluded: boolean | null; date: any | null; email: string | null; emailType: OrderEventsEmailsEnum | null; invoiceNumber: string | null; relatedOrder: OrderLineDiscountDelete_orderLineDiscountDelete_order_events_relatedOrder | null; message: string | null; quantity: number | null; transactionReference: string | null; type: OrderEventsEnum | null; user: OrderLineDiscountDelete_orderLineDiscountDelete_order_events_user | null; lines: (OrderLineDiscountDelete_orderLineDiscountDelete_order_events_lines | null)[] | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice_gross; net: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice_net; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_thumbnail { __typename: "Image"; url: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_variant | null; productName: string; productSku: string; quantity: number; quantityFulfilled: number; unitPrice: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_unitPrice; thumbnail: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine_thumbnail | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines { __typename: "FulfillmentLine"; id: string; quantity: number; orderLine: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines_orderLine | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_warehouse { __typename: "Warehouse"; id: string; name: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments { __typename: "Fulfillment"; id: string; lines: (OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_lines | null)[] | null; fulfillmentOrder: number; status: FulfillmentStatus; trackingNumber: string; warehouse: OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments_warehouse | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice_gross; net: OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice_net; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_thumbnail { __typename: "Image"; url: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_lines { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_variant | null; productName: string; productSku: string; quantity: number; quantityFulfilled: number; unitPrice: OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_unitPrice; thumbnail: OrderLineDiscountDelete_orderLineDiscountDelete_order_lines_thumbnail | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingMethod { __typename: "ShippingMethod"; id: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingPrice { __typename: "TaxedMoney"; gross: OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingPrice_gross; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_subtotal_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_subtotal { __typename: "TaxedMoney"; gross: OrderLineDiscountDelete_orderLineDiscountDelete_order_subtotal_gross; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_total_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_total_tax { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_total { __typename: "TaxedMoney"; gross: OrderLineDiscountDelete_orderLineDiscountDelete_order_total_gross; tax: OrderLineDiscountDelete_orderLineDiscountDelete_order_total_tax; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_totalAuthorized { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_totalCaptured { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_user { __typename: "User"; id: string; email: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_availableShippingMethods_price { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_availableShippingMethods { __typename: "ShippingMethod"; id: string; name: string; price: OrderLineDiscountDelete_orderLineDiscountDelete_order_availableShippingMethods_price | null; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_discount { __typename: "Money"; amount: number; currency: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_invoices { __typename: "Invoice"; id: string; number: string | null; createdAt: any; url: string | null; status: JobStatusEnum; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order_channel { __typename: "Channel"; isActive: boolean; id: string; name: string; currencyCode: string; } export interface OrderLineDiscountDelete_orderLineDiscountDelete_order { __typename: "Order"; id: string; metadata: (OrderLineDiscountDelete_orderLineDiscountDelete_order_metadata | null)[]; privateMetadata: (OrderLineDiscountDelete_orderLineDiscountDelete_order_privateMetadata | null)[]; billingAddress: OrderLineDiscountDelete_orderLineDiscountDelete_order_billingAddress | null; canFinalize: boolean; created: any; customerNote: string; events: (OrderLineDiscountDelete_orderLineDiscountDelete_order_events | null)[] | null; fulfillments: (OrderLineDiscountDelete_orderLineDiscountDelete_order_fulfillments | null)[]; lines: (OrderLineDiscountDelete_orderLineDiscountDelete_order_lines | null)[]; number: string | null; paymentStatus: PaymentChargeStatusEnum; shippingAddress: OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingAddress | null; shippingMethod: OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingMethod | null; shippingMethodName: string | null; shippingPrice: OrderLineDiscountDelete_orderLineDiscountDelete_order_shippingPrice; status: OrderStatus; subtotal: OrderLineDiscountDelete_orderLineDiscountDelete_order_subtotal; total: OrderLineDiscountDelete_orderLineDiscountDelete_order_total; actions: (OrderAction | null)[]; totalAuthorized: OrderLineDiscountDelete_orderLineDiscountDelete_order_totalAuthorized; totalCaptured: OrderLineDiscountDelete_orderLineDiscountDelete_order_totalCaptured; user: OrderLineDiscountDelete_orderLineDiscountDelete_order_user | null; userEmail: string | null; availableShippingMethods: (OrderLineDiscountDelete_orderLineDiscountDelete_order_availableShippingMethods | null)[] | null; discount: OrderLineDiscountDelete_orderLineDiscountDelete_order_discount | null; invoices: (OrderLineDiscountDelete_orderLineDiscountDelete_order_invoices | null)[] | null; channel: OrderLineDiscountDelete_orderLineDiscountDelete_order_channel; isPaid: boolean; } export interface OrderLineDiscountDelete_orderLineDiscountDelete { __typename: "OrderLineDiscountDelete"; errors: OrderLineDiscountDelete_orderLineDiscountDelete_errors[]; order: OrderLineDiscountDelete_orderLineDiscountDelete_order | null; } export interface OrderLineDiscountDelete { orderLineDiscountDelete: OrderLineDiscountDelete_orderLineDiscountDelete | null; } export interface OrderLineDiscountDeleteVariables { orderLineId: string; }
the_stack
import { CFB$Container, CFB$Entry } from 'cfb'; import { WorkBook, WorkSheet, Range, CellObject } from '../'; import type { utils } from "../"; declare var encode_cell: typeof utils.encode_cell; declare var encode_range: typeof utils.encode_range; declare var book_new: typeof utils.book_new; declare var book_append_sheet: typeof utils.book_append_sheet; declare var sheet_to_json: typeof utils.sheet_to_json; declare var decode_range: typeof utils.decode_range; import * as _CFB from 'cfb'; declare var CFB: typeof _CFB; //<<import { utils } from "../../"; //<<const { encode_cell, encode_range, book_new, book_append_sheet } = utils; function u8_to_dataview(array: Uint8Array): DataView { return new DataView(array.buffer, array.byteOffset, array.byteLength); } //<<export { u8_to_dataview }; function u8str(u8: Uint8Array): string { return /* Buffer.isBuffer(u8) ? u8.toString() :*/ typeof TextDecoder != "undefined" ? new TextDecoder().decode(u8) : utf8read(a2s(u8)); } function stru8(str: string): Uint8Array { return typeof TextEncoder != "undefined" ? new TextEncoder().encode(str) : s2a(utf8write(str)) as Uint8Array; } //<<export { u8str, stru8 }; function u8contains(body: Uint8Array, search: Uint8Array): boolean { outer: for(var L = 0; L <= body.length - search.length; ++L) { for(var j = 0; j < search.length; ++j) if(body[L+j] != search[j]) continue outer; return true; } return false; } //<<export { u8contains } /** Concatenate Uint8Arrays */ function u8concat(u8a: Uint8Array[]): Uint8Array { var len = u8a.reduce((acc: number, x: Uint8Array) => acc + x.length, 0); var out = new Uint8Array(len); var off = 0; u8a.forEach(u8 => { out.set(u8, off); off += u8.length; }); return out; } //<<export { u8concat }; /** Count the number of bits set (assuming int32_t interpretation) */ function popcnt(x: number): number { x -= ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24; } /** Read a 128-bit decimal from the modern cell storage */ function readDecimal128LE(buf: Uint8Array, offset: number): number { var exp = ((buf[offset + 15] & 0x7F) << 7) | (buf[offset + 14] >> 1); var mantissa = buf[offset + 14] & 1; for(var j = offset + 13; j >= offset; --j) mantissa = mantissa * 256 + buf[j]; return ((buf[offset+15] & 0x80) ? -mantissa : mantissa) * Math.pow(10, exp - 0x1820); } /** Write a 128-bit decimal to the modern cell storage */ function writeDecimal128LE(buf: Uint8Array, offset: number, value: number): void { // TODO: something more correct than this var exp = Math.floor(value == 0 ? 0 : /*Math.log10*/Math.LOG10E * Math.log(Math.abs(value))) + 0x1820 - 16; var mantissa = (value / Math.pow(10, exp - 0x1820)); buf[offset+15] |= exp >> 7; buf[offset+14] |= (exp & 0x7F) << 1; for(var i = 0; mantissa >= 1; ++i, mantissa /= 256) buf[offset + i] = mantissa & 0xFF; buf[offset+15] |= (value >= 0 ? 0 : 0x80); } type Ptr = [number]; /** Parse an integer from the varint that can be exactly stored in a double */ function parse_varint49(buf: Uint8Array, ptr?: Ptr): number { var l = ptr ? ptr[0] : 0; var usz = buf[l] & 0x7F; varint: if(buf[l++] >= 0x80) { usz |= (buf[l] & 0x7F) << 7; if(buf[l++] < 0x80) break varint; usz |= (buf[l] & 0x7F) << 14; if(buf[l++] < 0x80) break varint; usz |= (buf[l] & 0x7F) << 21; if(buf[l++] < 0x80) break varint; usz += (buf[l] & 0x7F) * Math.pow(2, 28); ++l; if(buf[l++] < 0x80) break varint; usz += (buf[l] & 0x7F) * Math.pow(2, 35); ++l; if(buf[l++] < 0x80) break varint; usz += (buf[l] & 0x7F) * Math.pow(2, 42); ++l; if(buf[l++] < 0x80) break varint; } if(ptr) ptr[0] = l; return usz; } /** Write a varint up to 7 bytes / 49 bits */ function write_varint49(v: number): Uint8Array { var usz = new Uint8Array(7); usz[0] = (v & 0x7F); var L = 1; sz: if(v > 0x7F) { usz[L-1] |= 0x80; usz[L] = (v >> 7) & 0x7F; ++L; if(v <= 0x3FFF) break sz; usz[L-1] |= 0x80; usz[L] = (v >> 14) & 0x7F; ++L; if(v <= 0x1FFFFF) break sz; usz[L-1] |= 0x80; usz[L] = (v >> 21) & 0x7F; ++L; if(v <= 0xFFFFFFF) break sz; usz[L-1] |= 0x80; usz[L] = ((v/0x100) >>> 21) & 0x7F; ++L; if(v <= 0x7FFFFFFFF) break sz; usz[L-1] |= 0x80; usz[L] = ((v/0x10000) >>> 21) & 0x7F; ++L; if(v <= 0x3FFFFFFFFFF) break sz; usz[L-1] |= 0x80; usz[L] = ((v/0x1000000) >>> 21) & 0x7F; ++L; } return usz.slice(0, L); } //<<export { parse_varint49, write_varint49 }; /** Parse a 32-bit signed integer from the raw varint */ function varint_to_i32(buf: Uint8Array): number { var l = 0, i32 = buf[l] & 0x7F; varint: if(buf[l++] >= 0x80) { i32 |= (buf[l] & 0x7F) << 7; if(buf[l++] < 0x80) break varint; i32 |= (buf[l] & 0x7F) << 14; if(buf[l++] < 0x80) break varint; i32 |= (buf[l] & 0x7F) << 21; if(buf[l++] < 0x80) break varint; i32 |= (buf[l] & 0x7F) << 28; } return i32; } //<<export { varint_to_i32 }; interface ProtoItem { data: Uint8Array; type: number; } type ProtoField = Array<ProtoItem> type ProtoMessage = Array<ProtoField>; /** Shallow parse of a Protobuf message */ function parse_shallow(buf: Uint8Array): ProtoMessage { var out: ProtoMessage = [], ptr: Ptr = [0]; while(ptr[0] < buf.length) { var off = ptr[0]; var num = parse_varint49(buf, ptr); var type = num & 0x07; num = Math.floor(num / 8); var len = 0; var res: Uint8Array; if(num == 0) break; switch(type) { case 0: { var l = ptr[0]; while(buf[ptr[0]++] >= 0x80); res = buf.slice(l, ptr[0]); } break; case 5: len = 4; res = buf.slice(ptr[0], ptr[0] + len); ptr[0] += len; break; case 1: len = 8; res = buf.slice(ptr[0], ptr[0] + len); ptr[0] += len; break; case 2: len = parse_varint49(buf, ptr); res = buf.slice(ptr[0], ptr[0] + len); ptr[0] += len; break; case 3: // Start group case 4: // End group default: throw new Error(`PB Type ${type} for Field ${num} at offset ${off}`); } var v: ProtoItem = { data: res, type }; if(out[num] == null) out[num] = [v]; else out[num].push(v); } return out; } /** Serialize a shallow parse */ function write_shallow(proto: ProtoMessage): Uint8Array { var out: Uint8Array[] = []; proto.forEach((field, idx) => { if(idx == 0) return; field.forEach(item => { if(!item.data) return; out.push(write_varint49(idx * 8 + item.type)); if(item.type == 2) out.push(write_varint49(item.data.length)); out.push(item.data); }); }); return u8concat(out); } //<<export { parse_shallow, write_shallow }; /** Map over each entry in a repeated (or single-value) field */ function mappa<U>(data: ProtoField, cb:(Uint8Array) => U): U[] { return data?.map(d => cb(d.data)) || []; } interface IWAMessage { /** Metadata in .TSP.MessageInfo */ meta: ProtoMessage; data: Uint8Array; } interface IWAArchiveInfo { id?: number; merge?: boolean; messages?: IWAMessage[]; } /** Extract all messages from a IWA file */ function parse_iwa_file(buf: Uint8Array): IWAArchiveInfo[] { var out: IWAArchiveInfo[] = [], ptr: Ptr = [0]; while(ptr[0] < buf.length) { /* .TSP.ArchiveInfo */ var len = parse_varint49(buf, ptr); var ai = parse_shallow(buf.slice(ptr[0], ptr[0] + len)); ptr[0] += len; var res: IWAArchiveInfo = { /* TODO: technically ID is optional */ id: varint_to_i32(ai[1][0].data), messages: [] }; ai[2].forEach(b => { var mi = parse_shallow(b.data); var fl = varint_to_i32(mi[3][0].data); res.messages.push({ meta: mi, data: buf.slice(ptr[0], ptr[0] + fl) }); ptr[0] += fl; }); if(ai[3]?.[0]) res.merge = (varint_to_i32(ai[3][0].data) >>> 0) > 0; out.push(res); } return out; } /** Generate an IWA file from a parsed structure */ function write_iwa_file(ias: IWAArchiveInfo[]): Uint8Array { var bufs: Uint8Array[] = []; ias.forEach(ia => { var ai: ProtoMessage = [ [], [ {data: write_varint49(ia.id), type: 0} ], [] ]; if(ia.merge != null) ai[3] = [ { data: write_varint49(+!!ia.merge), type: 0 } ]; var midata: Uint8Array[] = []; ia.messages.forEach(mi => { midata.push(mi.data); mi.meta[3] = [ { type: 0, data: write_varint49(mi.data.length) } ]; ai[2].push({data: write_shallow(mi.meta), type: 2}); }); var aipayload = write_shallow(ai); bufs.push(write_varint49(aipayload.length)); bufs.push(aipayload); midata.forEach(mid => bufs.push(mid)); }); return u8concat(bufs); } //<<export { IWAMessage, IWAArchiveInfo, parse_iwa_file, write_iwa_file }; /** Decompress a snappy chunk */ function parse_snappy_chunk(type: number, buf: Uint8Array): Uint8Array { if(type != 0) throw new Error(`Unexpected Snappy chunk type ${type}`); var ptr: Ptr = [0]; var usz = parse_varint49(buf, ptr); var chunks = []; while(ptr[0] < buf.length) { var tag = buf[ptr[0]] & 0x3; if(tag == 0) { var len = buf[ptr[0]++] >> 2; if(len < 60) ++len; else { var c = len - 59; len = buf[ptr[0]]; if(c > 1) len |= (buf[ptr[0]+1]<<8); if(c > 2) len |= (buf[ptr[0]+2]<<16); if(c > 3) len |= (buf[ptr[0]+3]<<24); len >>>=0; len++; ptr[0] += c; } chunks.push(buf.slice(ptr[0], ptr[0] + len)); ptr[0] += len; continue; } else { var offset = 0, length = 0; if(tag == 1) { length = ((buf[ptr[0]] >> 2) & 0x7) + 4; offset = (buf[ptr[0]++] & 0xE0) << 3; offset |= buf[ptr[0]++]; } else { length = (buf[ptr[0]++] >> 2) + 1; if(tag == 2) { offset = buf[ptr[0]] | (buf[ptr[0]+1]<<8); ptr[0] += 2; } else { offset = (buf[ptr[0]] | (buf[ptr[0]+1]<<8) | (buf[ptr[0]+2]<<16) | (buf[ptr[0]+3]<<24))>>>0; ptr[0] += 4; } } chunks = [u8concat(chunks)]; if(offset == 0) throw new Error("Invalid offset 0"); if(offset > chunks[0].length) throw new Error("Invalid offset beyond length"); if(length >= offset) { chunks.push(chunks[0].slice(-offset)); length -= offset; while(length >= chunks[chunks.length-1].length) { chunks.push(chunks[chunks.length - 1]); length -= chunks[chunks.length - 1].length; } } chunks.push(chunks[0].slice(-offset, -offset + length)); } } var o = u8concat(chunks); if(o.length != usz) throw new Error(`Unexpected length: ${o.length} != ${usz}`); return o; } /** Decompress IWA file */ function decompress_iwa_file(buf: Uint8Array): Uint8Array { var out = []; var l = 0; while(l < buf.length) { var t = buf[l++]; var len = buf[l] | (buf[l+1]<<8) | (buf[l+2] << 16); l += 3; out.push(parse_snappy_chunk(t, buf.slice(l, l + len))); l += len; } if(l !== buf.length) throw new Error("data is not a valid framed stream!"); return u8concat(out); } /** Compress IWA file */ function compress_iwa_file(buf: Uint8Array): Uint8Array { var out: Uint8Array[] = []; var l = 0; while(l < buf.length) { var c = Math.min(buf.length - l, 0xFFFFFFF); var frame = new Uint8Array(4); out.push(frame); var usz = write_varint49(c); var L = usz.length; out.push(usz); if(c <= 60) { L++; out.push(new Uint8Array([(c - 1)<<2])); } else if(c <= 0x100) { L += 2; out.push(new Uint8Array([0xF0, (c-1) & 0xFF])); } else if(c <= 0x10000) { L += 3; out.push(new Uint8Array([0xF4, (c-1) & 0xFF, ((c-1) >> 8) & 0xFF])); } else if(c <= 0x1000000) { L += 4; out.push(new Uint8Array([0xF8, (c-1) & 0xFF, ((c-1) >> 8) & 0xFF, ((c-1) >> 16) & 0xFF])); } else if(c <= 0x100000000) { L += 5; out.push(new Uint8Array([0xFC, (c-1) & 0xFF, ((c-1) >> 8) & 0xFF, ((c-1) >> 16) & 0xFF, ((c-1) >>> 24) & 0xFF])); } out.push(buf.slice(l, l + c)); L += c; frame[0] = 0; frame[1] = L & 0xFF; frame[2] = (L >> 8) & 0xFF; frame[3] = (L >> 16) & 0xFF; l += c; } return u8concat(out); } //<<export { decompress_iwa_file, compress_iwa_file }; /** Parse "old storage" (version 0..3) */ function parse_old_storage(buf: Uint8Array, sst: string[], rsst: string[], v: 0|1|2|3): CellObject { var dv = u8_to_dataview(buf); var flags = dv.getUint32(4, true); /* TODO: find the correct field position of number formats, formulae, etc */ var data_offset = (v > 1 ? 12 : 8) + popcnt(flags & (v > 1 ? 0x0D8E : 0x018E)) * 4; var ridx = -1, sidx = -1, ieee = NaN, dt = new Date(2001, 0, 1); if(flags & 0x0200) { ridx = dv.getUint32(data_offset, true); data_offset += 4; } data_offset += popcnt(flags & (v > 1 ? 0x3000 : 0x1000)) * 4; if(flags & 0x0010) { sidx = dv.getUint32(data_offset, true); data_offset += 4; } if(flags & 0x0020) { ieee = dv.getFloat64(data_offset, true); data_offset += 8; } if(flags & 0x0040) { dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1000); data_offset += 8; } var ret: CellObject; switch(buf[2]) { case 0: break; // return { t: "z" }; // blank? case 2: ret = { t: "n", v: ieee }; break; // number case 3: ret = { t: "s", v: sst[sidx] }; break; // string case 5: ret = { t: "d", v: dt }; break; // date-time case 6: ret = { t: "b", v: ieee > 0 }; break; // boolean case 7: ret = { t: "n", v: ieee / 86400 }; break; // duration in seconds TODO: emit [hh]:[mm] style format with adjusted value case 8: ret = { t: "e", v: 0}; break; // "formula error" TODO: enumerate and map errors to csf equivalents case 9: { // "rich text" if(ridx > -1) ret = { t: "s", v: rsst[ridx] }; else throw new Error(`Unsupported cell type ${buf.slice(0,4)}`); } break; default: throw new Error(`Unsupported cell type ${buf.slice(0,4)}`); } /* TODO: Some fields appear after the cell data */ return ret; } /** Parse "new storage" (version 5) */ function parse_new_storage(buf: Uint8Array, sst: string[], rsst: string[]): CellObject { var dv = u8_to_dataview(buf); var flags = dv.getUint32(8, true); /* TODO: find the correct field position of number formats, formulae, etc */ var data_offset = 12; var ridx = -1, sidx = -1, d128 = NaN, ieee = NaN, dt = new Date(2001, 0, 1); if(flags & 0x0001) { d128 = readDecimal128LE(buf, data_offset); data_offset += 16; } if(flags & 0x0002) { ieee = dv.getFloat64(data_offset, true); data_offset += 8; } if(flags & 0x0004) { dt.setTime(dt.getTime() + dv.getFloat64(data_offset, true) * 1000); data_offset += 8; } if(flags & 0x0008) { sidx = dv.getUint32(data_offset, true); data_offset += 4; } if(flags & 0x0010) { ridx = dv.getUint32(data_offset, true); data_offset += 4; } var ret: CellObject; switch(buf[1]) { case 0: break; // return { t: "z" }; // blank? case 2: ret = { t: "n", v: d128 }; break; // number case 3: ret = { t: "s", v: sst[sidx] }; break; // string case 5: ret = { t: "d", v: dt }; break; // date-time case 6: ret = { t: "b", v: ieee > 0 }; break; // boolean case 7: ret = { t: "n", v: ieee / 86400 }; break; // duration in seconds TODO: emit [hh]:[mm] style format with adjusted value case 8: ret = { t: "e", v: 0}; break; // "formula error" TODO: enumerate and map errors to csf equivalents case 9: { // "rich text" if(ridx > -1) ret = { t: "s", v: rsst[ridx] }; else throw new Error(`Unsupported cell type ${buf[1]} : ${flags & 0x1F} : ${buf.slice(0,4)}`); } break; case 10: ret = { t: "n", v: d128 }; break; // currency default: throw new Error(`Unsupported cell type ${buf[1]} : ${flags & 0x1F} : ${buf.slice(0,4)}`); } /* TODO: All styling fields appear after the cell data */ return ret; } /** Write a cell "new storage" (version 5) */ function write_new_storage(cell: CellObject, sst: string[]): Uint8Array { var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0; out[0] = 5; switch(cell.t) { case "n": out[1] = 2; writeDecimal128LE(out, l, cell.v as number); flags |= 1; l += 16; break; case "b": out[1] = 6; dv.setFloat64(l, cell.v ? 1 : 0, true); flags |= 2; l += 8; break; case "s": if(sst.indexOf(cell.v as string) == -1) throw new Error(`Value ${cell.v} missing from SST!`); out[1] = 3; dv.setUint32(l, sst.indexOf(cell.v as string), true); flags |= 8; l += 4; break; default: throw "unsupported cell type " + cell.t; } dv.setUint32(8, flags, true); return out.slice(0, l); } /** Write a cell "old storage" (version 3) */ function write_old_storage(cell: CellObject, sst: string[]): Uint8Array { var out = new Uint8Array(32), dv = u8_to_dataview(out), l = 12, flags = 0; out[0] = 3; switch(cell.t) { case "n": out[2] = 2; dv.setFloat64(l, cell.v as number, true); flags |= 0x20; l += 8; break; case "b": out[2] = 6; dv.setFloat64(l, cell.v ? 1 : 0, true); flags |= 0x20; l += 8; break; case "s": if(sst.indexOf(cell.v as string) == -1) throw new Error(`Value ${cell.v} missing from SST!`); out[2] = 3; dv.setUint32(l, sst.indexOf(cell.v as string), true); flags |= 0x10; l += 4; break; default: throw "unsupported cell type " + cell.t; } dv.setUint32(4, flags, true); return out.slice(0, l); } //<<export { write_new_storage, write_old_storage }; function parse_cell_storage(buf: Uint8Array, sst: string[], rsst: string[]): CellObject { switch(buf[0]) { case 0: case 1: case 2: case 3: return parse_old_storage(buf, sst, rsst, buf[0]); case 5: return parse_new_storage(buf, sst, rsst); default: throw new Error(`Unsupported payload version ${buf[0]}`); } } /** .TSS.StylesheetArchive */ //function parse_TSS_StylesheetArchive(M: IWAMessage[][], root: IWAMessage): void { // var pb = parse_shallow(root.data); //} /** Parse .TSP.Reference */ function parse_TSP_Reference(buf: Uint8Array): number { var pb = parse_shallow(buf); return parse_varint49(pb[1][0].data); } /** Write .TSP.Reference */ function write_TSP_Reference(idx: number): Uint8Array { return write_shallow([ [], [ { type: 0, data: write_varint49(idx) } ] ]); } //<<export { parse_TSP_Reference, write_TSP_Reference }; type MessageSpace = {[id: number]: IWAMessage[]}; /** Parse .TST.TableDataList */ function parse_TST_TableDataList(M: MessageSpace, root: IWAMessage): string[] { var pb = parse_shallow(root.data); // .TST.TableDataList.ListType var type = varint_to_i32(pb[1][0].data); var entries = pb[3]; var data = []; (entries||[]).forEach(entry => { // .TST.TableDataList.ListEntry var le = parse_shallow(entry.data); var key = varint_to_i32(le[1][0].data)>>>0; switch(type) { case 1: data[key] = u8str(le[3][0].data); break; case 8: { // .TSP.RichTextPayloadArchive var rt = M[parse_TSP_Reference(le[9][0].data)][0]; var rtp = parse_shallow(rt.data); // .TSWP.StorageArchive var rtpref = M[parse_TSP_Reference(rtp[1][0].data)][0]; var mtype = varint_to_i32(rtpref.meta[1][0].data); if(mtype != 2001) throw new Error(`2000 unexpected reference to ${mtype}`); var tswpsa = parse_shallow(rtpref.data); data[key] = tswpsa[3].map(x => u8str(x.data)).join(""); } break; } }); return data; } type TileStorageType = -1 | 0 | 1; interface TileRowInfo { /** Row Index */ R: number; /** Cell Storage */ cells?: Uint8Array[]; } /** Parse .TSP.TileRowInfo */ function parse_TST_TileRowInfo(u8: Uint8Array, type: TileStorageType): TileRowInfo { var pb = parse_shallow(u8); var R = varint_to_i32(pb[1][0].data) >>> 0; var cnt = varint_to_i32(pb[2][0].data) >>> 0; // var version = pb?.[5]?.[0] && (varint_to_i32(pb[5][0].data) >>> 0); var wide_offsets = pb[8]?.[0]?.data && varint_to_i32(pb[8][0].data) > 0 || false; /* select storage by type (1 = modern / 0 = old / -1 = try modern, old) */ var used_storage_u8: Uint8Array, used_storage: Uint8Array; if(pb[7]?.[0]?.data && type != 0) { used_storage_u8 = pb[7]?.[0]?.data; used_storage = pb[6]?.[0]?.data; } else if(pb[4]?.[0]?.data && type != 1) { used_storage_u8 = pb[4]?.[0]?.data; used_storage = pb[3]?.[0]?.data; } else throw `NUMBERS Tile missing ${type} cell storage`; /* find all offsets -- 0xFFFF means cells are not present */ var width = wide_offsets ? 4 : 1; var used_storage_offsets = u8_to_dataview(used_storage_u8); var offsets: Array<[number, number]> = []; for(var C = 0; C < used_storage_u8.length / 2; ++C) { var off = used_storage_offsets.getUint16(C*2, true); if(off < 65535) offsets.push([C, off]); } if(offsets.length != cnt) throw `Expected ${cnt} cells, found ${offsets.length}`; var cells: Uint8Array[] = []; for(C = 0; C < offsets.length - 1; ++C) cells[offsets[C][0]] = used_storage.subarray(offsets[C][1] * width, offsets[C+1][1] * width); if(offsets.length >= 1) cells[offsets[offsets.length - 1][0]] = used_storage.subarray(offsets[offsets.length - 1][1] * width); return { R, cells }; } interface TileInfo { data: Uint8Array[][]; nrows: number; } /** Parse .TST.Tile */ function parse_TST_Tile(M: MessageSpace, root: IWAMessage): TileInfo { var pb = parse_shallow(root.data); // ESBuild issue 2136 // var storage: TileStorageType = (pb?.[7]?.[0]) ? ((varint_to_i32(pb[7][0].data)>>>0) > 0 ? 1 : 0 ) : -1; var storage: TileStorageType = -1; if(pb?.[7]?.[0]) { if(varint_to_i32(pb[7][0].data)>>>0) storage = 1; else storage = 0; } var ri = mappa(pb[5], (u8: Uint8Array) => parse_TST_TileRowInfo(u8, storage)); return { nrows: varint_to_i32(pb[4][0].data)>>>0, data: ri.reduce((acc, x) => { if(!acc[x.R]) acc[x.R] = []; x.cells.forEach((cell, C) => { if(acc[x.R][C]) throw new Error(`Duplicate cell r=${x.R} c=${C}`); acc[x.R][C] = cell; }); return acc; }, [] as Uint8Array[][]) }; } /** Parse .TST.TableModelArchive (6001) */ function parse_TST_TableModelArchive(M: MessageSpace, root: IWAMessage, ws: WorkSheet) { var pb = parse_shallow(root.data); var range: Range = { s: {r:0, c:0}, e: {r:0, c:0} }; range.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1; if(range.e.r < 0) throw new Error(`Invalid row varint ${pb[6][0].data}`); range.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1; if(range.e.c < 0) throw new Error(`Invalid col varint ${pb[7][0].data}`); ws["!ref"] = encode_range(range); // .TST.DataStore var store = parse_shallow(pb[4][0].data); var sst = parse_TST_TableDataList(M, M[parse_TSP_Reference(store[4][0].data)][0]); var rsst: string[] = store[17]?.[0] ? parse_TST_TableDataList(M, M[parse_TSP_Reference(store[17][0].data)][0]) : []; // .TST.TileStorage var tile = parse_shallow(store[3][0].data); var _R = 0; /* TODO: should this list be sorted by id ? */ tile[1].forEach(t => { var tl = (parse_shallow(t.data)); // var id = varint_to_i32(tl[1][0].data); var ref = M[parse_TSP_Reference(tl[2][0].data)][0]; var mtype = varint_to_i32(ref.meta[1][0].data); if(mtype != 6002) throw new Error(`6001 unexpected reference to ${mtype}`); var _tile = parse_TST_Tile(M, ref); _tile.data.forEach((row, R) => { row.forEach((buf, C) => { var addr = encode_cell({r:_R + R,c:C}); var res = parse_cell_storage(buf, sst, rsst); if(res) ws[addr] = res; }); }); _R += _tile.nrows; }); if(store[13]?.[0]) { var ref = M[parse_TSP_Reference(store[13][0].data)][0]; var mtype = varint_to_i32(ref.meta[1][0].data); if(mtype != 6144) throw new Error(`Expected merge type 6144, found ${mtype}`); ws["!merges"] = parse_shallow(ref.data)?.[1].map(pi => { var merge = parse_shallow(pi.data); var origin = u8_to_dataview(parse_shallow(merge[1][0].data)[1][0].data), size = u8_to_dataview(parse_shallow(merge[2][0].data)[1][0].data); return { s: { r: origin.getUint16(0, true), c: origin.getUint16(2, true) }, e: { r: origin.getUint16(0, true) + size.getUint16(0, true) - 1, c: origin.getUint16(2, true) + size.getUint16(2, true) - 1 } }; }); } } /** Parse .TST.TableInfoArchive (6000) */ function parse_TST_TableInfoArchive(M: MessageSpace, root: IWAMessage): WorkSheet { var pb = parse_shallow(root.data); var out: WorkSheet = { "!ref": "A1" }; var tableref = M[parse_TSP_Reference(pb[2][0].data)]; var mtype = varint_to_i32(tableref[0].meta[1][0].data); if(mtype != 6001) throw new Error(`6000 unexpected reference to ${mtype}`); parse_TST_TableModelArchive(M, tableref[0], out); return out; } interface NSheet { name: string; sheets: WorkSheet[]; } /** Parse .TN.SheetArchive (2) */ function parse_TN_SheetArchive(M: MessageSpace, root: IWAMessage): NSheet { var pb = parse_shallow(root.data); var out: NSheet = { name: (pb[1]?.[0] ? u8str(pb[1][0].data) : ""), sheets: [] }; var shapeoffs = mappa(pb[2], parse_TSP_Reference); shapeoffs.forEach((off) => { M[off].forEach((m: IWAMessage) => { var mtype = varint_to_i32(m.meta[1][0].data); if(mtype == 6000) out.sheets.push(parse_TST_TableInfoArchive(M, m)); }); }); return out; } /** Parse .TN.DocumentArchive */ function parse_TN_DocumentArchive(M: MessageSpace, root: IWAMessage): WorkBook { var out = book_new(); var pb = parse_shallow(root.data); if(pb[2]?.[0]) throw new Error("Keynote presentations are not supported"); // var stylesheet = mappa(pb[4], parse_TSP_Reference)[0]; // if(varint_to_i32(M[stylesheet][0].meta[1][0].data) == 401) parse_TSS_StylesheetArchive(M, M[stylesheet][0]); // var sidebar = mappa(pb[5], parse_TSP_Reference); // var theme = mappa(pb[6], parse_TSP_Reference); // var docinfo = parse_shallow(pb[8][0].data); // var tskinfo = parse_shallow(docinfo[1][0].data); // var author_storage = mappa(tskinfo[7], parse_TSP_Reference); var sheetoffs = mappa(pb[1], parse_TSP_Reference); sheetoffs.forEach((off) => { M[off].forEach((m: IWAMessage) => { var mtype = varint_to_i32(m.meta[1][0].data); if(mtype == 2) { var root = parse_TN_SheetArchive(M, m); root.sheets.forEach((sheet, idx) => { book_append_sheet(out, sheet, idx == 0 ? root.name : root.name + "_" + idx, true); }); } }); }); if(out.SheetNames.length == 0) throw new Error("Empty NUMBERS file"); return out; } /** Parse NUMBERS file */ function parse_numbers_iwa(cfb: CFB$Container): WorkBook { var M: MessageSpace = {}, indices: number[] = []; cfb.FullPaths.forEach(p => { if(p.match(/\.iwpv2/)) throw new Error(`Unsupported password protection`); }); /* collect entire message space */ cfb.FileIndex.forEach(s => { if(!s.name.match(/\.iwa$/)) return; var o: Uint8Array; try { o = decompress_iwa_file(s.content as Uint8Array); } catch(e) { return console.log("?? " + s.content.length + " " + (e.message || e)); } var packets: IWAArchiveInfo[]; try { packets = parse_iwa_file(o); } catch(e) { return console.log("## " + (e.message || e)); } packets.forEach(packet => { M[packet.id] = packet.messages; indices.push(packet.id); }); }); if(!indices.length) throw new Error("File has no messages"); /* find document root */ if(M?.[1]?.[0]?.meta?.[1]?.[0].data && varint_to_i32(M[1][0].meta[1][0].data) == 10000) throw new Error("Pages documents are not supported"); var docroot: IWAMessage = M?.[1]?.[0]?.meta?.[1]?.[0].data && varint_to_i32(M[1][0].meta[1][0].data) == 1 && M[1][0]; if(!docroot) indices.forEach((idx) => { M[idx].forEach((iwam) => { var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0; if(mtype == 1) { if(!docroot) docroot = iwam; else throw new Error("Document has multiple roots"); } }); }); if(!docroot) throw new Error("Cannot find Document root"); return parse_TN_DocumentArchive(M, docroot); } //<<export { parse_numbers_iwa }; interface DependentInfo { deps: number[]; location: string; type: number; } /** Write .TST.TileRowInfo */ function write_tile_row(tri: ProtoMessage, data: any[], SST: string[], wide: boolean): number { if(!tri[6]?.[0] || !tri[7]?.[0]) throw "Mutation only works on post-BNC storages!"; //var wide_offsets = tri[8]?.[0]?.data && varint_to_i32(tri[8][0].data) > 0 || false; var cnt = 0; if(tri[7][0].data.length < 2 * data.length) { var new_7 = new Uint8Array(2 * data.length); new_7.set(tri[7][0].data); tri[7][0].data = new_7; } //if(wide) { // tri[3] = [{type: 2, data: new Uint8Array([240, 159, 164, 160]) }]; // tri[4] = [{type: 2, data: new Uint8Array([240, 159, 164, 160]) }]; /* } else*/ if(tri[4][0].data.length < 2 * data.length) { var new_4 = new Uint8Array(2 * data.length); new_4.set(tri[4][0].data); tri[4][0].data = new_4; } var dv = u8_to_dataview(tri[7][0].data), last_offset = 0, cell_storage: Uint8Array[] = []; var _dv = u8_to_dataview(tri[4][0].data), _last_offset = 0, _cell_storage: Uint8Array[] = []; var width = wide ? 4 : 1; for(var C = 0; C < data.length; ++C) { if(data[C] == null) { dv.setUint16(C*2, 0xFFFF, true); _dv.setUint16(C*2, 0xFFFF); continue; } dv.setUint16(C*2, last_offset / width, true); /*if(!wide)*/ _dv.setUint16(C*2, _last_offset / width, true); var celload: Uint8Array, _celload: Uint8Array; switch(typeof data[C]) { case "string": celload = write_new_storage({t: "s", v: data[C]}, SST); /*if(!wide)*/ _celload = write_old_storage({t: "s", v: data[C]}, SST); break; case "number": celload = write_new_storage({t: "n", v: data[C]}, SST); /*if(!wide)*/ _celload = write_old_storage({t: "n", v: data[C]}, SST); break; case "boolean": celload = write_new_storage({t: "b", v: data[C]}, SST); /*if(!wide)*/ _celload = write_old_storage({t: "b", v: data[C]}, SST); break; default: throw new Error("Unsupported value " + data[C]); } cell_storage.push(celload); last_offset += celload.length; /*if(!wide)*/ { _cell_storage.push(_celload); _last_offset += _celload.length; } ++cnt; } tri[2][0].data = write_varint49(cnt); tri[5][0].data = write_varint49(5); for(; C < tri[7][0].data.length/2; ++C) { dv.setUint16(C*2, 0xFFFF, true); /*if(!wide)*/ _dv.setUint16(C*2, 0xFFFF, true); } tri[6][0].data = u8concat(cell_storage); /*if(!wide)*/ tri[3][0].data = u8concat(_cell_storage); tri[8] = [{type: 0, data: write_varint49(wide ? 1 : 0)}]; return cnt; } /** Write IWA Message */ function write_iwam(type: number, payload: Uint8Array): IWAMessage { return { meta: [ [], [ { type: 0, data: write_varint49(type) } ] ], data: payload }; } var USE_WIDE_ROWS = true; /** Write NUMBERS workbook */ function write_numbers_iwa(wb: WorkBook, opts: any): CFB$Container { if(!opts || !opts.numbers) throw new Error("Must pass a `numbers` option -- check the README"); /* TODO: support multiple worksheets, larger ranges, more data types, etc */ var ws = wb.Sheets[wb.SheetNames[0]]; if(wb.SheetNames.length > 1) console.error("The Numbers writer currently writes only the first table"); var range = decode_range(ws["!ref"]); range.s.r = range.s.c = 0; /* Actual NUMBERS 12.0 limit ALL1000000 */ var trunc = false; if(range.e.c > 999) { trunc = true; range.e.c = 999; } if(range.e.r > 254 /* 1000000 */) { trunc = true; range.e.r = 254 /* 1000000 */; } if(trunc) console.error(`The Numbers writer is currently limited to ${encode_range(range)}`); var data = sheet_to_json<any>(ws, { range, header: 1 }); var SST = ["~Sh33tJ5~"]; data.forEach(row => row.forEach(cell => { if(typeof cell == "string") SST.push(cell); })) var dependents: {[x:number]: DependentInfo} = {}; var indices: number[] = []; /* read template and build packet metadata */ var cfb: CFB$Container = CFB.read(opts.numbers, { type: "base64" }); cfb.FileIndex.map((fi, idx): [CFB$Entry, string] => ([fi, cfb.FullPaths[idx]])).forEach(row => { var fi = row[0], fp = row[1]; if(fi.type != 2) return; if(!fi.name.match(/\.iwa/)) return; /* Reframe .iwa files */ var old_content = fi.content; var raw1 = decompress_iwa_file(old_content as Uint8Array); var x = parse_iwa_file(raw1); x.forEach(packet => { indices.push(packet.id); dependents[packet.id] = { deps: [], location: fp, type: varint_to_i32(packet.messages[0].meta[1][0].data) }; }); }); /* precompute a varint for each id */ indices.sort((x,y) => x-y); var indices_varint: Array<[number, Uint8Array]> = indices.filter(x => x > 1).map(x => [x, write_varint49(x)] ); /* build dependent tree */ cfb.FileIndex.map((fi, idx): [CFB$Entry, string] => ([fi, cfb.FullPaths[idx]])).forEach(row => { var fi = row[0]; if(!fi.name.match(/\.iwa/)) return; var x = parse_iwa_file(decompress_iwa_file(fi.content as Uint8Array)); x.forEach(ia => { indices_varint.forEach(ivi => { if(ia.messages.some(mess => varint_to_i32(mess.meta[1][0].data) != 11006 && u8contains(mess.data, ivi[1]))) { dependents[ivi[0]].deps.push(ia.id); } }) }); }); function get_unique_msgid(dep: DependentInfo) { for(var i = 927262; i < 2000000; ++i) if(!dependents[i]) { dependents[i] = dep; return i; } throw new Error("Too many messages"); } /* .TN.DocumentArchive */ var entry = CFB.find(cfb, dependents[1].location); var x = parse_iwa_file(decompress_iwa_file(entry.content as Uint8Array)); var docroot: IWAArchiveInfo; for(var xi = 0; xi < x.length; ++xi) { var packet = x[xi]; if(packet.id == 1) docroot = packet; } /* .TN.SheetArchive */ var sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[1][0].data); entry = CFB.find(cfb, dependents[sheetrootref].location); x = parse_iwa_file(decompress_iwa_file(entry.content as Uint8Array)); for(xi = 0; xi < x.length; ++xi) { packet = x[xi]; if(packet.id == sheetrootref) docroot = packet; } /* write worksheet name */ var sheetref = parse_shallow(docroot.messages[0].data); { sheetref[1] = [ { type: 2, data: stru8(wb.SheetNames[0]) }]; } docroot.messages[0].data = write_shallow(sheetref); entry.content = compress_iwa_file(write_iwa_file(x)); entry.size = entry.content.length; /* .TST.TableInfoArchive */ sheetrootref = parse_TSP_Reference(sheetref[2][0].data); entry = CFB.find(cfb, dependents[sheetrootref].location); x = parse_iwa_file(decompress_iwa_file(entry.content as Uint8Array)); for(xi = 0; xi < x.length; ++xi) { packet = x[xi]; if(packet.id == sheetrootref) docroot = packet; } /* .TST.TableModelArchive */ sheetrootref = parse_TSP_Reference(parse_shallow(docroot.messages[0].data)[2][0].data); entry = CFB.find(cfb, dependents[sheetrootref].location); x = parse_iwa_file(decompress_iwa_file(entry.content as Uint8Array)); for(xi = 0; xi < x.length; ++xi) { packet = x[xi]; if(packet.id == sheetrootref) docroot = packet; } var pb = parse_shallow(docroot.messages[0].data); { pb[6][0].data = write_varint49(range.e.r + 1); pb[7][0].data = write_varint49(range.e.c + 1); // pb[22] = [ { type: 0, data: write_varint49(1) } ]; // enables table display var cruidsref = parse_TSP_Reference(pb[46][0].data); var oldbucket = CFB.find(cfb, dependents[cruidsref].location); var _x = parse_iwa_file(decompress_iwa_file(oldbucket.content as Uint8Array)); { for(var j = 0; j < _x.length; ++j) { if(_x[j].id == cruidsref) break; } if(_x[j].id != cruidsref) throw "Bad ColumnRowUIDMapArchive"; /* .TST.ColumnRowUIDMapArchive */ var cruids = parse_shallow(_x[j].messages[0].data); cruids[1] = []; cruids[2] = [], cruids[3] = []; for(var C = 0; C <= range.e.c; ++C) { cruids[1].push({type: 2, data: write_shallow([ [], [ { type: 0, data: write_varint49(C + 420690) } ], [ { type: 0, data: write_varint49(C + 420690) } ] ])}); cruids[2].push({type: 0, data: write_varint49(C)}); cruids[3].push({type: 0, data: write_varint49(C)}); } cruids[4] = []; cruids[5] = [], cruids[6] = []; for(var R = 0; R <= range.e.r; ++R) { cruids[4].push({type: 2, data: write_shallow([ [], [ { type: 0, data: write_varint49(R + 726270)} ], [ { type: 0, data: write_varint49(R + 726270)} ] ])}); cruids[5].push({type: 0, data: write_varint49(R)}); cruids[6].push({type: 0, data: write_varint49(R)}); } _x[j].messages[0].data = write_shallow(cruids); } oldbucket.content = compress_iwa_file(write_iwa_file(_x)); oldbucket.size = oldbucket.content.length; delete pb[46]; // forces Numbers to refresh cell table var store = parse_shallow(pb[4][0].data); { store[7][0].data = write_varint49(range.e.r + 1); var row_headers = parse_shallow(store[1][0].data); var row_header_ref = parse_TSP_Reference(row_headers[2][0].data); oldbucket = CFB.find(cfb, dependents[row_header_ref].location); _x = parse_iwa_file(decompress_iwa_file(oldbucket.content as Uint8Array)); { if(_x[0].id != row_header_ref) throw "Bad HeaderStorageBucket"; var base_bucket = parse_shallow(_x[0].messages[0].data); if(base_bucket?.[2]?.[0]) for(R = 0; R < data.length; ++R) { var _bucket = parse_shallow(base_bucket[2][0].data); _bucket[1][0].data = write_varint49(R); _bucket[4][0].data = write_varint49(data[R].length); base_bucket[2][R] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) }; } _x[0].messages[0].data = write_shallow(base_bucket); } oldbucket.content = compress_iwa_file(write_iwa_file(_x)); oldbucket.size = oldbucket.content.length; var col_header_ref = parse_TSP_Reference(store[2][0].data); oldbucket = CFB.find(cfb, dependents[col_header_ref].location); _x = parse_iwa_file(decompress_iwa_file(oldbucket.content as Uint8Array)); { if(_x[0].id != col_header_ref) throw "Bad HeaderStorageBucket"; base_bucket = parse_shallow(_x[0].messages[0].data); for(C = 0; C <= range.e.c; ++C) { _bucket = parse_shallow(base_bucket[2][0].data); _bucket[1][0].data = write_varint49(C); _bucket[4][0].data = write_varint49(range.e.r + 1); base_bucket[2][C] = { type: base_bucket[2][0].type, data: write_shallow(_bucket) }; } _x[0].messages[0].data = write_shallow(base_bucket); } oldbucket.content = compress_iwa_file(write_iwa_file(_x)); oldbucket.size = oldbucket.content.length; if(ws["!merges"]) { var mergeid = get_unique_msgid({ type: 6144, deps: [sheetrootref], location: dependents[sheetrootref].location }); var mergedata: ProtoMessage = [ [], [] ]; ws["!merges"].forEach(m => { mergedata[1].push({ type: 2, data: write_shallow([ [], [{ type: 2, data: write_shallow([ [], [{ type: 5, data: new Uint8Array(new Uint16Array([m.s.r, m.s.c]).buffer) }], ])}], [{ type: 2, data: write_shallow([ [], [{ type: 5, data: new Uint8Array(new Uint16Array([m.e.r - m.s.r + 1, m.e.c - m.s.c + 1]).buffer) }], ]) }] ]) }); }); store[13] = [ { type: 2, data: write_TSP_Reference(mergeid) } ]; x.push({ id: mergeid, messages: [ write_iwam(6144, write_shallow(mergedata)) ] }); } /* ref to string table */ var sstref = parse_TSP_Reference(store[4][0].data); (() => { var sentry = CFB.find(cfb, dependents[sstref].location); var sx = parse_iwa_file(decompress_iwa_file(sentry.content as Uint8Array)); var sstroot: IWAArchiveInfo; for(var sxi = 0; sxi < sx.length; ++sxi) { var packet = sx[sxi]; if(packet.id == sstref) sstroot = packet; } var sstdata = parse_shallow(sstroot.messages[0].data); { sstdata[3] = []; SST.forEach((str, i) => { sstdata[3].push({type: 2, data: write_shallow([ [], [ { type: 0, data: write_varint49(i) } ], [ { type: 0, data: write_varint49(1) } ], [ { type: 2, data: stru8(str) } ] ])}); }); } sstroot.messages[0].data = write_shallow(sstdata); sentry.content = compress_iwa_file(write_iwa_file(sx)); sentry.size = sentry.content.length; })(); var tile = parse_shallow(store[3][0].data); // TileStorage { var t = tile[1][0]; tile[3] = [{type: 0, data: write_varint49(USE_WIDE_ROWS ? 1 : 0)}]; var tl = parse_shallow(t.data); // first Tile { var tileref = parse_TSP_Reference(tl[2][0].data); (() => { var tentry = CFB.find(cfb, dependents[tileref].location); var tx = parse_iwa_file(decompress_iwa_file(tentry.content as Uint8Array)); var tileroot: IWAArchiveInfo; for(var sxi = 0; sxi < tx.length; ++sxi) { var packet = tx[sxi]; if(packet.id == tileref) tileroot = packet; } // .TST.Tile var tiledata = parse_shallow(tileroot.messages[0].data); { delete tiledata[6]; delete tile[7]; var rowload = new Uint8Array(tiledata[5][0].data); tiledata[5] = []; //var cnt = 0; for(var R = 0; R <= range.e.r; ++R) { var tilerow = parse_shallow(rowload); /* cnt += */ write_tile_row(tilerow, data[R], SST, USE_WIDE_ROWS); tilerow[1][0].data = write_varint49(R); tiledata[5].push({data: write_shallow(tilerow), type: 2}); } tiledata[1] = [{type: 0, data: write_varint49(0 /*range.e.c + 1*/)}]; tiledata[2] = [{type: 0, data: write_varint49(0 /*range.e.r + 1*/)}]; tiledata[3] = [{type: 0, data: write_varint49(0 /*cnt*/)}]; tiledata[4] = [{type: 0, data: write_varint49(range.e.r + 1)}]; tiledata[6] = [{type: 0, data: write_varint49(5)}]; tiledata[7] = [{type: 0, data: write_varint49(1)}]; tiledata[8] = [{type: 0, data: write_varint49(USE_WIDE_ROWS ? 1 : 0)}]; } tileroot.messages[0].data = write_shallow(tiledata); tentry.content = compress_iwa_file(write_iwa_file(tx)); tentry.size = tentry.content.length; })(); } t.data = write_shallow(tl); } store[3][0].data = write_shallow(tile); } pb[4][0].data = write_shallow(store); } docroot.messages[0].data = write_shallow(pb); entry.content = compress_iwa_file(write_iwa_file(x)); entry.size = entry.content.length; return cfb; }
the_stack
import { isNullOrUndefined, _InternalMessageId, hasDocument, hasOwnProperty, arrForEach } from "@microsoft/applicationinsights-core-js"; import { IClickAnalyticsConfiguration } from "../Interfaces/Datamodel"; const Prototype = "prototype"; const DEFAULT_DONOT_TRACK_TAG = "ai-dnt"; const DEFAULT_AI_BLOB_ATTRIBUTE_TAG = "ai-blob"; const DEFAULT_DATA_PREFIX = "data-"; export const _ExtendedInternalMessageId = { ..._InternalMessageId, CannotParseAiBlobValue: 101, InvalidContentBlob: 102, TrackPageActionEventFailed: 103 }; /** * Finds attributes in overrideConfig which are invalid or should be objects * and deletes them. useful in override config * @param overrideConfig - override config object * @param attributeNamesExpectedObjects - attributes that should be objects in override config object */ export function removeNonObjectsAndInvalidElements(overrideConfig: IClickAnalyticsConfiguration, attributeNamesExpectedObjects: Array<string>): void { removeInvalidElements(overrideConfig); for (var i in attributeNamesExpectedObjects) { if (attributeNamesExpectedObjects.hasOwnProperty(i)) { var objectName = attributeNamesExpectedObjects[i]; if (typeof overrideConfig[objectName] === "object") { removeInvalidElements(overrideConfig[objectName]); } else { delete overrideConfig[objectName]; } } } } /** * Finds attributes in object which are invalid * and deletes them. useful in override config * @param object Input object */ export function removeInvalidElements(object: Object): void { /// Because the config object 'callback' contains only functions, /// when it is stringified it returns the empty object. This explains /// the workaround regarding 'callback' for (var property in object) { if (!isValueAssigned(object[property]) || (JSON.stringify(object[property]) === "{}" && (property !== "callback"))) { delete object[property]; } } } /** * Checks if value is assigned to the given param. * @param value - The token from which the tenant id is to be extracted. * @returns True/false denoting if value is assigned to the param. */ export function isValueAssigned(value: any) { /// <summary> takes a value and checks for undefined, null and empty string </summary> /// <param type="any"> value to be tested </param> /// <returns> true if value is null undefined or emptyString </returns> return !(isNullOrUndefined(value) || value === ""); } /** * Determines whether an event is a right click or not * @param evt - Mouse event * @returns true if the event is a right click */ export function isRightClick(evt: any): boolean { try { if ("which" in evt) { // Chrome, FF, ... return (evt.which === 3); } else if ("button" in evt) { // IE, ... return (evt.button === 2); } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Determines whether an event is a left click or not * @param evt - Mouse event * @returns true if the event is a left click */ export function isLeftClick(evt: any): boolean { try { if ("which" in evt) { // Chrome, FF, ... return (evt.which === 1); } else if ("button" in evt) { // IE, ... return (evt.button === 1); } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Determines whether an event is a middle click or not * @param evt - Mouse event * @returns true if the event is a middle click */ export function isMiddleClick(evt: any): boolean { try { if ("which" in evt) { // Chrome, FF, ... return (evt.which === 2); } else if ("button" in evt) { // IE, ... return (evt.button === 4); } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Determines whether an event is a keyboard enter or not * @param evt - Keyboard event * @returns true if the event is a keyboard enter */ export function isKeyboardEnter(evt: KeyboardEvent): boolean { try { if ("keyCode" in evt) { // Chrome, FF, ... return (evt.keyCode === 13); } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Determines whether an event is a keyboard space or not * @param evt - Keyboard event * @returns true if the event is a space enter */ export function isKeyboardSpace(evt: KeyboardEvent) { try { if ("keyCode" in evt) { // Chrome, FF, ... return (evt.keyCode === 32); } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Determines whether the elemt have a DNT(Do Not Track) tag * @param element - DOM element * @param doNotTrackFieldName - DOM element * @returns true if the element must not be tarcked */ export function isElementDnt(element: Element, doNotTrackFieldName: string): boolean { var dntElement = findClosestByAttribute(element, doNotTrackFieldName); if (!isValueAssigned(dntElement)) { return false; } return true; } /** * Walks up DOM tree to find element with attribute * @param el - DOM element * @param attribute - Attribute name * @returns Dom element which contains attribute */ export function findClosestByAttribute(el: Element, attribute: string): Element { return walkUpDomChainWithElementValidation(el, isAttributeInElement, attribute); } /** * checks if attribute is in element. * method checks for empty string, in case the attribute is set but no value is assigned to it * @param element - DOM element * @param attributeToLookFor - Attribute name * @returns true if attribute is in element, even if empty string */ export function isAttributeInElement(element: Element, attributeToLookFor: string): Boolean { var value = element.getAttribute(attributeToLookFor); return isValueAssigned(value); } /** * Walks up DOM tree to find element which matches validationMethod * @param el - DOM element * @param validationMethod - DOM element validation method * @param validationMethodParam - DOM element validation method parameters * @returns Dom element which is an anchor */ export function walkUpDomChainWithElementValidation(el: Element, validationMethod: Function, validationMethodParam?: any): Element { var element = el; if (element) { while (!validationMethod(element, validationMethodParam)) { element = (element.parentNode as Element); if (!element || !(element.getAttribute)) { return null; } } return element; } } /** * Determine if DOM element is an anchor * @param element - DOM element * @returns Is element an anchor */ export function isElementAnAnchor(element: Element): boolean { return element.nodeName === "A"; } /** * Walks up DOM tree to find anchor element * @param element - DOM element * @returns Dom element which is an anchor */ export function findClosestAnchor(element: Element): Element { /// <summary> Walks up DOM tree to find anchor element </summary> /// <param type='object'> DOM element </param> /// <returns> Dom element which is an anchor</returns> return walkUpDomChainWithElementValidation(element, isElementAnAnchor); } /** * Returns the specified field and also removes the property from the object if exists. * @param obj - Input object * @param fieldName - >Name of the field/property to be extracted * @returns Value of the specified tag */ export function extractFieldFromObject(obj: Object, fieldName: string): string { var fieldValue: any; if (obj && obj[fieldName]) { fieldValue = obj[fieldName]; delete obj[fieldName]; } return fieldValue; } /** * Adds surrounding square brackets to the passed in text * @param str - Input string * @returns String with surrounding brackets */ export function bracketIt(str: string): string { /// <summary> /// Adds surrounding square brackets to the passed in text /// </summary> return "[" + str + "]"; } /** * Pass in the objects to merge as arguments. * @param obj1 - object to merge. Set this argument to 'true' for a deep extend. * @param obj2 - object to merge. * @param obj3 - object to merge. * @param obj4 - object to merge. * @param obj5 - object to merge. * @returns The extended object. */ export function extend(obj?: any, obj2?: any, obj3?: any, obj4?: any, obj5?: any): any { // Variables var extended = {}; var deep = false; var i = 0; var length = arguments.length; var objProto = Object[Prototype]; var theArgs = arguments; // Check if a deep merge if (objProto.toString.call(theArgs[0]) === "[object Boolean]") { deep = theArgs[0]; i++; } // Merge the object into the extended object var merge = (obj: Object) => { for (var prop in obj) { if (hasOwnProperty(obj, prop)) { // If deep merge and property is an object, merge properties if (deep && objProto.toString.call(obj[prop]) === "[object Object]") { extended[prop] = extend(true, extended[prop], obj[prop]); } else { extended[prop] = obj[prop]; } } } }; // Loop through each object and conduct a merge for (; i < length; i++) { var obj = theArgs[i]; merge(obj); } return extended; } export function validateContentNamePrefix ( config: IClickAnalyticsConfiguration, defaultDataPrefix: string) { return isValueAssigned(config.dataTags.customDataPrefix) && (config.dataTags.customDataPrefix.indexOf(defaultDataPrefix) === 0); } /** * Merge passed in configuration with default configuration * @param overrideConfig */ export function mergeConfig(overrideConfig: IClickAnalyticsConfiguration): IClickAnalyticsConfiguration { let defaultConfig: IClickAnalyticsConfiguration = { // General library settings autoCapture: true, callback: { pageActionPageTags: null }, pageTags: {}, // overrideValues to use instead of collecting automatically coreData: { referrerUri: hasDocument ? document.referrer : "", requestUri: "", pageName: "", pageType: "" }, dataTags: { useDefaultContentNameOrId: false, aiBlobAttributeTag: DEFAULT_AI_BLOB_ATTRIBUTE_TAG, customDataPrefix: DEFAULT_DATA_PREFIX, captureAllMetaDataContent: false, dntDataTag: DEFAULT_DONOT_TRACK_TAG }, behaviorValidator: (key:string) => key || "", defaultRightClickBhvr: "", dropInvalidEvents : false }; let attributesThatAreObjectsInConfig: any[] = []; for (const attribute in defaultConfig) { if (typeof defaultConfig[attribute] === "object") { attributesThatAreObjectsInConfig.push(attribute); } } if (overrideConfig) { // delete attributes that should be object and // delete properties that are null, undefined, '' removeNonObjectsAndInvalidElements(overrideConfig, attributesThatAreObjectsInConfig); if(isValueAssigned(overrideConfig.dataTags)) { overrideConfig.dataTags.customDataPrefix = validateContentNamePrefix(overrideConfig, DEFAULT_DATA_PREFIX) ? overrideConfig.dataTags.customDataPrefix : DEFAULT_DATA_PREFIX; } return extend(true, defaultConfig, overrideConfig); } } export function BehaviorMapValidator (map: any) { return (key: string) => map[key] || ""; } export function BehaviorValueValidator (behaviorArray: string[]) { return (key: string) => { let result; arrForEach(behaviorArray, (value) => { if (value === key) { result = value; return -1; } }); return result || ""; } } export function BehaviorEnumValidator (enumObj: any) { return (key: string) => enumObj[key] || ""; }
the_stack
import { FilterOptions, RunWorkflowOptions, SourceOptions, StepOptions, WorkflowOptions, } from "./interface.ts"; import { hasPermissionSlient } from "./permission.ts"; import { Context, StepType } from "./internal-interface.ts"; import { parseWorkflow } from "./parse-workflow.ts"; import { getContent } from "./utils/file.ts"; import { getFilesByFilter } from "./utils/filter.ts"; import { isObject } from "./utils/object.ts"; import { parseObject } from "./parse-object.ts"; import { isRemotePath } from "./utils/path.ts"; import { getStepResponse, runStep, setErrorResult } from "./run-step.ts"; import { filterCtxItems, getSourceItemsFromResult, } from "./get-source-items-from-result.ts"; import { config, delay, dirname, join, log, relative, SqliteDb, } from "../deps.ts"; import report, { getReporter } from "./report.ts"; import { Keydb } from "./adapters/json-store-adapter.ts"; import { filterSourceItems } from "./filter-source-items.ts"; import { markSourceItems } from "./mark-source-items.ts"; import { runCmd, setCmdOkResult } from "./run-cmd.ts"; import { getFinalRunOptions, getFinalSourceOptions, getFinalWorkflowOptions, } from "./default-options.ts"; import { runPost } from "./run-post.ts"; import { runAssert } from "./run-assert.ts"; import { getEnv } from "./utils/env.ts"; interface ValidWorkflow { ctx: Context; workflow: WorkflowOptions; } const parse1Keys = ["env"]; const parse2Keys = ["if", "debug"]; const parse3ForGeneralKeys = [ "if", "debug", "database", "sleep", "limit", "force", ]; const parse3ForStepKeys = [ "id", "from", "use", "args", ]; const parse4ForSourceKeys = [ "force", "itemsPath", "key", "limit", "reverse", ]; const parse6ForSourceKeys = [ "filterFrom", "filterItemsFrom", ]; const parse7ForSourceKeys = [ "cmd", ]; export async function run(runOptions: RunWorkflowOptions) { const debugEnvPermmision = { name: "env", variable: "DEBUG" } as const; const dataPermission = { name: "read", path: "data" } as const; let DebugEnvValue = undefined; if (await hasPermissionSlient(debugEnvPermmision)) { DebugEnvValue = Deno.env.get("DEBUG"); } let isDebug = !!(DebugEnvValue !== undefined && DebugEnvValue !== "false"); const cliWorkflowOptions = getFinalRunOptions(runOptions, isDebug); isDebug = cliWorkflowOptions.debug || false; const { files, content, } = cliWorkflowOptions; let workflowFiles: string[] = []; const cwd = Deno.cwd(); if (content) { workflowFiles = []; } else { workflowFiles = await getFilesByFilter(cwd, files); } let env = {}; const allEnvPermmision = { name: "env" } as const; // first try to get .env const dotEnvFilePermmision = { name: "read", path: ".env,.env.defaults,.env.example", } as const; if (await hasPermissionSlient(dotEnvFilePermmision)) { env = config(); } if (await hasPermissionSlient(allEnvPermmision)) { env = { ...env, ...Deno.env.toObject(), }; } // get options let validWorkflows: ValidWorkflow[] = []; // if stdin if (content) { const workflow = parseWorkflow(content); if (isObject(workflow)) { const workflowFilePath = "/tmp/denoflow/tmp-workflow.yml"; const workflowRelativePath = relative(cwd, workflowFilePath); validWorkflows.push({ ctx: { public: { env, workflowPath: workflowFilePath, workflowRelativePath, workflowCwd: dirname(workflowFilePath), cwd: cwd, sources: {}, steps: {}, state: undefined, items: [], itemSourceOptions: undefined, }, sourcesOptions: [], currentStepType: StepType.Source, }, workflow: workflow, }); } } const errors = []; for (let i = 0; i < workflowFiles.length; i++) { const workflowRelativePath = workflowFiles[i]; let fileContent = ""; let workflowFilePath = ""; if (isRemotePath(workflowRelativePath)) { const netContent = await fetch(workflowRelativePath); workflowFilePath = workflowRelativePath; fileContent = await netContent.text(); } else { workflowFilePath = join(cwd, workflowRelativePath); fileContent = await getContent(workflowFilePath); } const workflow = parseWorkflow(fileContent); if (!isObject(workflow)) { continue; } validWorkflows.push({ ctx: { public: { env, workflowPath: workflowFilePath, workflowRelativePath: workflowRelativePath, workflowCwd: dirname(workflowFilePath), cwd: cwd, sources: {}, steps: {}, state: undefined, items: [], itemSourceOptions: undefined, }, sourcesOptions: [], currentStepType: StepType.Source, }, workflow: workflow, }); // run code } // sort by alphabet validWorkflows = validWorkflows.sort((a, b) => { const aPath = a.ctx.public.workflowRelativePath; const bPath = b.ctx.public.workflowRelativePath; if (aPath < bPath) { return -1; } if (aPath > bPath) { return 1; } return 0; }); report.info( ` ${validWorkflows.length} valid workflows:\n${ validWorkflows.map((item) => getReporterName(item.ctx)).join( "\n", ) }\n`, "Success found", ); // run workflows step by step for ( let workflowIndex = 0; workflowIndex < validWorkflows.length; workflowIndex++ ) { let { ctx, workflow } = validWorkflows[workflowIndex]; // parse root env first // parse env first const parsedWorkflowFileOptionsWithEnv = await parseObject(workflow, ctx, { keys: parse1Keys, }) as WorkflowOptions; // run env // parse env to env if (parsedWorkflowFileOptionsWithEnv.env) { for (const key in parsedWorkflowFileOptionsWithEnv.env) { const value = parsedWorkflowFileOptionsWithEnv.env[key]; if (typeof value === "string") { const debugEnvPermmision = { name: "env", variable: key } as const; if (await hasPermissionSlient(debugEnvPermmision)) { Deno.env.set(key, value); } } } } // parse general options const parsedWorkflowGeneralOptionsWithGeneral = await parseObject( parsedWorkflowFileOptionsWithEnv, ctx, { keys: parse3ForGeneralKeys, default: { if: true, }, }, ) as WorkflowOptions; const workflowOptions = getFinalWorkflowOptions( parsedWorkflowGeneralOptionsWithGeneral || {}, cliWorkflowOptions, ); isDebug = workflowOptions.debug || false; const workflowReporter = getReporter( `${getReporterName(ctx)}`, isDebug, ); // check if need to run if (!workflowOptions?.if) { workflowReporter.info( `because if condition is false`, "Skip workflow", ); continue; } else { workflowReporter.info( ``, "Start handle workflow", ); } // merge to get default ctx.public.options = workflowOptions; const database = workflowOptions.database as string; let db; if (database?.startsWith("sqlite")) { db = new SqliteDb(database); } else { let namespace = ctx.public.workflowRelativePath; if (namespace.startsWith("..")) { // use absolute path as namespace namespace = `@denoflowRoot${ctx.public.workflowPath}`; } db = new Keydb(database, { namespace: namespace, }); } ctx.db = db; // check permission // unique key let state; let internalState = { keys: [], }; if (await hasPermissionSlient(dataPermission)) { state = await db.get("state") || undefined; internalState = await db.get("internalState") || { keys: [], }; } ctx.public.state = state; ctx.internalState = internalState; ctx.initState = JSON.stringify(state); ctx.initInternalState = JSON.stringify(internalState); const sources = workflow.sources; try { if (sources) { workflowReporter.info("", "Start get sources"); for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { const source = sources[sourceIndex]; ctx.public.sourceIndex = sourceIndex; const sourceReporter = getReporter( `${getReporterName(ctx)} -> source:${ctx.public.sourceIndex}`, isDebug, ); let sourceOptions = { ...source, }; try { // parse env first sourceOptions = await parseObject(source, ctx, { keys: parse1Keys, }) as SourceOptions; // parse if only sourceOptions = await parseObject( sourceOptions, ctx, { keys: parse2Keys, default: { if: true, }, }, ) as SourceOptions; // set log level if (sourceOptions?.debug || ctx.public.options?.debug) { sourceReporter.level = log.LogLevels.DEBUG; } // check if need to run if (!sourceOptions.if) { sourceReporter.info( `because if condition is false`, "Skip source", ); } // parse on // insert step env sourceOptions = await parseObject( sourceOptions, { ...ctx, public: { ...ctx.public, env: { ...ctx.public.env, ...await getEnv(), ...sourceOptions.env, }, }, }, { keys: parse3ForStepKeys, }, ) as SourceOptions; // get options sourceOptions = getFinalSourceOptions( workflowOptions, cliWorkflowOptions, sourceOptions, ); isDebug = sourceOptions.debug || false; // check if if (!sourceOptions.if) { ctx.public.result = undefined; ctx.public.ok = true; ctx.public.error = undefined; ctx.public.cmdResult = undefined; ctx.public.cmdCode = undefined; ctx.public.cmdOk = true; ctx.public.isRealOk = true; ctx.public.sources[sourceIndex] = getStepResponse(ctx); if (sourceOptions.id) { ctx.public.sources[sourceOptions.id] = ctx.public.sources[sourceIndex]; } continue; } // run source ctx = await runStep(ctx, { reporter: sourceReporter, ...sourceOptions, }); // parse4 sourceOptions = await parseObject(sourceOptions, ctx, { keys: parse4ForSourceKeys, }) as SourceOptions; // get source items by itemsPath, key ctx = await getSourceItemsFromResult(ctx, { ...sourceOptions, reporter: sourceReporter, }); // parse6 sourceOptions = await parseObject(sourceOptions, ctx, { keys: parse6ForSourceKeys, }) as SourceOptions; // run user filter, filter from, filterItems, filterItemsFrom, only allow one. ctx = await filterSourceItems(ctx, { reporter: sourceReporter, ...sourceOptions, }); // run cmd if (sourceOptions.cmd) { sourceOptions = await parseObject(sourceOptions, ctx, { keys: parse7ForSourceKeys, }) as SourceOptions; const cmdResult = await runCmd(ctx, sourceOptions.cmd as string); ctx = setCmdOkResult(ctx, cmdResult.stdout); } // mark source items, add unique key and source index to items ctx = markSourceItems(ctx, sourceOptions); ctx.public.sources[sourceIndex] = getStepResponse(ctx); if (sourceOptions.id) { ctx.public.sources[sourceOptions.id] = ctx.public.sources[sourceIndex]; } // run assert if (sourceOptions.assert) { ctx = await runAssert(ctx, { reporter: sourceReporter, ...sourceOptions, }); } if (ctx.public.items.length > 0) { // run post sourceReporter.info( "", `Source ${sourceIndex} get ${ctx.public.items.length} items`, ); } if (sourceOptions.post) { await runPost(ctx, { reporter: sourceReporter, ...sourceOptions, }); } ctx.sourcesOptions.push(sourceOptions); } catch (e) { ctx = setErrorResult(ctx, e); ctx.public.sources[sourceIndex] = getStepResponse(ctx); if (source.id) { ctx.public.sources[source.id] = ctx.public.sources[sourceIndex]; } if (source.continueOnError) { ctx.public.ok = true; sourceReporter.warning( `Failed run source`, ); sourceReporter.warning(e); sourceReporter.warning( `Ignore this error, because continueOnError is true.`, ); break; } else { sourceReporter.error( `Failed run source`, ); throw e; } } // parse 8 sleep sourceOptions = await parseObject(sourceOptions, ctx, { keys: ["sleep"], }) as SourceOptions; // check is need sleep if (sourceOptions.sleep && sourceOptions.sleep > 0) { sourceReporter.info( `${sourceOptions.sleep} seconds`, "Sleep", ); await delay(sourceOptions.sleep * 1000); } } } // insert new ctx.items if (sources) { let collectCtxItems: unknown[] = []; sources.forEach((_, theSourceIndex) => { if (Array.isArray(ctx.public.sources[theSourceIndex].result)) { collectCtxItems = collectCtxItems.concat( ctx.public.sources[theSourceIndex].result, ); } }); ctx.public.items = collectCtxItems; if (ctx.public.items.length > 0) { workflowReporter.info( `Total ${ctx.public.items.length} items`, "Finish get sources", ); } } // if items >0, then continue if ((ctx.public.items as unknown[]).length === 0) { // no need to handle steps workflowReporter.info( `because no any valid sources items returned`, "Skip workflow", ); continue; } // run filter const filter = workflow.filter; if (filter) { ctx.currentStepType = StepType.Filter; const filterReporter = getReporter( `${getReporterName(ctx)} -> filter`, isDebug, ); let filterOptions = { ...filter }; let ifFilter = true; try { // parse env first filterOptions = await parseObject(filter, ctx, { keys: parse1Keys, }) as FilterOptions; // parse if debug only filterOptions = await parseObject( filterOptions, ctx, { keys: parse2Keys, default: { if: true, }, }, ) as FilterOptions; // set log level if (filterOptions?.debug || ctx.public.options?.debug) { filterReporter.level = log.LogLevels.DEBUG; } // check if need to run if (!filterOptions.if) { ifFilter = false; filterReporter.info( `because if condition is false`, "Skip filter", ); } else { // parse on // insert step env filterOptions = await parseObject( filterOptions, { ...ctx, public: { ...ctx.public, env: { ...ctx.public.env, ...await getEnv(), ...filterOptions.env, }, }, }, { keys: parse3ForStepKeys, }, ) as FilterOptions; // get options filterOptions = getFinalSourceOptions( workflowOptions, cliWorkflowOptions, filterOptions, ); isDebug = filterOptions.debug || false; if (!filterOptions.if) { continue; } filterReporter.info("", "Start handle filter"); // run Filter ctx = await runStep(ctx, { reporter: filterReporter, ...filterOptions, }); if ( Array.isArray(ctx.public.result) && ctx.public.result.length === ctx.public.items.length ) { ctx.public.items = ctx.public.items.filter((_item, index) => { return !!((ctx.public.result as boolean[])[index]); }); ctx.public.result = ctx.public.items; } else if (filterOptions.run || filterOptions.use) { // if run or use, then result must be array filterReporter.error( `Failed to run filter script`, ); // invalid result throw new Error( "Invalid filter step result, result must be array , boolean[], which array length must be equal to ctx.items length", ); } if (filterOptions.cmd) { filterOptions = await parseObject(filterOptions, ctx, { keys: ["cmd"], }) as FilterOptions; const cmdResult = await runCmd(ctx, filterOptions.cmd as string); ctx = setCmdOkResult(ctx, cmdResult.stdout); } ctx.public.filter = getStepResponse(ctx); // parse limit filterOptions = await parseObject(filterOptions, ctx, { keys: ["limit"], }) as FilterOptions; // run filter ctx = filterCtxItems(ctx, { ...filterOptions, reporter: filterReporter, }); // run assert if (filterOptions.assert) { ctx = await runAssert(ctx, { reporter: filterReporter, ...filterOptions, }); } // run post if (filterOptions.post) { await runPost(ctx, { reporter: filterReporter, ...filterOptions, }); } } } catch (e) { ctx = setErrorResult(ctx, e); ctx.public.filter = getStepResponse(ctx); if (filter.continueOnError) { ctx.public.ok = true; filterReporter.warning( `Failed to run filter`, ); filterReporter.warning(e); filterReporter.warning( `Ignore this error, because continueOnError is true.`, ); break; } else { filterReporter.error( `Failed to run filter`, ); throw e; } } if (ifFilter) { filterReporter.info( `Total ${ctx.public.items.length} items`, "Finish handle filter", ); // check is need sleep // parse sleep filterOptions = await parseObject(filterOptions, ctx, { keys: ["sleep"], }) as FilterOptions; if (filterOptions.sleep && filterOptions.sleep > 0) { filterReporter.info( `${filterOptions.sleep} seconds`, "Sleep", ); await delay(filterOptions.sleep * 1000); } } } ctx.currentStepType = StepType.Step; for ( let index = 0; index < (ctx.public.items as unknown[]).length; index++ ) { ctx.public.itemIndex = index; ctx.public.item = (ctx.public.items as unknown[])[index]; if ( (ctx.public.item as Record<string, string>) && (ctx.public.item as Record<string, string>)["@denoflowKey"] ) { ctx.public.itemKey = (ctx.public.item as Record<string, string>)["@denoflowKey"]; } else if (isObject(ctx.public.item)) { ctx.public.itemKey = undefined; workflowReporter.warning( `Can not found internal item key \`@denoflowKey\`, maybe you changed the item format. Missing this key, denoflow can not store the unique key state. Fix this, Try not change the reference item, only change the property you need to change. Try to manual adding a \`@denoflowKey\` as item unique key.`, ); } else { ctx.public.itemKey = undefined; } if ( (ctx.public.item as Record<string, number>) && (((ctx.public.item as Record<string, number>)[ "@denoflowSourceIndex" ]) as number) >= 0 ) { ctx.public.itemSourceIndex = ((ctx.public.item as Record<string, number>)[ "@denoflowSourceIndex" ]) as number; ctx.public.itemSourceOptions = ctx.sourcesOptions[ctx.public.itemSourceIndex]; } else if (isObject(ctx.public.item)) { ctx.public.itemSourceOptions = undefined; workflowReporter.warning( `Can not found internal item key \`@denoflowSourceIndex\`, maybe you changed the item format. Try not change the reference item, only change the property you need to change. Try to manual adding a \`@denoflowKey\` as item unique key.`, ); } else { ctx.public.itemSourceOptions = undefined; } const itemReporter = getReporter( `${getReporterName(ctx)} -> item:${index}`, isDebug, ); if (ctx.public.options?.debug) { itemReporter.level = log.LogLevels.DEBUG; } if (!workflow.steps) { workflow.steps = []; } else { itemReporter.info( ``, "Start run steps", ); itemReporter.debug(`${JSON.stringify(ctx.public.item, null, 2)}`); } for (let j = 0; j < workflow.steps.length; j++) { const step = workflow.steps[j]; ctx.public.stepIndex = j; const stepReporter = getReporter( `${getReporterName(ctx)} -> step:${ctx.public.stepIndex}`, isDebug, ); let stepOptions = { ...step }; try { // parse env first stepOptions = await parseObject(stepOptions, ctx, { keys: parse1Keys, }) as StepOptions; // parse if only stepOptions = await parseObject(stepOptions, ctx, { keys: parse2Keys, default: { if: true, }, }) as StepOptions; if (stepOptions.debug || ctx.public.options?.debug) { stepReporter.level = log.LogLevels.DEBUG; } // console.log("stepOptions1", stepOptions); if (!stepOptions.if) { stepReporter.info( `because if condition is false`, "Skip step", ); } // parse on // insert step env stepOptions = await parseObject(stepOptions, { ...ctx, public: { ...ctx.public, env: { ...ctx.public.env, ...await getEnv(), ...stepOptions.env, }, }, }, { keys: parse3ForStepKeys, default: { if: true, }, }) as StepOptions; // console.log("stepOptions2.5", stepOptions); // get options stepOptions = getFinalSourceOptions( workflowOptions, cliWorkflowOptions, stepOptions, ); isDebug = stepOptions.debug || false; stepReporter.debug( `Start run this step.`, ); // console.log('ctx2',ctx); // console.log("stepOptions2", stepOptions); if (!stepOptions.if) { ctx.public.result = undefined; ctx.public.ok = true; ctx.public.error = undefined; ctx.public.cmdResult = undefined; ctx.public.cmdCode = undefined; ctx.public.cmdOk = true; ctx.public.isRealOk = true; ctx.public.steps[j] = getStepResponse(ctx); if (step.id) { ctx.public.steps[step.id] = ctx.public.steps[j]; } continue; } ctx = await runStep(ctx, { ...stepOptions, reporter: stepReporter, }); if (stepOptions.cmd) { // parse cmd stepOptions = await parseObject(stepOptions, { ...ctx, public: { ...ctx.public, env: { ...ctx.public.env, ...await getEnv(), ...stepOptions.env, }, }, }, { keys: ["cmd"], }) as StepOptions; const cmdResult = await runCmd(ctx, stepOptions.cmd as string); ctx = setCmdOkResult(ctx, cmdResult.stdout); } ctx.public.steps[j] = getStepResponse(ctx); if (step.id) { ctx.public.steps[step.id] = ctx.public.steps[j]; } stepReporter.debug( `Finish to run this step.`, ); } catch (e) { ctx.public.steps[j] = getStepResponse(ctx); if (step.id) { ctx.public.steps[step.id] = ctx.public.steps[j]; } if (step.continueOnError) { ctx.public.ok = true; stepReporter.warning( `Failed to run step`, ); stepReporter.warning(e); stepReporter.warning( `Ignore this error, because continueOnError is true.`, ); break; } else { stepReporter.error( `Failed to run step`, ); throw e; } } // this item steps all ok, add unique keys to the internal state // run assert if (stepOptions.assert) { await runAssert(ctx, { reporter: stepReporter, ...stepOptions, }); } if (stepOptions.post) { await runPost(ctx, { reporter: stepReporter, ...stepOptions, }); } stepReporter.info("", "Finish run step " + j); // parse sleep stepOptions = await parseObject(stepOptions, ctx, { keys: ["sleep"], }) as StepOptions; // check is need sleep if (stepOptions.sleep && stepOptions.sleep > 0) { stepReporter.info( `${stepOptions.sleep} seconds`, "Sleep", ); await delay(stepOptions.sleep * 1000); } } // check is !force // get item source options if ( ctx.public.itemSourceOptions && !ctx.public.itemSourceOptions.force ) { if (!ctx.internalState || !ctx.internalState.keys) { ctx.internalState!.keys = []; } if ( ctx.public.itemKey && !ctx.internalState!.keys.includes(ctx.public.itemKey!) ) { ctx.internalState!.keys.unshift(ctx.public.itemKey!); } // only save 1000 items for save memory if (ctx.internalState!.keys.length > 1000) { ctx.internalState!.keys = ctx.internalState!.keys.slice(0, 1000); } } if (workflow.steps.length > 0) { itemReporter.info( ``, `Finish run steps`, ); } } // run post step const post = workflow.post; if (post) { const postReporter = getReporter( `${getReporterName(ctx)} -> post`, isDebug, ); let postOptions = { ...post }; try { // parse env first postOptions = await parseObject(postOptions, ctx, { keys: parse1Keys, }) as StepOptions; // parse if only postOptions = await parseObject(postOptions, ctx, { keys: parse2Keys, default: { if: true, }, }) as StepOptions; if (postOptions.debug || ctx.public.options?.debug) { postReporter.level = log.LogLevels.DEBUG; } if (!postOptions.if) { postReporter.info( `because if condition is false`, "Skip post", ); continue; } // parse on // insert step env postOptions = await parseObject(postOptions, { ...ctx, public: { ...ctx.public, env: { ...ctx.public.env, ...await getEnv(), ...postOptions.env, }, }, }, { keys: parse3ForStepKeys, }) as StepOptions; // get options postOptions = getFinalSourceOptions( workflowOptions, cliWorkflowOptions, postOptions, ); isDebug = postOptions.debug || false; postReporter.info( `Start run post.`, ); // console.log('ctx2',ctx); ctx = await runStep(ctx, { ...postOptions, reporter: postReporter, }); if (postOptions.cmd) { // parse cmd postOptions = await parseObject(postOptions, ctx, { keys: ["cmd"], }) as StepOptions; const cmdResult = await runCmd(ctx, postOptions.cmd as string); ctx = setCmdOkResult(ctx, cmdResult.stdout); } postReporter.debug( `Finish to run post.`, ); } catch (e) { if (post.continueOnError) { ctx.public.ok = true; postReporter.warning( `Failed to run post`, ); postReporter.warning(e); postReporter.warning( `Ignore this error, because continueOnError is true.`, ); break; } else { postReporter.error( `Failed to run post`, ); throw e; } } // this item steps all ok, add unique keys to the internal state // run assert if (postOptions.assert) { await runAssert(ctx, { reporter: postReporter, ...postOptions, }); } if (postOptions.post) { await runPost(ctx, { reporter: postReporter, ...postOptions, }); } postReporter.info("", "Finish run post "); // parse sleep postOptions = await parseObject(postOptions, ctx, { keys: ["sleep"], }) as StepOptions; // check is need sleep if (postOptions.sleep && postOptions.sleep > 0) { postReporter.info( `${postOptions.sleep} seconds`, "Sleep", ); await delay(postOptions.sleep * 1000); } } // save state, internalState // check is changed const currentState = JSON.stringify(ctx.public.state); // add success items uniqueKey to internal State const currentInternalState = JSON.stringify(ctx.internalState); if (currentState !== ctx.initState) { workflowReporter.debug(`Save state`); await ctx.db!.set("state", ctx.public.state); } else { // workflowReporter.debug(`Skip save sate, cause no change happened`); } if (currentInternalState !== ctx.initInternalState) { workflowReporter.debug( `Save internal state`, ); await ctx.db!.set("internalState", ctx.internalState); } else { // workflowReporter.debug( // `Skip save internal state, cause no change happened`, // ); } workflowReporter.info( ``, "Finish workflow", ); } catch (e) { workflowReporter.error( `Failed to run this workflow`, ); workflowReporter.error(e); if (validWorkflows.length > workflowIndex + 1) { workflowReporter.debug("workflow", "Start next workflow"); } errors.push({ ctx, error: e, }); } console.log("\n"); } if (errors.length > 0) { report.error("Error details:"); errors.forEach((error) => { report.error( `Run ${getReporterName(error.ctx)} failed, error: `, ); report.error(error.error); }); throw new Error(`Failed to run this time`); } } function getReporterName(ctx: Context) { const relativePath = ctx.public.workflowRelativePath; const absolutePath = ctx.public.workflowPath; if (relativePath.startsWith("..")) { return absolutePath; } else { return relativePath; } }
the_stack
import * as Yup from "yup"; import { addMethod, ArraySchema, mixed, number, object, Schema, string, ValidationError } from "yup"; addMethod(object, "unique", function (propertyName, message) { //@ts-ignore return this.test("unique", message, function (value) { if (!value || !value[propertyName]) { return true; } //@ts-ignore const { path } = this; //@ts-ignore const options = [...this.parent]; const currentIndex = options.indexOf(value); const subOptions = options.slice(0, currentIndex); if (subOptions.some((option) => option[propertyName] === value[propertyName])) { //@ts-ignore throw this.createError({ path: `${path}.${propertyName}`, message, }); } return true; }); }); export const ValidatorOneof = (...options: (string | RegExp)[]) => { return (value: string) => { if (!value) return undefined; for (let i = 0; i < options.length; i++) { if (typeof options[i] === "string" && value === options[i]) { return undefined; } else if ( typeof options[i] === "object" && options[i].constructor.name === "RegExp" && value.match(options[i]) ) { return undefined; } } return `Must be one of ${options.map((x) => x.toString()).join(", ")}`; }; }; export const regExpIp = new RegExp( "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ); // https://regex101.com/r/wG1nZ3/37 export const regExpWildcardDomain = new RegExp(/^(\*\.)?([\w-]+\.)+[a-zA-Z]+$/); const yupValidatorWrap = function <T>(...v: Schema<T>[]) { return function (value: T) { let schema: Schema<T>; if (v.length === 1) { schema = v[0]; } else { schema = mixed(); for (let i = 0; i < v.length; i++) { schema = schema.concat(v[i]); } } try { schema.validateSync(value); return undefined; } catch (e) { if (!ValidationError.isError(e)) { throw e; } return e.errors[0] || "Unknown error"; } }; }; const yupValidatorWrapForArray = function <T>(arraySchema: ArraySchema<T>, ...v: Schema<T>[]) { return function (values: T[]) { try { arraySchema.validateSync(values); } catch (e) { if (!ValidationError.isError(e)) { throw e; } return e.errors[0] || "Unknown error"; } if (v.length === 0) { return undefined; } const validateFunction = yupValidatorWrap<T>(...v); const errors = values.map((value) => validateFunction(value)); if (errors.findIndex((x) => !!x) < 0) { return undefined; } return errors; }; }; // Basic yup validator const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*"; const envVarNameFmtErrMsg = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit"; const IsEnvVarName = string() .required("Required") .matches(new RegExp(`^${envVarNameFmt}$`), envVarNameFmtErrMsg); const dns1123LabelFmt = "[a-z0-9]([-a-z0-9]*[a-z0-9])?"; const IsDNS1123Label = string() .required("Required") .max(63, "Max length is 63") .matches( new RegExp(`^${dns1123LabelFmt}$`), "Not a valid DNS1123 label. Regex is " + new RegExp(`^${dns1123LabelFmt}$`), ); const dns1123SubDomainFmt = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*"; export const InvalidDNS1123SubDomain = "Invalid domain"; const IsDNS1123SubDomain = string() .required("Required") .matches(new RegExp(`^${dns1123SubDomainFmt}$`), InvalidDNS1123SubDomain) .max(253); const IsDNS1123SubDomainWithOptionalWildcardPrefix = string() .required("Required") .matches(new RegExp(`^(\\*\\.|\\*-*)?${dns1123SubDomainFmt}$`), InvalidDNS1123SubDomain) .max(253); // wildcard definition - RFC 1034 section 4.3.3. // examples: // - valid: *.bar.com, *.foo.bar.com // - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, * const wildcardDNS1123SubDomainFmt = "\\*\\." + dns1123SubDomainFmt; const IsWildcardDNS1123SubDomain = Yup.string() .required("Required") .matches(new RegExp(`^${wildcardDNS1123SubDomainFmt}$`), "Not a valid wildcard DNS123 SubDomain") .max(253); export const IsOrCommonOrWildcardDNS1123SubDomain = Yup.string() .required("Required") .matches( new RegExp(`^(${wildcardDNS1123SubDomainFmt}|${dns1123SubDomainFmt})\\.${dns1123LabelFmt}$`), `Not a valid domain. Valid examples: "foo.bar"; "*.foo.bar"`, ) .max(253); const hostnameFmt = "[a-z0-9_]([-a-z0-9_]*[a-z0-9_])?"; export const InvalidHostInCertificateErrorMessage = "Invalid domain"; const IsValidHostInCertificate = Yup.string() .required("Required") .max(253) .matches( new RegExp(`^(?:\\*\\.)?(?:${hostnameFmt}\\.)*${dns1123LabelFmt}\\.${dns1123LabelFmt}$`), InvalidHostInCertificateErrorMessage, ); // ================= Kalm Validators ================== export const ValidatorIsEnvVarName = yupValidatorWrap<string>(IsEnvVarName); export const ValidatorIsDNS123Label = yupValidatorWrap<string>(IsDNS1123Label); export const ValidatorIsDNS1123SubDomain = yupValidatorWrap<string>(IsDNS1123SubDomain); export const ValidatorArrayOfIsDNS1123SubDomain = yupValidatorWrapForArray<string>( Yup.array<string>().required("Should have at least one item"), IsDNS1123SubDomain, ); export const ValidatorArrayOfIsDNS1123SubDomainWithOptionalWildcardPrefix = yupValidatorWrapForArray<string>( Yup.array<string>().required("Should have at least one item"), IsDNS1123SubDomainWithOptionalWildcardPrefix, ); export const ValidatorArrayOfIsValidHostInCertificate = yupValidatorWrapForArray<string>( Yup.array<string>().required("Should have at least one item"), IsValidHostInCertificate, ); export const ValidatorIsWildcardDNS1123SubDomain = yupValidatorWrap<string>(IsWildcardDNS1123SubDomain); export const ValidatorIsCommonOrWildcardDNS1123SubDomain = yupValidatorWrap<string>( IsOrCommonOrWildcardDNS1123SubDomain, ); export const ValidatorArrayOfDIsWildcardDNS1123SubDomain = yupValidatorWrapForArray<string>( Yup.array<string>().required("Should have at least one item"), IsWildcardDNS1123SubDomain, ); // Allowed characters in an HTTP Path as defined by RFC 3986. A HTTP path may // contain: // * unreserved characters (alphanumeric, '-', '.', '_', '~') // * percent-encoded octets // * sub-delims ("!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=") // * a colon character (":") export const NotValidPathPrefixError = "Not a valid path prefix"; export const NoPrefixSlashError = 'Should start with a "/"'; export const PathArrayCantBeBlankError = "Should have at least one path prefix"; export const InvalidHostError = "Host must be a valid IP address or hostname."; export const ValidatorArrayOfPath = yupValidatorWrapForArray<string>( Yup.array<string>().required(PathArrayCantBeBlankError), Yup.string() .required("Path Prefix can'b be blank") .matches(/^\//, NoPrefixSlashError) .matches(/^\/[A-Za-z0-9/\-._~%!$&'()*+,;=:]*$/, NotValidPathPrefixError), ); export const ValidatorContainerPortRequired = yupValidatorWrap<number | undefined>( number() .required("Required") .test("", "Can't use 443 port", (value) => value !== 443), ); export const ValidatorPort = yupValidatorWrap<number | undefined>( number().test("", "Can't use 443 port", (value) => value !== 443), ); export const ValidatorIsEmail = yupValidatorWrap<string>(string().required("Required").email("invalid email address")); export const ValidatorRequired = yupValidatorWrap<any>( mixed() .required("Required") // mixed.required() will not validate empty string .test("", "Required", (value) => typeof value !== "string" || value !== ""), ); export const ValidatorVolumeSize = yupValidatorWrap<string>( string() .required("Required") .notOneOf(["0Gi"], "Invalid Value") .matches(/(^\d+(\.\d+)?)(Gi)$/, "Invalid Value"), ); export const ValidatorMemory = yupValidatorWrap<string | undefined>( string() .notRequired() .notOneOf(["0Mi"], "Invalid Value") .matches(/(^\d+(\.\d+)?)(Mi)$/, "Invalid Value"), ); export const ValidatorCPU = yupValidatorWrap<string | undefined>( string().test( "Validate CPU", "The minimum support is 1m", (value) => value === undefined || parseFloat(`${value}`) >= 1, ), ); export const ValidatorSchedule = yupValidatorWrap<string | undefined>( string() .required("Required") .matches( /^(\*|((\*\/)?[1-5]?[0-9])) (\*|((\*\/)?[1-5]?[0-9])) (\*|((\*\/)?(1?[0-9]|2[0-3]))) (\*|((\*\/)?([1-9]|[12][0-9]|3[0-1]))) (\*|((\*\/)?([1-9]|1[0-2])))$/, "Invalid Schedule Rule", ), ); export const ValidatorInjectedFilePath = yupValidatorWrap<string | undefined>( string() .required("Required") .test("", 'Must be an absolute path, which starts with a "/"', (value) => !value || value.startsWith("/")) .test("", 'File name mush not end with "/"', (value) => !value || !value.endsWith("/")), ); export const ValidatorRegistryHost = yupValidatorWrap<string | undefined>( string() .notRequired() .test("", 'Require prefix "https://"', (value) => !value || value.startsWith("https://")) .test("", 'Require no suffix "/"', (value) => !value || !value.endsWith("/")), ); export const ValidatorArrayNotEmpty = yupValidatorWrapForArray( Yup.array<any>().required("Should have at least one item"), ); export const validateHostWithWildcardPrefix = yupValidatorWrap<string | undefined>( string() .required("Required") .max(511) .test( "", InvalidHostError, (value) => value === undefined || !!String(value).match(regExpIp) || !!String(value).match(regExpWildcardDomain), ), ); export const ValidatorIpAndHosts = yupValidatorWrapForArray( Yup.array<string>().required("Required"), string() .required("Required") .max(511) .test( "", InvalidHostError, (value) => value === undefined || value === "*" || !!String(value).match(regExpIp) || !!String(value).match(regExpWildcardDomain), ), ); export const ValidateHost = yupValidatorWrap<string | undefined>( string() .required("Required") .max(511) .test("", "Domain is invalid.", (value) => value === undefined || !!String(value).match(regExpWildcardDomain)), ); export const ValidatorOneOfFactory = (values: any[]) => yupValidatorWrap(Yup.string().oneOf(values)); export const ValidatorEnvName = yupValidatorWrap<string>( string() .required() .matches( /^[-._a-zA-Z][-._a-zA-Z0-9]*$/, "Env name is invalid. regex used for validation is '[-._a-zA-Z][-._a-zA-Z0-9]*'", ), );
the_stack
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/cr_icons_css.m.js'; import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {skColorToRgba} from 'chrome://resources/js/color_utils.js'; import {isMac} from 'chrome://resources/js/cr.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {hasKeyModifiers} from 'chrome://resources/js/util.m.js'; import {TextDirection} from 'chrome://resources/mojo/mojo/public/mojom/base/text_direction.mojom-webui.js'; import {SkColor} from 'chrome://resources/mojo/skia/public/mojom/skcolor.mojom-webui.js'; import {Url} from 'chrome://resources/mojo/url/mojom/url.mojom-webui.js'; import {DomRepeat, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {MostVisitedBrowserProxy} from './browser_proxy.js'; import {MostVisitedInfo, MostVisitedPageCallbackRouter, MostVisitedPageHandlerRemote, MostVisitedTheme, MostVisitedTile} from './most_visited.mojom-webui.js'; import {MostVisitedWindowProxy} from './window_proxy.js'; enum ScreenWidth { NARROW = 0, MEDIUM = 1, WIDE = 2, } function resetTilePosition(tile: HTMLElement) { tile.style.position = ''; tile.style.left = ''; tile.style.top = ''; } function setTilePosition(tile: HTMLElement, {x, y}: {x: number, y: number}) { tile.style.position = 'fixed'; tile.style.left = `${x}px`; tile.style.top = `${y}px`; } function getHitIndex(rects: Array<DOMRect>, x: number, y: number): number { return rects.findIndex( r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom); } /** * Returns null if URL is not valid. */ function normalizeUrl(urlString: string): URL|null { try { const url = new URL( urlString.includes('://') ? urlString : `https://${urlString}/`); if (['http:', 'https:'].includes(url.protocol)) { return url; } } catch (e) { } return null; } interface RepeaterEvent extends Event { model: { item: MostVisitedTile, index: number, }; } const MostVisitedElementBase = I18nMixin(PolymerElement); export interface MostVisitedElement { $: { actionMenu: CrActionMenuElement, container: HTMLElement, dialog: CrDialogElement, toast: CrToastElement, addShortcut: HTMLElement, tiles: DomRepeat, }; } export class MostVisitedElement extends MostVisitedElementBase { static get is() { return 'cr-most-visited'; } static get properties() { return { theme: Object, /** * When the tile icon background is dark, the icon color is white for * contrast. This can be used to determine the color of the tile hover as * well. */ useWhiteTileIcon_: { type: Boolean, reflectToAttribute: true, computed: `computeUseWhiteTileIcon_(theme)`, }, /** * If true wraps the tile titles in white pills. */ useTitlePill_: { type: Boolean, reflectToAttribute: true, computed: `computeUseTitlePill_(theme)`, }, columnCount_: { type: Number, computed: `computeColumnCount_(tiles_, screenWidth_, maxTiles_)`, }, rowCount_: { type: Number, computed: 'computeRowCount_(columnCount_, tiles_)', }, customLinksEnabled_: { type: Boolean, reflectToAttribute: true, }, dialogTileTitle_: String, dialogTileUrl_: { type: String, observer: 'onDialogTileUrlChange_', }, dialogTileUrlInvalid_: { type: Boolean, value: false, }, dialogTitle_: String, dialogSaveDisabled_: { type: Boolean, computed: `computeDialogSaveDisabled_(dialogTitle_, dialogTileUrl_, dialogShortcutAlreadyExists_)`, }, dialogShortcutAlreadyExists_: { type: Boolean, computed: 'computeDialogShortcutAlreadyExists_(tiles_, dialogTileUrl_)', }, dialogTileUrlError_: { type: String, computed: `computeDialogTileUrlError_(dialogTileUrl_, dialogShortcutAlreadyExists_)`, }, isDark_: { type: Boolean, reflectToAttribute: true, computed: `computeIsDark_(theme)`, }, /** * Used to hide hover style and cr-icon-button of tiles while the tiles * are being reordered. */ reordering_: { type: Boolean, value: false, reflectToAttribute: true, }, maxTiles_: { type: Number, computed: 'computeMaxTiles_(customLinksEnabled_)', }, maxVisibleTiles_: { type: Number, computed: 'computeMaxVisibleTiles_(columnCount_, rowCount_)', }, showAdd_: { type: Boolean, value: false, computed: 'computeShowAdd_(tiles_, maxVisibleTiles_, customLinksEnabled_)', }, showToastButtons_: Boolean, screenWidth_: Number, tiles_: Array, toastContent_: String, visible_: { type: Boolean, reflectToAttribute: true, }, }; } private theme: MostVisitedTheme|null; private useWhiteTileIcon_: boolean; private useTitlePill_: boolean; private columnCount_: number; private rowCount_: number; private customLinksEnabled_: boolean; private dialogTileTitle_: string; private dialogTileUrl_: string; private dialogTileUrlInvalid_: boolean; private dialogTitle_: string; private dialogSaveDisabled_: boolean; private dialogShortcutAlreadyExists_: boolean; private dialogTileUrlError_: string; private isDark_: boolean; private reordering_: boolean; private maxTiles_: number; private maxVisibleTiles_: number; private showAdd_: boolean; private showToastButtons_: boolean; private screenWidth_: ScreenWidth; private tiles_: Array<MostVisitedTile>; private toastContent_: string; private visible_: boolean; private adding_: boolean = false; private callbackRouter_: MostVisitedPageCallbackRouter; private pageHandler_: MostVisitedPageHandlerRemote; private windowProxy_: MostVisitedWindowProxy; private setMostVisitedInfoListenerId_: number|null = null; private actionMenuTargetIndex_: number = -1; private dragOffset_: {x: number, y: number}|null; private tileRects_: Array<DOMRect> = []; private isRtl_: boolean; private eventTracker_: EventTracker; private boundOnWidthChange_: () => void; private mediaListenerWideWidth_: MediaQueryList; private mediaListenerMediumWidth_: MediaQueryList; private boundOnDocumentKeyDown_: (e: KeyboardEvent) => void; private get tileElements_() { return Array.from( this.shadowRoot!.querySelectorAll<HTMLElement>('.tile:not([hidden])')); } // Suppress TypeScript's error TS2376 to intentionally allow calling // performance.mark() before calling super(). // @ts-ignore constructor() { performance.mark('most-visited-creation-start'); super(); this.callbackRouter_ = MostVisitedBrowserProxy.getInstance().callbackRouter; this.pageHandler_ = MostVisitedBrowserProxy.getInstance().handler; this.windowProxy_ = MostVisitedWindowProxy.getInstance(); /** * This is the position of the mouse with respect to the top-left corner * of the tile being dragged. */ this.dragOffset_ = null; } connectedCallback() { super.connectedCallback(); this.isRtl_ = window.getComputedStyle(this)['direction'] === 'rtl'; this.eventTracker_ = new EventTracker(); this.setMostVisitedInfoListenerId_ = this.callbackRouter_.setMostVisitedInfo.addListener( (info: MostVisitedInfo) => { performance.measure( 'most-visited-mojo', 'most-visited-mojo-start'); this.visible_ = info.visible; this.customLinksEnabled_ = info.customLinksEnabled; this.tiles_ = info.tiles.slice(0, assert(this.maxTiles_)); }); performance.mark('most-visited-mojo-start'); this.eventTracker_.add(document, 'visibilitychange', () => { // This updates the most visited tiles every time the NTP tab gets // activated. if (document.visibilityState === 'visible') { this.pageHandler_.updateMostVisitedInfo(); } }); this.pageHandler_.updateMostVisitedInfo(); FocusOutlineManager.forDocument(document); } disconnectedCallback() { super.disconnectedCallback(); this.mediaListenerWideWidth_.removeListener( assert(this.boundOnWidthChange_)); this.mediaListenerMediumWidth_.removeListener( assert(this.boundOnWidthChange_)); this.ownerDocument.removeEventListener( 'keydown', this.boundOnDocumentKeyDown_); this.eventTracker_.removeAll(); } ready() { super.ready(); this.boundOnWidthChange_ = this.updateScreenWidth_.bind(this); this.mediaListenerWideWidth_ = this.windowProxy_.matchMedia('(min-width: 672px)'); this.mediaListenerWideWidth_.addListener(this.boundOnWidthChange_); this.mediaListenerMediumWidth_ = this.windowProxy_.matchMedia('(min-width: 560px)'); this.mediaListenerMediumWidth_.addListener(this.boundOnWidthChange_); this.updateScreenWidth_(); this.boundOnDocumentKeyDown_ = e => this.onDocumentKeyDown_(e); this.ownerDocument.addEventListener( 'keydown', this.boundOnDocumentKeyDown_); performance.measure('most-visited-creation', 'most-visited-creation-start'); } private rgbaOrInherit_(skColor: SkColor|null): string { return skColor ? skColorToRgba(skColor) : 'inherit'; } private clearForceHover_() { const forceHover = this.shadowRoot!.querySelector('.force-hover'); if (forceHover) { forceHover.classList.remove('force-hover'); } } private computeColumnCount_(): number { let maxColumns = 3; if (this.screenWidth_ === ScreenWidth.WIDE) { maxColumns = 5; } else if (this.screenWidth_ === ScreenWidth.MEDIUM) { maxColumns = 4; } const shortcutCount = this.tiles_ ? this.tiles_.length : 0; const canShowAdd = this.maxTiles_ > shortcutCount; const tileCount = Math.min(this.maxTiles_, shortcutCount + (canShowAdd ? 1 : 0)); const columnCount = tileCount <= maxColumns ? tileCount : Math.min(maxColumns, Math.ceil(tileCount / 2)); return columnCount || 3; } private computeRowCount_(): number { if (this.columnCount_ === 0) { return 0; } const shortcutCount = this.tiles_ ? this.tiles_.length : 0; return this.columnCount_ <= shortcutCount ? 2 : 1; } private computeMaxTiles_(): number { return this.customLinksEnabled_ ? 10 : 8; } private computeMaxVisibleTiles_(): number { return this.columnCount_ * this.rowCount_; } private computeShowAdd_(): boolean { return this.customLinksEnabled_ && this.tiles_ && this.tiles_.length < this.maxVisibleTiles_; } private computeDialogSaveDisabled_(): boolean { return !this.dialogTileUrl_.trim() || normalizeUrl(this.dialogTileUrl_) === null || this.dialogShortcutAlreadyExists_; } private computeDialogShortcutAlreadyExists_(): boolean { const dialogTileHref = (normalizeUrl(this.dialogTileUrl_) || {}).href; if (!dialogTileHref) { return false; } return (this.tiles_ || []).some(({url: {url}}, index) => { if (index === this.actionMenuTargetIndex_) { return false; } const otherUrl = normalizeUrl(url); return otherUrl && otherUrl.href === dialogTileHref; }); } private computeDialogTileUrlError_(): string { return loadTimeData.getString( this.dialogShortcutAlreadyExists_ ? 'shortcutAlreadyExists' : 'invalidUrl'); } private computeIsDark_(): boolean { return this.theme ? this.theme.isDark : false; } private computeUseWhiteTileIcon_(): boolean { return this.theme ? this.theme.useWhiteTileIcon : false; } private computeUseTitlePill_(): boolean { return this.theme ? this.theme.useTitlePill : false; } /** * If a pointer is over a tile rect that is different from the one being * dragged, the dragging tile is moved to the new position. The reordering * is done in the DOM and the by the |reorderMostVisitedTile()| call. This is * done to prevent flicking between the time when the tiles are moved back to * their original positions (by removing position absolute) and when the * tiles are updated via a |setMostVisitedTiles()| call. * * |reordering_| is not set to false when the tiles are reordered. The callers * will need to set it to false. This is necessary to handle a mouse drag * issue. */ private dragEnd_(x: number, y: number) { if (!this.customLinksEnabled_) { this.reordering_ = false; return; } this.dragOffset_ = null; const dragElement = this.shadowRoot!.querySelector<HTMLElement>('.tile.dragging'); if (!dragElement) { this.reordering_ = false; return; } const dragIndex = (this.$.tiles.modelForElement(dragElement) as unknown as { index: number }).index; dragElement.classList.remove('dragging'); this.tileElements_.forEach(el => resetTilePosition(el)); resetTilePosition(this.$.addShortcut); const dropIndex = getHitIndex(this.tileRects_, x, y); if (dragIndex !== dropIndex && dropIndex > -1) { const [draggingTile] = this.tiles_.splice(dragIndex, 1); this.tiles_.splice(dropIndex, 0, draggingTile); this.notifySplices('tiles_', [ { index: dragIndex, removed: [draggingTile], addedCount: 0, object: this.tiles_, type: 'splice', }, { index: dropIndex, removed: [], addedCount: 1, object: this.tiles_, type: 'splice', }, ]); this.pageHandler_.reorderMostVisitedTile(draggingTile.url, dropIndex); } } /** * The positions of the tiles are updated based on the location of the * pointer. */ private dragOver_(x: number, y: number) { const dragElement = this.shadowRoot!.querySelector<HTMLElement>('.tile.dragging'); if (!dragElement) { this.reordering_ = false; return; } const dragIndex = (this.$.tiles.modelForElement(dragElement) as unknown as { index: number }).index; setTilePosition(dragElement, { x: x - this.dragOffset_!.x, y: y - this.dragOffset_!.y, }); const dropIndex = getHitIndex(this.tileRects_, x, y); this.tileElements_.forEach((element, i) => { let positionIndex; if (i === dragIndex) { return; } else if (dropIndex === -1) { positionIndex = i; } else if (dragIndex < dropIndex && dragIndex <= i && i <= dropIndex) { positionIndex = i - 1; } else if (dragIndex > dropIndex && dragIndex >= i && i >= dropIndex) { positionIndex = i + 1; } else { positionIndex = i; } setTilePosition(element, this.tileRects_[positionIndex]); }); } /** * Sets up tile reordering for both drag and touch events. This method stores * the following to be used in |dragOver_()| and |dragEnd_()|. * |dragOffset_|: This is the mouse/touch offset with respect to the * top/left corner of the tile being dragged. It is used to update the * dragging tile location during the drag. * |reordering_|: This is property/attribute used to hide the hover style * and cr-icon-button of the tiles while they are being reordered. * |tileRects_|: This is the rects of the tiles before the drag start. It is * to determine which tile the pointer is over while dragging. */ private dragStart_(dragElement: HTMLElement, x: number, y: number) { // Need to clear the tile that has a forced hover style for when the drag // started without moving the mouse after the last drag/drop. this.clearForceHover_(); dragElement.classList.add('dragging'); const dragElementRect = dragElement.getBoundingClientRect(); this.dragOffset_ = { x: x - dragElementRect.x, y: y - dragElementRect.y, }; const tileElements = this.tileElements_; // Get all the rects first before setting the absolute positions. this.tileRects_ = tileElements.map(t => t.getBoundingClientRect()); if (this.showAdd_) { const element = this.$.addShortcut; setTilePosition(element, element.getBoundingClientRect()); } tileElements.forEach((tile, i) => { setTilePosition(tile, this.tileRects_[i]); }); this.reordering_ = true; } private getFaviconUrl_(url: Url): string { const faviconUrl = new URL('chrome://favicon2/'); faviconUrl.searchParams.set('size', '24'); faviconUrl.searchParams.set('scale_factor', '1x'); faviconUrl.searchParams.set('show_fallback_monogram', ''); faviconUrl.searchParams.set('page_url', url.url); return faviconUrl.href; } private getRestoreButtonText_(): string { return loadTimeData.getString( this.customLinksEnabled_ ? 'restoreDefaultLinks' : 'restoreThumbnailsShort'); } private getTileTitleDirectionClass_(tile: MostVisitedTile): string { return tile.titleDirection === TextDirection.RIGHT_TO_LEFT ? 'title-rtl' : 'title-ltr'; } private isHidden_(index: number): boolean { return index >= this.maxVisibleTiles_; } private onAdd_() { this.dialogTitle_ = loadTimeData.getString('addLinkTitle'); this.dialogTileTitle_ = ''; this.dialogTileUrl_ = ''; this.dialogTileUrlInvalid_ = false; this.adding_ = true; this.$.dialog.showModal(); } private onAddShortcutKeyDown_(e: KeyboardEvent) { if (hasKeyModifiers(e)) { return; } if (!this.tiles_ || this.tiles_.length === 0) { return; } const backKey = this.isRtl_ ? 'ArrowRight' : 'ArrowLeft'; if (e.key === backKey || e.key === 'ArrowUp') { this.tileFocus_(this.tiles_.length - 1); } } private onDialogCancel_() { this.actionMenuTargetIndex_ = -1; this.$.dialog.cancel(); } private onDialogClose_() { this.dialogTileUrl_ = ''; if (this.adding_) { this.$.addShortcut.focus(); } this.adding_ = false; } private onDialogTileUrlBlur_() { if (this.dialogTileUrl_.length > 0 && (normalizeUrl(this.dialogTileUrl_) === null || this.dialogShortcutAlreadyExists_)) { this.dialogTileUrlInvalid_ = true; } } private onDialogTileUrlChange_() { this.dialogTileUrlInvalid_ = false; } private onDocumentKeyDown_(e: KeyboardEvent) { if (e.altKey || e.shiftKey) { return; } const modifier = isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey; if (modifier && e.key === 'z') { e.preventDefault(); this.onUndoClick_(); } } private onDragStart_(e: DragEvent) { if (!this.customLinksEnabled_) { return; } // |dataTransfer| is null in tests. if (e.dataTransfer) { // Remove the ghost image that appears when dragging. e.dataTransfer.setDragImage(new Image(), 0, 0); } this.dragStart_(e.target as HTMLElement, e.x, e.y); const dragOver = (e: DragEvent) => { e.preventDefault(); e.dataTransfer!.dropEffect = 'move'; this.dragOver_(e.x, e.y); }; this.ownerDocument.addEventListener('dragover', dragOver); this.ownerDocument.addEventListener('dragend', e => { this.ownerDocument.removeEventListener('dragover', dragOver); this.dragEnd_(e.x, e.y); const dropIndex = getHitIndex(this.tileRects_, e.x, e.y); if (dropIndex !== -1) { this.tileElements_[dropIndex].classList.add('force-hover'); } this.addEventListener('pointermove', () => { this.clearForceHover_(); // When |reordering_| is true, the normal hover style is not shown. // After a drop, the element that has hover is not correct. It will be // after the mouse moves. this.reordering_ = false; }, {once: true}); }, {once: true}); } private onEdit_() { this.$.actionMenu.close(); this.dialogTitle_ = loadTimeData.getString('editLinkTitle'); const tile = this.tiles_[this.actionMenuTargetIndex_]; this.dialogTileTitle_ = tile.title; this.dialogTileUrl_ = tile.url.url; this.dialogTileUrlInvalid_ = false; this.$.dialog.showModal(); } private onRestoreDefaultsClick_() { if (!this.$.toast.open || !this.showToastButtons_) { return; } this.$.toast.hide(); this.pageHandler_.restoreMostVisitedDefaults(); } private async onRemove_() { this.$.actionMenu.close(); await this.tileRemove_(this.actionMenuTargetIndex_); this.actionMenuTargetIndex_ = -1; } private async onSave_() { const newUrl = {url: normalizeUrl(this.dialogTileUrl_)!.href}; this.$.dialog.close(); let newTitle = this.dialogTileTitle_.trim(); if (newTitle.length === 0) { newTitle = this.dialogTileUrl_; } if (this.adding_) { const {success} = await this.pageHandler_.addMostVisitedTile(newUrl, newTitle); this.toast_(success ? 'linkAddedMsg' : 'linkCantCreate', success); } else { const {url, title} = this.tiles_[this.actionMenuTargetIndex_]; if (url.url !== newUrl.url || title !== newTitle) { const {success} = await this.pageHandler_.updateMostVisitedTile( url, newUrl, newTitle); this.toast_(success ? 'linkEditedMsg' : 'linkCantEdit', success); } this.actionMenuTargetIndex_ = -1; } } private onTileActionButtonClick_(e: RepeaterEvent) { e.preventDefault(); this.actionMenuTargetIndex_ = e.model.index; this.$.actionMenu.showAt(e.target as HTMLElement); } private onTileRemoveButtonClick_(e: RepeaterEvent) { e.preventDefault(); this.tileRemove_(e.model.index); } private onTileClick_(e: MouseEvent&RepeaterEvent) { if (e.defaultPrevented) { // Ignore previousely handled events. return; } if (loadTimeData.getBoolean('handleMostVisitedNavigationExplicitly')) { e.preventDefault(); // Prevents default browser action (navigation). } this.pageHandler_.onMostVisitedTileNavigation( e.model.item, e.model.index, e.button || 0, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey); } private onTileKeyDown_(e: KeyboardEvent&RepeaterEvent) { if (hasKeyModifiers(e)) { return; } if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight' && e.key !== 'ArrowUp' && e.key !== 'ArrowDown' && e.key !== 'Delete') { return; } const index = e.model.index; if (e.key === 'Delete') { this.tileRemove_(index); return; } const advanceKey = this.isRtl_ ? 'ArrowLeft' : 'ArrowRight'; const delta = (e.key === advanceKey || e.key === 'ArrowDown') ? 1 : -1; this.tileFocus_(Math.max(0, index + delta)); } private onUndoClick_() { if (!this.$.toast.open || !this.showToastButtons_) { return; } this.$.toast.hide(); this.pageHandler_.undoMostVisitedTileAction(); } private onTouchStart_(e: TouchEvent) { if (this.reordering_ || !this.customLinksEnabled_) { return; } const tileElement = (e.composedPath() as HTMLElement[]) .find(el => el.classList && el.classList.contains('tile')); if (!tileElement) { return; } const {clientX, clientY} = e.changedTouches[0]; this.dragStart_(tileElement, clientX, clientY); const touchMove = (e: TouchEvent) => { const {clientX, clientY} = e.changedTouches[0]; this.dragOver_(clientX, clientY); }; const touchEnd = (e: TouchEvent) => { this.ownerDocument.removeEventListener('touchmove', touchMove); tileElement.removeEventListener('touchend', touchEnd); tileElement.removeEventListener('touchcancel', touchEnd); const {clientX, clientY} = e.changedTouches[0]; this.dragEnd_(clientX, clientY); this.reordering_ = false; }; this.ownerDocument.addEventListener('touchmove', touchMove); tileElement.addEventListener('touchend', touchEnd, {once: true}); tileElement.addEventListener('touchcancel', touchEnd, {once: true}); } private tileFocus_(index: number) { if (index < 0) { return; } const tileElements = this.tileElements_; if (index < tileElements.length) { tileElements[index].focus(); } else if (this.showAdd_ && index === tileElements.length) { this.$.addShortcut.focus(); } } private toast_(msgId: string, showButtons: boolean) { this.toastContent_ = loadTimeData.getString(msgId); this.showToastButtons_ = showButtons; this.$.toast.show(); } private tileRemove_(index: number) { const {url, isQueryTile} = this.tiles_[index]; this.pageHandler_.deleteMostVisitedTile(url); // Do not show the toast buttons when a query tile is removed unless it is a // custom link. Removal is not reversible for non custom link query tiles. this.toast_( 'linkRemovedMsg', /* showButtons= */ this.customLinksEnabled_ || !isQueryTile); this.tileFocus_(index); } private updateScreenWidth_() { if (this.mediaListenerWideWidth_.matches) { this.screenWidth_ = ScreenWidth.WIDE; } else if (this.mediaListenerMediumWidth_.matches) { this.screenWidth_ = ScreenWidth.MEDIUM; } else { this.screenWidth_ = ScreenWidth.NARROW; } } private onTilesRendered_() { performance.measure('most-visited-rendered'); this.pageHandler_.onMostVisitedTilesRendered( this.tiles_.slice(0, assert(this.maxVisibleTiles_)), this.windowProxy_.now()); } static get template() { return html`{__html_template__}`; } } customElements.define(MostVisitedElement.is, MostVisitedElement);
the_stack
import express from "express"; import { Maybe } from "tsmonad"; import Database from "./Database"; import { PublicUser } from "magda-typescript-common/src/authorization-api/model"; import { getUserIdHandling } from "magda-typescript-common/src/session/GetUserId"; import GenericError from "magda-typescript-common/src/authorization-api/GenericError"; import AuthError from "magda-typescript-common/src/authorization-api/AuthError"; import { installStatusRouter } from "magda-typescript-common/src/express/status"; import { NodeNotFoundError } from "./NestedSetModelQueryer"; import isUUID from "is-uuid"; import bcrypt from "bcrypt"; export interface ApiRouterOptions { database: Database; registryApiUrl: string; opaUrl: string; jwtSecret: string; tenantId: number; } /** * @apiDefine Auth Authorization API */ export default function createApiRouter(options: ApiRouterOptions) { const database = options.database; const orgQueryer = database.getOrgQueryer(); const router: express.Router = express.Router(); const status = { probes: { database: database.check.bind(database) } }; installStatusRouter(router, status); installStatusRouter(router, status, "/private"); installStatusRouter(router, status, "/public"); function respondWithError(route: string, res: express.Response, e: Error) { console.error(`Error happened when processed "${route}"`); console.error(e); if (e instanceof NodeNotFoundError) { res.status(404).json({ isError: true, errorCode: 404, errorMessage: e.message || "Could not find resource" }); } else if (e instanceof GenericError) { res.status(e.statusCode).json({ isError: true, errorCode: e.statusCode, errorMessage: e.message }); } else { res.status(500).json({ isError: true, errorCode: 500, errorMessage: "Internal server error" }); } } function handleMaybePromise<T>( res: express.Response, promise: Promise<Maybe<T>>, route: string, notFoundMessage: string = "Could not find resource" ) { return promise .then((resource) => resource.caseOf({ just: (resource) => res.json(resource), nothing: () => res.status(404).json({ isError: true, errorCode: 404, errorMessage: notFoundMessage }) }) ) .catch((e) => { respondWithError(route, res, e); }) .then(() => res.end()); } const MUST_BE_ADMIN = function (req: any, res: any, next: any) { //--- private API requires admin level access getUserIdHandling( req, res, options.jwtSecret, async (userId: string) => { try { const user = (await database.getUser(userId)).valueOrThrow( new AuthError( `Cannot locate user record by id: ${userId}`, 401 ) ); if (!user.isAdmin) throw new AuthError( "Only admin users are authorised to access this API", 403 ); req.user = { // the default session data type is UserToken // But any auth plugin provider could choose to customise the session by adding more fields // avoid losing customise session data here ...(req.user ? req.user : {}), ...user }; next(); } catch (e) { console.warn(e); if (e instanceof AuthError) res.status(e.statusCode).send(e.message); else res.status(401).send("Not authorized"); } } ); }; const NO_CACHE = function (req: any, res: any, next: any) { res.set({ "Cache-Control": "no-cache, no-store, must-revalidate", Pragma: "no-cache", Expires: "0" }); next(); }; /** * retrieve user info with api key id & api key * this api is only meant to be accessed internally (by gateway) * This route needs to run without MUST_BE_ADMIN middleware as it will authenticate request by APIkey itself */ router.get("/private/users/apikey/:apiKeyId", async function (req, res) { try { const apiKey = req.get("X-Magda-API-Key"); const apiKeyId = req.params.apiKeyId; if (!apiKeyId || !isUUID.anyNonNil(apiKeyId)) { // --- 400 Bad Request throw new GenericError( "Expect the last URL segment to be valid API key ID in uuid format", 400 ); } if (!apiKey) { // --- 400 Bad Request throw new GenericError( "X-Magda-API-Key header cannot be empty", 400 ); } const apiKeyRecord = await database.getUserApiKeyById(apiKeyId); const match = await bcrypt.compare(apiKey, apiKeyRecord.hash); if (match) { const user = ( await database.getUser(apiKeyRecord["user_id"]) ).valueOr(null); if (!user) { throw new GenericError("Unauthorized", 401); } res.json(user); res.status(200); } else { throw new GenericError("Unauthorized", 401); } } catch (e) { const error = e instanceof GenericError ? e : new GenericError("" + e); respondWithError("/private/users/apikey/:apiKeyId", res, error); } res.end(); }); router.all("/private/*", MUST_BE_ADMIN); router.get("/private/users/lookup", function (req, res) { const source = req.query.source as string; const sourceId = req.query.sourceId as string; handleMaybePromise( res, database.getUserByExternalDetails(source, sourceId), "/private/users/lookup" ); }); router.get("/private/users/:userId", function (req, res) { const userId = req.params.userId; handleMaybePromise( res, database.getUser(userId), "/private/users/:userId" ); }); router.post("/private/users", async function (req, res) { try { const user = await database.createUser(req.body); res.json(user); } catch (e) { respondWithError("/private/users", res, e); } }); /** * @apiGroup Auth * @api {post} /v0/auth/user/:userId/roles Add Roles to a user * @apiDescription Returns a list of current role ids of the user. * Required admin access. * * @apiSuccessExample {json} 200 * ["xxxx-xxxx-xxx-xxx-xx", "xx-xx-xxx-xxxx-xxxxx"] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.post("/public/user/:userId/roles", MUST_BE_ADMIN, async function ( req, res ) { try { const userId = req.params.userId; const roleIds = await database.addUserRoles(userId, req.body); res.json(roleIds); } catch (e) { respondWithError("POST /public/user/:userId/roles", res, e); } }); /** * @apiGroup Auth * @api {delete} /v0/auth/user/:userId/roles Remove a list roles from a user * @apiDescription Returns the JSON response indicates the operation has been done successfully or not * Required admin access. * * @apiSuccessExample {json} 200 * { * isError: false * } * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.delete("/public/user/:userId/roles", MUST_BE_ADMIN, async function ( req, res ) { try { const userId = req.params.userId; await database.deleteUserRoles(userId, req.body); res.json({ isError: false }); } catch (e) { respondWithError("DELETE /public/user/:userId/roles", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/user/:userId/roles Get all roles of a user * @apiDescription Returns an array of roles. When no roles can be found, an empty array will be returned * Required admin access. * * @apiSuccessExample {json} 200 * [{ * id: "xxx-xxx-xxxx-xxxx-xx", * name: "Admin Roles", * permissionIds: ["xxx-xxx-xxx-xxx-xx", "xxx-xx-xxx-xx-xxx-xx"], * description?: "This is an admin role" * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/user/:userId/roles", MUST_BE_ADMIN, async function ( req, res ) { try { const userId = req.params.userId; const roles = await database.getUserRoles(userId); res.json(roles); } catch (e) { respondWithError("GET /public/user/:userId/roles", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/user/:userId/permissions Get all permissions of a user * @apiDescription Returns an array of permissions. When no permissions can be found, an empty array will be returned. * Required admin access. * * @apiSuccessExample {json} 200 * [{ * id: "xxx-xxx-xxxx-xxxx-xx", * name: "View Datasets", * resourceId: "xxx-xxx-xxxx-xx", * resourceId: "object/dataset/draft", * userOwnershipConstraint: true, * orgUnitOwnershipConstraint: false, * preAuthorisedConstraint: false, * operations: [{ * id: "xxxxx-xxx-xxx-xxxx", * name: "Read Draft Dataset", * uri: "object/dataset/draft/read", * description: "xxxxxx" * }], * permissionIds: ["xxx-xxx-xxx-xxx-xx", "xxx-xx-xxx-xx-xxx-xx"], * description?: "This is an admin role", * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get( "/public/user/:userId/permissions", MUST_BE_ADMIN, async function (req, res) { try { const userId = req.params.userId; const permissions = await database.getUserPermissions(userId); res.json(permissions); } catch (e) { respondWithError( "GET /public/user/:userId/permissions", res, e ); } } ); /** * @apiGroup Auth * @api {get} /v0/auth/role/:roleId/permissions Get all permissions of a role * @apiDescription Returns an array of permissions. When no permissions can be found, an empty array will be returned. * Required admin access. * * @apiSuccessExample {json} 200 * [{ * id: "xxx-xxx-xxxx-xxxx-xx", * name: "View Datasets", * resourceId: "xxx-xxx-xxxx-xx", * resourceId: "object/dataset/draft", * userOwnershipConstraint: true, * orgUnitOwnershipConstraint: false, * preAuthorisedConstraint: false, * operations: [{ * id: "xxxxx-xxx-xxx-xxxx", * name: "Read Draft Dataset", * uri: "object/dataset/draft/read", * description: "xxxxxx" * }], * permissionIds: ["xxx-xxx-xxx-xxx-xx", "xxx-xx-xxx-xx-xxx-xx"], * description?: "This is an admin role", * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get( "/public/role/:roleId/permissions", MUST_BE_ADMIN, async function (req, res) { try { const roleId = req.params.roleId; const permissions = await database.getRolePermissions(roleId); res.json(permissions); } catch (e) { respondWithError( "GET /public/role/:roleId/permissions", res, e ); } } ); /** * @apiGroup Auth * @api {get} /v0/auth/users/whoami Get Current User Info (whoami) * @apiDescription Returns current user * * @apiSuccessExample {json} 200 * { * "id":"...", * "displayName":"Fred Nerk", * "email":"fred.nerk@data61.csiro.au", * "photoURL":"...", * "source":"google", * "isAdmin": true * } * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/users/whoami", NO_CACHE, async function (req, res) { try { const currentUserInfo = await database.getCurrentUserInfo( req, options.jwtSecret ); res.json(currentUserInfo); } catch (e) { if (e instanceof GenericError) { const data = e.toData(); res.status(data.errorCode).json(data); } else { respondWithError("/public/users/whoami", res, e); } } }); /** * @apiGroup Auth * @api {get} /v0/auth/users/all Get all users * @apiDescription Returns all users * * @apiSuccessExample {json} 200 * [{ * "id":"...", * "displayName":"Fred Nerk", * "email":"fred.nerk@data61.csiro.au", * "photoURL":"...", * "source":"google", * "isAdmin": true, * "roles": [{ * id": "...", * name: "Authenticated Users", * permissionIds: ["e5ce2fc4-9f38-4f52-8190-b770ed2074e", "a4a34ab4-67be-4806-a8de-f7e3c5d452f0"] * }] * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/users/all", MUST_BE_ADMIN, async (req, res) => { try { const users = await database.getUsers(); if (!users?.length) { res.json([]); return; } res.json( await Promise.all( users.map(async (user) => ({ ...user, roles: await database.getUserRoles(user.id) })) ) ); } catch (e) { respondWithError("GET /public/users/all", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/users/:userId Get User By Id * @apiDescription Returns user by id * * @apiParam {string} userId id of user * * @apiSuccessExample {json} 200 * { * "id":"...", * "displayName":"Fred Nerk", * "photoURL":"...", * "isAdmin": true * } * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/users/:userId", NO_CACHE, (req, res) => { const userId = req.params.userId; const getPublicUser = database.getUser(userId).then((userMaybe) => userMaybe.map((user) => { const publicUser: PublicUser = { id: user.id, photoURL: user.photoURL, displayName: user.displayName, isAdmin: user.isAdmin }; return publicUser; }) ); handleMaybePromise(res, getPublicUser, "/public/users/:userId"); }); /** * @apiGroup Auth * @api {put} /v0/auth/users/:userId Update User By Id * @apiDescription Updates a user's info by Id. * Supply a JSON object that contains fields to be udpated in body. * * @apiParam {string} userId id of user * @apiParamExample (Body) {json}: * { * displayName: "xxxx" * isAdmin: true * } * * @apiSuccessExample {json} 200 * { result: "SUCCESS" * } * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.put("/public/users/:userId", MUST_BE_ADMIN, async (req, res) => { const userId = req.params.userId; const update = req.body; // update try { await database.updateUser(userId, update); res.status(200).json({ result: "SUCCESS" }); } catch (e) { respondWithError("/public/users/:userId", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits/bylevel/:orgLevel List OrgUnits at certain org tree level * @apiDescription * List all OrgUnits at certain org tree level * Optionally provide a test Org Unit Id that will be used to * test the relationship with each of returned orgUnit item. * Possible Value: 'ancestor', 'descendant', 'equal', 'unrelated' * * @apiParam (Path) {string} orgLevel The level number (starts from 1) where org Units of the tree are taken horizontally. * @apiParam (Query) {string} relationshipOrgUnitId Optional; The org unit id that is used to test the relationship with each of returned orgUnit item. * * @apiSuccessExample {string} 200 * [{ * "id": "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7", * "name": "node 1", * "description": "xxxxxxxx", * "relationship": "unrelated" * },{ * "id": "e5f0ed5f-bb00-4e49-89a6-3f044aecc3f7", * "name": "node 2", * "description": "xxxxxxxx", * "relationship": "ancestor" * }] * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/orgunits/bylevel/:orgLevel", async (req, res) => { try { const orgLevel = req.params.orgLevel; const relationshipOrgUnitId = req.query .relationshipOrgUnitId as string; const levelNumber = parseInt(orgLevel); if (levelNumber < 1 || isNaN(levelNumber)) throw new Error(`Invalid level number: ${orgLevel}.`); const nodes = await orgQueryer.getAllNodesAtLevel(levelNumber); if (relationshipOrgUnitId && nodes.length) { for (let i = 0; i < nodes.length; i++) { const r = await orgQueryer.compareNodes( nodes[i]["id"], relationshipOrgUnitId ); nodes[i]["relationship"] = r; } } res.status(200).json(nodes); } catch (e) { respondWithError("GET /public/orgunits/bylevel/:orgLevel", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits Get orgunits by name * @apiDescription * Gets org units matching a name * Optionally provide a test Org Unit Id that will be used to * test the relationship with each of returned orgUnit item. * Possible Value: 'ancestor', 'descendant', 'equal', 'unrelated' * * @apiParam (query) {string} nodeName the name of the org unit to look up * @apiParam (query) {boolean} leafNodesOnly Whether only leaf nodes should be returned * @apiParam (Query) {string} relationshipOrgUnitId Optional; The org unit id that is used to test the relationship with each of returned orgUnit item. * * @apiSuccessExample {json} 200 * [{ * "id": "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7", * "name": "other-team", * "description": "The other teams", * "relationship": "unrelated" * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/orgunits", async (req, res) => { try { const nodeName: string = req.query.nodeName as string; const leafNodesOnly: string = req.query.leafNodesOnly as string; const relationshipOrgUnitId = req.query .relationshipOrgUnitId as string; const nodes = await orgQueryer.getNodes({ name: nodeName, leafNodesOnly: leafNodesOnly === "true" }); if (relationshipOrgUnitId && nodes.length) { for (let i = 0; i < nodes.length; i++) { const r = await orgQueryer.compareNodes( nodes[i]["id"], relationshipOrgUnitId ); nodes[i]["relationship"] = r; } } res.status(200).json(nodes); } catch (e) { respondWithError("/public/orgunits", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits/root Get root organisation * @apiDescription Gets the root organisation unit (top of the tree). * * @apiSuccessExample {json} 200 * { * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * } * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/orgunits/root", async (req, res) => { handleMaybePromise( res, orgQueryer.getRootNode(), "GET /public/orgunits/root", "Cannot locate the root tree node." ); }); /** * @apiGroup Auth * @api {post} /v0/auth/orgunits/root Create root organisation * @apiDescription Creates the root organisation unit (top of the tree). * * @apiParamExample (Body) {json}: * { * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * } * * @apiSuccessExample {string} 200 * { * "nodeId": "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * } * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.post("/public/orgunits/root", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = await orgQueryer.createRootNode(req.body); res.status(200).json({ nodeId: nodeId }); } catch (e) { respondWithError("POST /public/orgunits/root", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits/:nodeId Get details for a node * @apiDescription Gets the details of the node with this id. * * @apiParam {string} nodeId id of the node to query * * @apiSuccessExample {json} 200 * { * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * } * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get("/public/orgunits/:nodeId", async (req, res) => { const nodeId = req.params.nodeId; handleMaybePromise( res, orgQueryer.getNodeById(nodeId), "GET /public/orgunits/:nodeId", `Could not find org unit with id ${nodeId}` ); }); /** * @apiGroup Auth * @api {put} /v0/auth/orgunits/:nodeId Set details for a node * @apiDescription Creates/updates a node at the specified id * * @apiParam (Path) {string} nodeId id of the node to query * @apiParamExample (Body) {json}: * { * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * } * * @apiSuccessExample {string} 200 * { * "nodeId": "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * } * * @apiErrorExample {json} 401/404/500 * { * "isError": true, * "errorCode": 401, //--- or 404, 500 depends on error type * "errorMessage": "Not authorized" * } */ router.put("/public/orgunits/:nodeId", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; const existingNodeMaybe = await orgQueryer.getNodeById(nodeId); existingNodeMaybe.caseOf({ just: async () => { await orgQueryer.updateNode(nodeId, req.body); res.status(200).json({ nodeId: nodeId }); }, nothing: async () => { const newNodeId = await orgQueryer.insertNode( nodeId, req.body ); res.status(200).json({ nodeId: newNodeId }); } }); } catch (e) { respondWithError("PUT /public/orgunits/:nodeId", res, e); } }); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits/:nodeId/children/immediate Get immediate children for a node * @apiDescription Gets all the children immediately below the requested node. If the node doesn't exist, returns an empty list. * * @apiParam {string} nodeId id of the node to query * * @apiSuccessExample {json} 200 * [{ * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get( "/public/orgunits/:nodeId/children/immediate", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; const nodes = await orgQueryer.getImmediateChildren(nodeId); res.status(200).json(nodes); } catch (e) { respondWithError( "/public/orgunits/:nodeId/children/immediate", res, e ); } } ); /** * @apiGroup Auth * @api {get} /v0/auth/orgunits/:nodeId/children/all Get all children for a node * @apiDescription Gets all the children below the requested node recursively. If node doesn't exist, returns an empty list. * * @apiParam {string} nodeId id of the node to query * * @apiSuccessExample {json} 200 * [{ * id: "e5f0ed5f-aa97-4e49-89a6-3f044aecc3f7" * name: "other-team" * description: "The other teams" * }] * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.get( "/public/orgunits/:nodeId/children/all", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; const nodes = await orgQueryer.getAllChildren(nodeId); res.status(200).json(nodes); } catch (e) { respondWithError( "/public/orgunits/:nodeId/children/all", res, e ); } } ); /** * @apiGroup Auth * @api {delete} /v0/auth/orgunits/:nodeId/subtree Delete subtree * @apiDescription Deletes a node and all its children. Will delete the root node if that is the one specified in nodeId. * * @apiParam {string} nodeId id of the node to delete * * @apiSuccessExample {json} 200 * { * "result": "SUCCESS" * } * * @apiErrorExample {json} 401/500 * { * "isError": true, * "errorCode": 401, //--- or 500 depends on error type * "errorMessage": "Not authorized" * } */ router.delete( "/public/orgunits/:nodeId/subtree", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; await orgQueryer.deleteSubTree(nodeId, true); res.status(200).json({ result: "SUCCESS" }); } catch (e) { respondWithError("/public/orgunits/:nodeId/subtree", res, e); } } ); router.delete( "/public/orgunits/:nodeId", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; await orgQueryer.deleteNode(nodeId); res.status(200).json(true); } catch (e) { respondWithError("DELETE /public/orgunits/:nodeId", res, e); } } ); router.put( "/public/orgunits/:nodeId/move/:newParentId", MUST_BE_ADMIN, async (req, res) => { try { const nodeId = req.params.nodeId; const newParentId = req.params.newParentId; await orgQueryer.moveSubTreeTo(nodeId, newParentId); res.status(200).json(true); } catch (e) { res.status(500).send(`Error: ${e}`); } } ); // This is for getting a JWT in development so you can do fake authenticated requests to a local server. if (process.env.NODE_ENV !== "production") { router.get("public/jwt", function (req, res) { res.status(200); res.write("X-Magda-Session: " + req.header("X-Magda-Session")); res.send(); }); } return router; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type CollectionTestsQueryVariables = {}; export type CollectionTestsQueryResponse = { readonly marketingCollection: { readonly " $fragmentRefs": FragmentRefs<"Collection_collection">; } | null; }; export type CollectionTestsQuery = { readonly response: CollectionTestsQueryResponse; readonly variables: CollectionTestsQueryVariables; }; /* query CollectionTestsQuery { marketingCollection(slug: "doesn't matter") { ...Collection_collection id } } fragment Collection_collection on MarketingCollection { id slug ...CollectionHeader_collection ...CollectionArtworks_collection ...FeaturedArtists_collection } fragment CollectionHeader_collection on MarketingCollection { title headerImage descriptionMarkdown image: artworksConnection(sort: "-decayed_merch", first: 1) { edges { node { image { url(version: "larger") } id } } id } } fragment CollectionArtworks_collection on MarketingCollection { slug id collectionArtworks: artworksConnection(sort: "-decayed_merch", first: 6) { edges { node { id __typename } cursor } ...InfiniteScrollArtworksGrid_connection pageInfo { endCursor hasNextPage } id } } fragment FeaturedArtists_collection on MarketingCollection { artworksConnection(aggregations: [MERCHANDISABLE_ARTISTS], size: 0, sort: "-decayed_merch") { merchandisableArtists(size: 9) { internalID ...ArtistListItem_artist id } id } query { artistIDs id } featuredArtistExclusionIds } fragment ArtistListItem_artist on Artist { id internalID slug name initials href is_followed: isFollowed nationality birthday deathday image { url } } fragment InfiniteScrollArtworksGrid_connection on ArtworkConnectionInterface { pageInfo { hasNextPage startCursor endCursor } edges { __typename node { slug id image { aspectRatio } ...ArtworkGridItem_artwork } ... on Node { id } } } fragment ArtworkGridItem_artwork on Artwork { title date sale_message: saleMessage is_biddable: isBiddable is_acquireable: isAcquireable is_offerable: isOfferable slug sale { is_auction: isAuction is_closed: isClosed display_timely_at: displayTimelyAt id } sale_artwork: saleArtwork { current_bid: currentBid { display } id } image { url(version: "large") aspect_ratio: aspectRatio } artists(shallow: true) { name id } partner { name id } href } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "slug", "value": "doesn't matter" } ], v1 = { "kind": "ScalarField", "alias": null, "name": "id", "args": null, "storageKey": null }, v2 = { "kind": "ScalarField", "alias": null, "name": "slug", "args": null, "storageKey": null }, v3 = { "kind": "ScalarField", "alias": null, "name": "title", "args": null, "storageKey": null }, v4 = { "kind": "Literal", "name": "sort", "value": "-decayed_merch" }, v5 = [ { "kind": "Literal", "name": "first", "value": 6 }, (v4/*: any*/) ], v6 = { "kind": "ScalarField", "alias": null, "name": "name", "args": null, "storageKey": null }, v7 = [ (v6/*: any*/), (v1/*: any*/) ], v8 = { "kind": "ScalarField", "alias": null, "name": "href", "args": null, "storageKey": null }, v9 = { "type": "ID", "enumValues": null, "plural": false, "nullable": false }, v10 = { "type": "String", "enumValues": null, "plural": false, "nullable": false }, v11 = { "type": "String", "enumValues": null, "plural": false, "nullable": true }, v12 = { "type": "FilterArtworksConnection", "enumValues": null, "plural": false, "nullable": true }, v13 = { "type": "String", "enumValues": null, "plural": true, "nullable": true }, v14 = { "type": "ID", "enumValues": null, "plural": false, "nullable": true }, v15 = { "type": "Artist", "enumValues": null, "plural": true, "nullable": true }, v16 = { "type": "Artwork", "enumValues": null, "plural": false, "nullable": true }, v17 = { "type": "Image", "enumValues": null, "plural": false, "nullable": true }, v18 = { "type": "Boolean", "enumValues": null, "plural": false, "nullable": true }, v19 = { "type": "Float", "enumValues": null, "plural": false, "nullable": false }; return { "kind": "Request", "fragment": { "kind": "Fragment", "name": "CollectionTestsQuery", "type": "Query", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "marketingCollection", "storageKey": "marketingCollection(slug:\"doesn't matter\")", "args": (v0/*: any*/), "concreteType": "MarketingCollection", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "Collection_collection", "args": null } ] } ] }, "operation": { "kind": "Operation", "name": "CollectionTestsQuery", "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "marketingCollection", "storageKey": "marketingCollection(slug:\"doesn't matter\")", "args": (v0/*: any*/), "concreteType": "MarketingCollection", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), (v3/*: any*/), { "kind": "ScalarField", "alias": null, "name": "headerImage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "descriptionMarkdown", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": "image", "name": "artworksConnection", "storageKey": "artworksConnection(first:1,sort:\"-decayed_merch\")", "args": [ { "kind": "Literal", "name": "first", "value": 1 }, (v4/*: any*/) ], "concreteType": "FilterArtworksConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "FilterArtworksEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Artwork", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "url", "args": [ { "kind": "Literal", "name": "version", "value": "larger" } ], "storageKey": "url(version:\"larger\")" } ] }, (v1/*: any*/) ] } ] }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": "collectionArtworks", "name": "artworksConnection", "storageKey": "artworksConnection(first:6,sort:\"-decayed_merch\")", "args": (v5/*: any*/), "concreteType": "FilterArtworksConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "edges", "storageKey": null, "args": null, "concreteType": "FilterArtworksEdge", "plural": true, "selections": [ { "kind": "LinkedField", "alias": null, "name": "node", "storageKey": null, "args": null, "concreteType": "Artwork", "plural": false, "selections": [ (v1/*: any*/), (v2/*: any*/), { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "aspectRatio", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "url", "args": [ { "kind": "Literal", "name": "version", "value": "large" } ], "storageKey": "url(version:\"large\")" }, { "kind": "ScalarField", "alias": "aspect_ratio", "name": "aspectRatio", "args": null, "storageKey": null } ] }, (v3/*: any*/), { "kind": "ScalarField", "alias": null, "name": "date", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "sale_message", "name": "saleMessage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_biddable", "name": "isBiddable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_acquireable", "name": "isAcquireable", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_offerable", "name": "isOfferable", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "sale", "storageKey": null, "args": null, "concreteType": "Sale", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "is_auction", "name": "isAuction", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "is_closed", "name": "isClosed", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "display_timely_at", "name": "displayTimelyAt", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": "sale_artwork", "name": "saleArtwork", "storageKey": null, "args": null, "concreteType": "SaleArtwork", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "current_bid", "name": "currentBid", "storageKey": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "display", "args": null, "storageKey": null } ] }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "artists", "storageKey": "artists(shallow:true)", "args": [ { "kind": "Literal", "name": "shallow", "value": true } ], "concreteType": "Artist", "plural": true, "selections": (v7/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "partner", "storageKey": null, "args": null, "concreteType": "Partner", "plural": false, "selections": (v7/*: any*/) }, (v8/*: any*/), { "kind": "ScalarField", "alias": null, "name": "__typename", "args": null, "storageKey": null } ] }, { "kind": "ScalarField", "alias": null, "name": "cursor", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "pageInfo", "storageKey": null, "args": null, "concreteType": "PageInfo", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "hasNextPage", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "startCursor", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endCursor", "args": null, "storageKey": null } ] }, (v1/*: any*/) ] }, { "kind": "LinkedHandle", "alias": "collectionArtworks", "name": "artworksConnection", "args": (v5/*: any*/), "handle": "connection", "key": "Collection_collectionArtworks", "filters": [ "sort" ] }, { "kind": "LinkedField", "alias": null, "name": "artworksConnection", "storageKey": "artworksConnection(aggregations:[\"MERCHANDISABLE_ARTISTS\"],size:0,sort:\"-decayed_merch\")", "args": [ { "kind": "Literal", "name": "aggregations", "value": [ "MERCHANDISABLE_ARTISTS" ] }, { "kind": "Literal", "name": "size", "value": 0 }, (v4/*: any*/) ], "concreteType": "FilterArtworksConnection", "plural": false, "selections": [ { "kind": "LinkedField", "alias": null, "name": "merchandisableArtists", "storageKey": "merchandisableArtists(size:9)", "args": [ { "kind": "Literal", "name": "size", "value": 9 } ], "concreteType": "Artist", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "internalID", "args": null, "storageKey": null }, (v1/*: any*/), (v2/*: any*/), (v6/*: any*/), { "kind": "ScalarField", "alias": null, "name": "initials", "args": null, "storageKey": null }, (v8/*: any*/), { "kind": "ScalarField", "alias": "is_followed", "name": "isFollowed", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "nationality", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "birthday", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "deathday", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "url", "args": null, "storageKey": null } ] } ] }, (v1/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "query", "storageKey": null, "args": null, "concreteType": "MarketingCollectionQuery", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "artistIDs", "args": null, "storageKey": null }, (v1/*: any*/) ] }, { "kind": "ScalarField", "alias": null, "name": "featuredArtistExclusionIds", "args": null, "storageKey": null } ] } ] }, "params": { "operationKind": "query", "name": "CollectionTestsQuery", "id": "bc3659ca34d0a3d9e4807e2294e185e2", "text": null, "metadata": { "relayTestingSelectionTypeInfo": { "marketingCollection": { "type": "MarketingCollection", "enumValues": null, "plural": false, "nullable": true }, "marketingCollection.id": (v9/*: any*/), "marketingCollection.slug": (v10/*: any*/), "marketingCollection.title": (v10/*: any*/), "marketingCollection.headerImage": (v11/*: any*/), "marketingCollection.descriptionMarkdown": (v11/*: any*/), "marketingCollection.image": (v12/*: any*/), "marketingCollection.collectionArtworks": (v12/*: any*/), "marketingCollection.artworksConnection": (v12/*: any*/), "marketingCollection.query": { "type": "MarketingCollectionQuery", "enumValues": null, "plural": false, "nullable": false }, "marketingCollection.featuredArtistExclusionIds": (v13/*: any*/), "marketingCollection.image.edges": { "type": "FilterArtworksEdge", "enumValues": null, "plural": true, "nullable": true }, "marketingCollection.image.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges": { "type": "ArtworkEdgeInterface", "enumValues": null, "plural": true, "nullable": true }, "marketingCollection.collectionArtworks.pageInfo": { "type": "PageInfo", "enumValues": null, "plural": false, "nullable": false }, "marketingCollection.collectionArtworks.id": (v14/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists": (v15/*: any*/), "marketingCollection.artworksConnection.id": (v14/*: any*/), "marketingCollection.query.artistIDs": (v13/*: any*/), "marketingCollection.query.id": (v14/*: any*/), "marketingCollection.image.edges.node": (v16/*: any*/), "marketingCollection.collectionArtworks.edges.node": (v16/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.internalID": (v9/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.id": (v9/*: any*/), "marketingCollection.image.edges.node.image": (v17/*: any*/), "marketingCollection.image.edges.node.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges.node.id": (v9/*: any*/), "marketingCollection.collectionArtworks.edges.cursor": (v10/*: any*/), "marketingCollection.collectionArtworks.pageInfo.hasNextPage": { "type": "Boolean", "enumValues": null, "plural": false, "nullable": false }, "marketingCollection.collectionArtworks.pageInfo.startCursor": (v11/*: any*/), "marketingCollection.collectionArtworks.pageInfo.endCursor": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.slug": (v9/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.name": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.initials": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.href": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.is_followed": (v18/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.nationality": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.birthday": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.deathday": (v11/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.image": (v17/*: any*/), "marketingCollection.image.edges.node.image.url": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.__typename": (v10/*: any*/), "marketingCollection.collectionArtworks.edges.node.slug": (v9/*: any*/), "marketingCollection.collectionArtworks.edges.node.image": (v17/*: any*/), "marketingCollection.collectionArtworks.edges.id": (v14/*: any*/), "marketingCollection.artworksConnection.merchandisableArtists.image.url": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.image.aspectRatio": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.node.title": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.date": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale_message": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.is_biddable": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.is_acquireable": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.is_offerable": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale": { "type": "Sale", "enumValues": null, "plural": false, "nullable": true }, "marketingCollection.collectionArtworks.edges.node.sale_artwork": { "type": "SaleArtwork", "enumValues": null, "plural": false, "nullable": true }, "marketingCollection.collectionArtworks.edges.node.artists": (v15/*: any*/), "marketingCollection.collectionArtworks.edges.node.partner": { "type": "Partner", "enumValues": null, "plural": false, "nullable": true }, "marketingCollection.collectionArtworks.edges.node.href": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.is_auction": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.is_closed": (v18/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.display_timely_at": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale_artwork.current_bid": { "type": "SaleArtworkCurrentBid", "enumValues": null, "plural": false, "nullable": true }, "marketingCollection.collectionArtworks.edges.node.sale_artwork.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges.node.image.url": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.image.aspect_ratio": (v19/*: any*/), "marketingCollection.collectionArtworks.edges.node.artists.name": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.artists.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges.node.partner.name": (v11/*: any*/), "marketingCollection.collectionArtworks.edges.node.partner.id": (v14/*: any*/), "marketingCollection.collectionArtworks.edges.node.sale_artwork.current_bid.display": (v11/*: any*/) } } } }; })(); (node as any).hash = 'fbe5831179fb6d1e2f66b7360c128d63'; export default node;
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormProperty { interface tab_dynamic_property_properties_Sections { dynamic_property_properties_2: DevKit.Controls.Section; dynamic_property_properties_3: DevKit.Controls.Section; dynamic_property_properties_41: DevKit.Controls.Section; } interface tab_dynamic_property_summary_Sections { dynamic_property_properties_1: DevKit.Controls.Section; dynamic_property_properties_31: DevKit.Controls.Section; } interface tab_dynamic_property_properties extends DevKit.Controls.ITab { Section: tab_dynamic_property_properties_Sections; } interface tab_dynamic_property_summary extends DevKit.Controls.ITab { Section: tab_dynamic_property_summary_Sections; } interface Tabs { dynamic_property_properties: tab_dynamic_property_properties; dynamic_property_summary: tab_dynamic_property_summary; } interface Body { Tab: Tabs; /** Select the data type of the property. */ DataType: DevKit.Controls.OptionSet; /** Shows the default value of the property for a decimal data type. */ DefaultValueDecimal: DevKit.Controls.Decimal; /** Shows the default value of the property for a double data type. */ DefaultValueDouble: DevKit.Controls.Double; /** Shows the default value of the property for a whole number data type. */ DefaultValueInteger: DevKit.Controls.Integer; /** Shows the default value of the property. */ DefaultValueOptionSet: DevKit.Controls.Lookup; /** Shows the default value of the property for a string data type. */ DefaultValueString: DevKit.Controls.String; /** Type a description for the property. */ Description: DevKit.Controls.String; /** Defines whether the attribute is hidden or shown. */ IsHidden: DevKit.Controls.Boolean; /** Defines whether the attribute is read-only or if it can be edited. */ IsReadOnly: DevKit.Controls.Boolean; /** Defines whether the attribute is mandatory. */ IsRequired: DevKit.Controls.Boolean; /** Shows the maximum allowed length of the property for a string data type. */ MaxLengthString: DevKit.Controls.Integer; /** Shows the maximum allowed value of the property for a decimal data type. */ MaxValueDecimal: DevKit.Controls.Decimal; /** Shows the maximum allowed value of the property for a double data type. */ MaxValueDouble: DevKit.Controls.Double; /** Shows the maximum allowed value of the property for a whole number data type. */ MaxValueInteger: DevKit.Controls.Integer; /** Shows the minimum allowed value of the property for a decimal data type. */ MinValueDecimal: DevKit.Controls.Decimal; /** Shows the minimum allowed value of the property for a double data type. */ MinValueDouble: DevKit.Controls.Double; /** Shows the minimum allowed value of the property for a whole number data type. */ MinValueInteger: DevKit.Controls.Integer; /** Type the name of the property. */ Name: DevKit.Controls.String; /** Shows the allowed precision of the property for a whole number data type. */ Precision: DevKit.Controls.Integer; /** Choose the product that the property is associated with. */ RegardingObjectId: DevKit.Controls.Lookup; } interface Grid { grid_DynamicPropertyOptionSetItem: DevKit.Controls.Grid; } } class FormProperty extends DevKit.IForm { /** * DynamicsCrm.DevKit form Property * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Property */ Body: DevKit.FormProperty.Body; /** The Grid of form Property */ Grid: DevKit.FormProperty.Grid; } namespace FormProperty_Quick_Create { interface tab_dynamic_property_summary_Sections { dynamic_property_properties_1: DevKit.Controls.Section; } interface tab_dynamic_property_summary extends DevKit.Controls.ITab { Section: tab_dynamic_property_summary_Sections; } interface Tabs { dynamic_property_summary: tab_dynamic_property_summary; } interface Body { Tab: Tabs; /** Select the data type of the property. */ DataType: DevKit.Controls.OptionSet; /** Shows the default value of the property for a decimal data type. */ DefaultValueDecimal: DevKit.Controls.Decimal; /** Shows the default value of the property for a double data type. */ DefaultValueDouble: DevKit.Controls.Double; /** Shows the default value of the property for a whole number data type. */ DefaultValueInteger: DevKit.Controls.Integer; /** Shows the default value of the property. */ DefaultValueOptionSet: DevKit.Controls.Lookup; /** Shows the default value of the property for a string data type. */ DefaultValueString: DevKit.Controls.String; /** Type a description for the property. */ Description: DevKit.Controls.String; /** Defines whether the attribute is hidden or shown. */ IsHidden: DevKit.Controls.Boolean; /** Defines whether the attribute is read-only or if it can be edited. */ IsReadOnly: DevKit.Controls.Boolean; /** Defines whether the attribute is mandatory. */ IsRequired: DevKit.Controls.Boolean; /** Shows the maximum allowed length of the property for a string data type. */ MaxLengthString: DevKit.Controls.Integer; /** Shows the maximum allowed value of the property for a decimal data type. */ MaxValueDecimal: DevKit.Controls.Decimal; /** Shows the maximum allowed value of the property for a double data type. */ MaxValueDouble: DevKit.Controls.Double; /** Shows the maximum allowed value of the property for a whole number data type. */ MaxValueInteger: DevKit.Controls.Integer; /** Shows the minimum allowed value of the property for a decimal data type. */ MinValueDecimal: DevKit.Controls.Decimal; /** Shows the minimum allowed value of the property for a double data type. */ MinValueDouble: DevKit.Controls.Double; /** Shows the minimum allowed value of the property for a whole number data type. */ MinValueInteger: DevKit.Controls.Integer; /** Type the name of the property. */ Name: DevKit.Controls.String; /** Shows the allowed precision of the property for a whole number data type. */ Precision: DevKit.Controls.Integer; /** Choose the product that the property is associated with. */ RegardingObjectId: DevKit.Controls.Lookup; } } class FormProperty_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form Property_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Property_Quick_Create */ Body: DevKit.FormProperty_Quick_Create.Body; } class DynamicPropertyApi { /** * DynamicsCrm.DevKit DynamicPropertyApi * @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; /** Shows the property in the product family that this property is being inherited from. */ BaseDynamicPropertyId: DevKit.WebApi.LookupValue; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Select the data type of the property. */ DataType: DevKit.WebApi.OptionSetValue; /** Default Value */ DefaultAttributeValue: DevKit.WebApi.StringValue; /** Shows the default value of the property for a decimal data type. */ DefaultValueDecimal: DevKit.WebApi.DecimalValue; /** Shows the default value of the property for a double data type. */ DefaultValueDouble: DevKit.WebApi.DoubleValue; /** Shows the default value of the property for a whole number data type. */ DefaultValueInteger: DevKit.WebApi.IntegerValue; /** Shows the default value of the property. */ DefaultValueOptionSet: DevKit.WebApi.LookupValue; /** Shows the default value of the property for a string data type. */ DefaultValueString: DevKit.WebApi.StringValue; /** Type a description for the property. */ Description: DevKit.WebApi.StringValue; /** Internal Use Only */ DMTImportState: DevKit.WebApi.IntegerValue; /** Shows the unique identifier of the property. */ DynamicPropertyId: DevKit.WebApi.GuidValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Defines whether the attribute is hidden or shown. */ IsHidden: DevKit.WebApi.BooleanValue; /** Defines whether the attribute is read-only or if it can be edited. */ IsReadOnly: DevKit.WebApi.BooleanValue; /** Defines whether the attribute is mandatory. */ IsRequired: DevKit.WebApi.BooleanValue; /** Shows the maximum allowed length of the property for a string data type. */ MaxLengthString: DevKit.WebApi.IntegerValue; /** Shows the maximum allowed value of the property for a decimal data type. */ MaxValueDecimal: DevKit.WebApi.DecimalValue; /** Shows the maximum allowed value of the property for a double data type. */ MaxValueDouble: DevKit.WebApi.DoubleValue; /** Shows the maximum allowed value of the property for a whole number data type. */ MaxValueInteger: DevKit.WebApi.IntegerValue; /** Shows the minimum allowed value of the property for a decimal data type. */ MinValueDecimal: DevKit.WebApi.DecimalValue; /** Shows the minimum allowed value of the property for a double data type. */ MinValueDouble: DevKit.WebApi.DoubleValue; /** Shows the minimum allowed value of the property for a whole number data type. */ MinValueInteger: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the name of the property. */ Name: DevKit.WebApi.StringValue; /** Unique identifier for the organization */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the related overwritten property. */ OverwrittenDynamicPropertyId: DevKit.WebApi.GuidValue; /** Shows the allowed precision of the property for a whole number data type. */ Precision: DevKit.WebApi.IntegerValue; /** Choose the product that the property is associated with. */ RegardingObjectId: DevKit.WebApi.LookupValue; /** Shows the root property that this property is derived from. */ RootDynamicPropertyId: DevKit.WebApi.GuidValue; /** Shows the state of the property. */ statecode: DevKit.WebApi.OptionSetValue; /** Shows whether the property is active or inactive. */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace DynamicProperty { enum DataType { /** 1 */ Decimal, /** 2 */ Floating_Point_Number, /** 0 */ Option_Set, /** 3 */ Single_Line_Of_Text, /** 4 */ Whole_Number } enum statecode { /** 0 */ Active, /** 1 */ Draft, /** 2 */ Retired } enum statuscode { /** 1 */ Active, /** 0 */ Draft, /** 2 */ Retired } 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':['Property','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { find, head } from 'ramda'; import { commands, Disposable, TextEditor, window, Selection, Position, } from 'vscode'; import { AreaIndexFinder } from './area-index-finder'; import { Config } from './config/config'; import { asyncDebounce } from './debounce'; import { InlineInput } from './inline-input'; import { JumpAreaFinder } from './jump-area-finder'; import { CancelReason } from './models/cancel-reason'; import { JumpKind } from './models/jump-kind'; import { JumpResult } from './models/jump-result'; import { LineIndexes } from './models/line-indexes'; import { Placeholder } from './models/placeholder'; import { PlaceHolderCalculus } from './placeholder-calculus'; import { PlaceHolderDecorator } from './placeholder-decorator'; const findPlaceholder = (char: string) => find<Placeholder>(plc => plc.placeholder === char.toLowerCase()); export class Jumper { public isJumping = false; private config: Config; private placeholderCalculus = new PlaceHolderCalculus(); private placeHolderDecorator = new PlaceHolderDecorator(); private jumpAreaFinder = new JumpAreaFinder(); private areaIndexFinder = new AreaIndexFinder(); private input: InlineInput; private isInSelectionMode: boolean; public jump( jumpKind: JumpKind, isInSelectionMode: boolean, ): Promise<JumpResult> { this.isInSelectionMode = isInSelectionMode; if (!!this.isJumping) { this.setMessage('Canceled', 2000); return Promise.reject(new Error('Jumping in progress')); } this.isJumping = true; return new Promise<JumpResult>(async (resolve, reject) => { const editor = window.activeTextEditor; if (!editor) { reject(new Error('No active editor')); this.isJumping = false; return; } const messaggeDisposable = this.setMessage('Type', 5000); try { const placeholder = await this.askForInitialChar(jumpKind, editor); this.setMessage('Jumped!', 2000); messaggeDisposable.dispose(); if (this.isInSelectionMode) { const isBackwardJump = editor.selection.active.line > placeholder.line || editor.selection.active.character > placeholder.character; const offset = isBackwardJump || !this.config.finder.includeEndCharInSelection ? 0 : 1; editor.selection = new Selection( new Position( editor.selection.active.line, editor.selection.active.character, ), new Position(placeholder.line, placeholder.character + offset), ); } else { editor.selection = new Selection( new Position(placeholder.line, placeholder.character), new Position(placeholder.line, placeholder.character), ); } await this.scrollToLine(placeholder.line); this.isJumping = false; resolve({ editor, placeholder }); } catch (error) { messaggeDisposable.dispose(); this.isJumping = false; if (error instanceof Error) { this.setMessage('Canceled', 2000); reject(error); } else { const message = this.buildMessage(error); this.setMessage(message, 2000); reject(new Error(message)); } } }); } public jumpToLine(isInSelectionMode: boolean | null): Promise<JumpResult> { if (isInSelectionMode !== null) { // if null, reuse the selectionMode from last call this.isInSelectionMode = isInSelectionMode; } if (!!this.input) { // we cancel any open InlineInput (e.g. from an interrupted call to jump()) this.input.cancel(); } this.isJumping = true; return new Promise<JumpResult>(async (resolve, reject) => { const editor = window.activeTextEditor; if (!editor) { reject(new Error('No active editor')); this.isJumping = false; return; } try { const placeholder = await this.buildPlaceholdersForLines(editor); this.setMessage('Jumped!', 2000); if (this.isInSelectionMode) { editor.selection = new Selection( new Position( editor.selection.active.line, editor.selection.active.character, ), new Position(placeholder.line, placeholder.character), ); } else { editor.selection = new Selection( new Position(placeholder.line, placeholder.character), new Position(placeholder.line, placeholder.character), ); } await this.scrollToLine(placeholder.line); this.isJumping = false; resolve({ editor, placeholder }); } catch (error) { this.isJumping = false; if (error instanceof Error) { this.setMessage('Canceled', 2000); reject(error); } else { const message = this.buildMessage(error); this.setMessage(message, 2000); reject(new Error(message)); } } }); } public refreshConfig(config: Config) { this.config = config; this.placeholderCalculus.refreshConfig(config); this.placeHolderDecorator.refreshConfig(config); this.jumpAreaFinder.refreshConfig(config); this.areaIndexFinder.refreshConfig(config); } public scrollToLine = async (line: number) => { switch (this.config.scroll.mode) { case 'center': await commands.executeCommand('revealLine', { lineNumber: line, at: 'center', }); break; case 'top': await commands.executeCommand('revealLine', { lineNumber: line, at: 'top', }); break; default: break; } }; private askForInitialChar(jumpKind: JumpKind, editor: TextEditor) { return new Promise<Placeholder>(async (resolve, reject) => { try { this.input = new InlineInput(); let char = await this.input.show(); if (!char) { reject(CancelReason.EmptyValue); return; } if (char && char.length > 1) { char = char.substring(0, 1); } const result = await this.buildPlaceholdersForChar( editor, char, jumpKind, ); resolve(result); } catch (error) { reject(error); } }); } private buildPlaceholdersForChar( editor: TextEditor, char: string, jumpKind: JumpKind, ) { return new Promise<Placeholder>(async (resolve, reject) => { try { const area = this.jumpAreaFinder.findArea(editor); const lineIndexes = this.areaIndexFinder.findByChar(editor, area, char); if (lineIndexes.count <= 0) { reject(CancelReason.NoMatches); return; } let placeholders: Placeholder[] = this.placeholderCalculus.buildPlaceholders( lineIndexes, ); if (placeholders.length === 0) { reject(CancelReason.NoMatches); return; } if (placeholders.length === 1) { const placeholder = head(placeholders); resolve(placeholder); } else { try { if (jumpKind === JumpKind.MultiChar) { placeholders = await this.recursivelyRestrict( editor, placeholders, lineIndexes, ); } if (placeholders.length > 1) { const jumpedPlaceholder = await this.recursivelyJumpTo( editor, placeholders, ); resolve(jumpedPlaceholder); } else { resolve(head(placeholders)); } } catch (error) { // let's try to recalculate placeholders if we change visible range if (error === CancelReason.ChangedVisibleRanges) { const debounced = await asyncDebounce(async () => { try { const placeholder = await this.buildPlaceholdersForChar( editor, char, jumpKind, ); resolve(placeholder); } catch (error) { reject(error); } }, 500); await debounced(); } else { reject(error); } } } } catch (error) { reject(error); } }); } private buildPlaceholdersForLines(editor: TextEditor) { return new Promise<Placeholder>(async (resolve, reject) => { const area = this.jumpAreaFinder.findArea(editor); const lineIndexes = this.areaIndexFinder.findByLines(editor, area); if (lineIndexes.count <= 0) { reject(CancelReason.NoMatches); return; } const placeholders: Placeholder[] = this.placeholderCalculus.buildPlaceholders( lineIndexes, ); if (placeholders.length === 0) { reject(CancelReason.NoMatches); return; } try { const jumpedPlaceholder = await this.recursivelyJumpTo( editor, placeholders, ); resolve(jumpedPlaceholder); } catch (error) { // let's try to recalculate placeholders if we change visible range if (error === CancelReason.ChangedVisibleRanges) { const debounced = await asyncDebounce(async () => { try { const placeholder = await this.buildPlaceholdersForLines(editor); resolve(placeholder); } catch (error) { reject(error); } }, 500); await debounced(); } else { reject(error); } } }); } /** * recursively creates placeholders in supplied editor and waits for user input for jumping * @param editor * @param placeholders */ private recursivelyJumpTo(editor: TextEditor, placeholders: Placeholder[]) { return new Promise<Placeholder>(async (resolve, reject) => { if (this.config.dim.enabled) { const placeholderHoles = this.placeholderCalculus.getPlaceholderHoles( placeholders, editor.document.lineCount, ); this.placeHolderDecorator.dimEditor(editor, placeholderHoles); } this.placeHolderDecorator.removeDecorations(editor); this.placeHolderDecorator.removeHighlights(editor); this.placeHolderDecorator.addDecorations(editor, placeholders); const messageDisposable = this.setMessage('Jump To', 5000); try { const char = await new InlineInput().show(); if (!char) { reject(CancelReason.EmptyValue); return; } this.placeHolderDecorator.removeDecorations(editor); this.placeHolderDecorator.removeHighlights(editor); this.placeHolderDecorator.undimEditor(editor); let placeholder = findPlaceholder(char)(placeholders); if (!placeholder) { reject(CancelReason.NoPlaceHolderMatched); return; } if (placeholder.root) { placeholder = placeholder.root; } const resolvedPlaceholder = await this.resolvePlaceholderOrChildren( placeholder, editor, ); resolve(resolvedPlaceholder); messageDisposable.dispose(); } catch (error) { this.placeHolderDecorator.removeDecorations(editor); this.placeHolderDecorator.removeHighlights(editor); this.placeHolderDecorator.undimEditor(editor); messageDisposable.dispose(); reject(error); } }); } private async resolvePlaceholderOrChildren( placeholder: Placeholder, editor: TextEditor, ) { return new Promise<Placeholder>(async (resolve, reject) => { if (placeholder.childrens.length > 1) { try { const innerPlaceholder = await this.recursivelyJumpTo( editor, placeholder.childrens, ); resolve(innerPlaceholder); } catch (error) { reject(error); } } else { resolve(placeholder); } }); } /** * recursively restrict placeholders in supplied editor with supplied input from user * @param editor * @param placeholders * @param lineIndexes */ private recursivelyRestrict( editor: TextEditor, placeholders: Placeholder[], lineIndexes: LineIndexes, ) { return new Promise<Placeholder[]>(async (resolve, reject) => { if (this.config.dim.enabled) { const placeholderHoles = this.placeholderCalculus.getPlaceholderHoles( placeholders, editor.document.lineCount, lineIndexes.highlightCount, ); this.placeHolderDecorator.dimEditor(editor, placeholderHoles); } this.placeHolderDecorator.addDecorations(editor, placeholders); this.placeHolderDecorator.addHighlights( editor, placeholders, lineIndexes.highlightCount, ); const messageDisposable = this.setMessage('Next char', 5000); try { const char = await new InlineInput().show(); if (!char) { reject(CancelReason.EmptyValue); return; } this.placeHolderDecorator.removeDecorations(editor); this.placeHolderDecorator.removeHighlights(editor); this.placeHolderDecorator.undimEditor(editor); const restrictedLineIndexes = this.areaIndexFinder.restrictByChar( editor, lineIndexes, char, ); // we failed to restrict if (restrictedLineIndexes.count <= 0) { // we try to check if char matches placeholder const placeholder = findPlaceholder(char)(placeholders); if (!!placeholder) { const resolvedPlaceholder = await this.resolvePlaceholderOrChildren( placeholder, editor, ); resolve([resolvedPlaceholder]); messageDisposable.dispose(); return; } else { // we keep the existing placeholders and try again resolve( await this.recursivelyRestrict(editor, placeholders, lineIndexes), ); messageDisposable.dispose(); return; } } const restrictedPlaceholders: Placeholder[] = this.placeholderCalculus.buildPlaceholders( restrictedLineIndexes, ); if (restrictedPlaceholders.length === 0) { reject(CancelReason.NoMatches); return; } if (restrictedPlaceholders.length === 1) { resolve(restrictedPlaceholders); } else { try { resolve( await this.recursivelyRestrict( editor, restrictedPlaceholders, restrictedLineIndexes, ), ); messageDisposable.dispose(); } catch (error) { console.error(error); reject(error); } } } catch (error) { console.error(error); if (error === CancelReason.Cancel) { // we pressed the escape character | canceled so we can start to jump messageDisposable.dispose(); resolve(placeholders); } else { this.placeHolderDecorator.removeDecorations(editor); this.placeHolderDecorator.removeHighlights(editor); this.placeHolderDecorator.undimEditor(editor); messageDisposable.dispose(); reject(error); } } }); } private buildMessage(error: CancelReason): string { switch (error) { case CancelReason.EmptyValue: return 'Empty Value'; case CancelReason.ChangedActiveEditor: return 'Changed editor'; case CancelReason.ChangedVisibleRanges: return 'Changed visible range'; case CancelReason.NoMatches: case CancelReason.NoPlaceHolderMatched: return 'No Matches'; default: return 'Canceled'; } } private setMessage(message: string, timeout: number): Disposable { if (timeout > 0) { return window.setStatusBarMessage(`$(rocket) ${message}`, timeout); } else { return window.setStatusBarMessage(`$(rocket) ${message}`); } } }
the_stack
import {UserPrefRepo} from './UserPrefRepo'; import {IssueEntity} from '../Library/Type/IssueEntity'; import {RemoteIssueEntity} from '../Library/Type/RemoteGitHubV3/RemoteIssueEntity'; import {GitHubUtil} from '../Library/Util/GitHubUtil'; import {StreamIssueRepo} from './StreamIssueRepo'; import {DateUtil} from '../Library/Util/DateUtil'; import {FilterSQLRepo} from './FilterSQLRepo'; import {DB} from '../Library/Infra/DB'; import {StreamEntity} from '../Library/Type/StreamEntity'; import {RepositoryEntity} from '../Library/Type/RepositoryEntity'; import {RemoteGitHubV4IssueEntity} from '../Library/Type/RemoteGitHubV4/RemoteGitHubV4IssueNodesEntity'; import {GitHubV4IssueClient} from '../Library/GitHub/V4/GitHubV4IssueClient'; class _IssueRepo { private async relations(issues: IssueEntity[]) { for (const issue of issues) issue.value = JSON.parse(issue.value as any); } async getIssues(issueIds: number[]): Promise<{error?: Error; issues?: IssueEntity[]}> { const {error, rows: issues} = await DB.select<IssueEntity>(`select * from issues where id in (${issueIds.join(',')})`); if (error) return {error}; await this.relations(issues); return {issues}; } async getIssue(issueId: number): Promise<{error?: Error; issue?: IssueEntity}> { const {error, issues} = await this.getIssues([issueId]); if (error) return {error}; return {issue: issues[0]}; } async getIssueByIssueNumber(repo: string, issueNumber: number): Promise<{error?: Error; issue?: IssueEntity}> { const {error, row: issue} = await DB.selectSingle<IssueEntity>(`select * from issues where repo = ? and number = ?`, [repo, issueNumber]); if (error) return {error}; if (!issue) return {issue: null}; await this.relations([issue]); return {issue}; } async getIssuesInStream(queryStreamId: number | null, defaultFilter: string, userFilter: string, page: number = 0, perPage = 30): Promise<{error?: Error; issues?: IssueEntity[]; totalCount?: number; hasNextPage?: boolean}> { const filter = `${userFilter} ${defaultFilter}`; const {issuesSQL, countSQL} = await this.buildSQL(queryStreamId, filter, page, perPage); const {error: e1, rows: issues} = await DB.select<IssueEntity>(issuesSQL); if (e1) return {error: e1}; const {error: e2, row: countRow} = await DB.selectSingle<{count: number}>(countSQL); if (e2) return {error: e2}; const hasNextPage = page * perPage + perPage < countRow.count; await this.relations(issues); return {issues, totalCount: countRow.count, hasNextPage}; } async getRecentlyIssues(): Promise<{error?: Error; issues?: IssueEntity[]}> { const {error, rows: issues} = await DB.select<IssueEntity>(`select * from issues order by updated_at desc limit 100`); if (error) return {error}; await this.relations(issues); return {issues}; } async getTotalCount(): Promise<{error?: Error; count?: number}>{ const {error, row} = await DB.selectSingle<{count: number}>('select count(1) as count from issues'); if (error) return {error}; return {count: row.count}; } async getTotalUnreadCount(): Promise<{error?: Error; count?: number}> { const {error, row} = await DB.selectSingle<{count: number}>(` select count(distinct t1.id) as count from issues as t1 inner join streams_issues as t2 on t1.id = t2.issue_id where ((read_at is null) or (updated_at > read_at)) and archived_at is null `); if (error) return {error}; return {count: row.count}; } async getUnreadCountInStream(streamId: number | null, defaultFilter: string, userFilter: string = ''): Promise<{error?: Error; count?: number}> { const filter = `${userFilter} ${defaultFilter}`; const {unreadCountSQL} = await this.buildSQL(streamId, filter, 0, 0); const {error, row: countRow} = await DB.selectSingle<{count: number}>(unreadCountSQL); if (error) return {error}; return {count: countRow.count}; } async getIncludeIds(issueIds: number[], queryStreamId: StreamEntity['queryStreamId'], defaultFilter: string, userFilter: string = ''): Promise<{error?: Error; issueIds?: number[]}> { const cond = FilterSQLRepo.getSQL(`${userFilter} ${defaultFilter}`); const sql = ` select id from issues where ${cond.filter} ${queryStreamId !== null ? `and id in (select issue_id from streams_issues where stream_id = ${queryStreamId})` : ''} and id in (${issueIds.join(',')}) `; const {error, rows} = await DB.select<{id: number}>(sql); if (error) return {error}; const includedIssueIds = rows.map(row => row.id); return {issueIds: includedIssueIds}; } isRead(issue: IssueEntity): boolean { return issue && issue.read_at !== null && issue.read_at >= issue.updated_at; } async createBulk(streamId: number, issues: RemoteIssueEntity[], markAdReadIfOldIssue: boolean = false): Promise<{error?: Error; updatedIssueIds?: number[]}> { const updatedIds = []; const loginName = UserPrefRepo.getUser().login; const now = DateUtil.localToUTCString(new Date()); for (const issue of issues) { const {repo, user} = GitHubUtil.getInfo(issue.url); const res = await this.getIssue(issue.id); if (res.error) return {error: res.error}; const currentIssue = res.issue; let readAt = null; // 新規issueかunreadされてないissueのみ if (!currentIssue || !(currentIssue.unread_at && currentIssue.unread_at > currentIssue.read_at)) { // 最終更新が自分の場合は既読 if (issue.last_timeline_user === loginName && issue.last_timeline_at === issue.updated_at) { readAt = issue.updated_at; } else if (markAdReadIfOldIssue) { // 古いissueの場合は既読 const fromNow = Date.now() - new Date(issue.updated_at).getTime(); if (fromNow >= 7 * 24 * 60 * 60 * 1000) { // 更新が7日前の場合、既読扱いとする readAt = now; } } } const params = [ issue.id, issue.node_id, issue.pull_request ? 'pr' : 'issue', issue.title, issue.created_at, issue.updated_at, issue.closed_at || null, issue.merged_at || null, readAt || currentIssue?.read_at || null, issue.number, user, repo, issue.user.login, // author issue.assignees.length ? issue.assignees.map((assignee)=> `<<<<${assignee.login}>>>>`).join('') : null, // hack: assignees format issue.labels.length ? issue.labels.map((label)=> `<<<<${label.name}>>>>`).join('') : null, // hack: labels format issue.milestone?.title || null, issue.milestone?.due_on || null, issue.draft ? 1 : 0, issue.private ? 1 : 0, issue.involves?.length ? issue.involves.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: involves format issue.mentions?.length ? issue.mentions.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: mentions format issue.requested_reviewers?.length ? issue.requested_reviewers.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: review_requested format issue.reviews?.length ? issue.reviews.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: reviews format issue.projects?.length ? issue.projects.map(project => `<<<<${project.url}>>>>`).join('') : null, // hack: project_urls format issue.projects?.length ? issue.projects.map(project => `<<<<${project.name}>>>>`).join('') : null, // hack: project_names format issue.projects?.length ? issue.projects.map(project => `<<<<${project.column}>>>>`).join('') : null, // hack: project_columns format issue.last_timeline_user || currentIssue?.last_timeline_user, issue.last_timeline_at || currentIssue?.last_timeline_at, issue.html_url, issue.body, JSON.stringify(issue) ]; if (currentIssue) { const {error} = await DB.exec(` update issues set id = ?, node_id = ?, type = ?, title = ?, created_at = ?, updated_at = ?, closed_at = ?, merged_at = ?, read_at = ?, number = ?, user = ?, repo = ?, author = ?, assignees = ?, labels = ?, milestone = ?, due_on = ?, draft = ?, repo_private = ?, involves = ?, mentions = ?, review_requested = ?, reviews = ?, project_urls = ?, project_names = ?, project_columns = ?, last_timeline_user = ?, last_timeline_at = ?, html_url = ?, body = ?, value = ? where id = ${issue.id} `, params); if (error) return {error}; if (issue.updated_at > currentIssue.updated_at) updatedIds.push(issue.id); } else { const {error} = await DB.exec(` insert into issues ( id, node_id, type, title, created_at, updated_at, closed_at, merged_at, read_at, number, user, repo, author, assignees, labels, milestone, due_on, draft, repo_private, involves, mentions, review_requested, reviews, project_urls, project_names, project_columns, last_timeline_user, last_timeline_at, html_url, body, value ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `, params); if (error) return {error}; updatedIds.push(issue.id); } } // limit max records const max = UserPrefRepo.getPref().database.max; await DB.exec(`delete from issues where id in (select id from issues order by updated_at desc limit ${max}, 1000)`); // create stream-issue const issueIds = issues.map(issue => issue.id); const res = await this.getIssues(issueIds); if (res.error) return {error: res.error}; const {error} = await StreamIssueRepo.createBulk(streamId, res.issues); if (error) return {error}; return {updatedIssueIds: updatedIds}; } async updateWithV4(v4Issues: RemoteGitHubV4IssueEntity[]): Promise<{error?: Error}> { if (!v4Issues.length) return {}; const nodeIds = v4Issues.map(v4Issue => `"${v4Issue.node_id}"`); const {error, rows: issues} = await DB.select<IssueEntity>(`select * from issues where node_id in (${nodeIds.join(',')})`); if (error) return {error}; const v3Issues = issues.map<RemoteIssueEntity>(issue => JSON.parse(issue.value as any)); GitHubV4IssueClient.injectV4ToV3(v4Issues, v3Issues); for (const v3Issue of v3Issues) { const currentIssue = issues.find(issue => issue.id === v3Issue.id); const params = [ v3Issue.merged_at || null, v3Issue.draft ? 1 : 0, v3Issue.private ? 1 : 0, v3Issue.involves?.length ? v3Issue.involves.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: involves format v3Issue.requested_reviewers?.length ? v3Issue.requested_reviewers.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: review_requested format v3Issue.reviews?.length ? v3Issue.reviews.map(user => `<<<<${user.login}>>>>`).join('') : null, // hack: reviews format v3Issue.projects?.length ? v3Issue.projects.map(project => `<<<<${project.url}>>>>`).join('') : null, // hack: project_urls format v3Issue.projects?.length ? v3Issue.projects.map(project => `<<<<${project.name}>>>>`).join('') : null, // hack: project_names format v3Issue.projects?.length ? v3Issue.projects.map(project => `<<<<${project.column}>>>>`).join('') : null, // hack: project_columns format v3Issue.last_timeline_user || currentIssue?.last_timeline_user, v3Issue.last_timeline_at || currentIssue?.last_timeline_at, JSON.stringify(v3Issue) ]; const {error} = await DB.exec(` update issues set merged_at = ?, draft = ?, repo_private = ?, involves = ?, review_requested = ?, reviews = ?, project_urls = ?, project_names = ?, project_columns = ?, last_timeline_user = ?, last_timeline_at = ?, value = ? where id = ${v3Issue.id} `, params); if (error) return {error}; } return {}; } async updateRead(issueId: number, date: Date): Promise<{error?: Error; issue?: IssueEntity}> { if (date) { const readAt = DateUtil.localToUTCString(date); const {error} = await DB.exec( `update issues set read_at = ?, prev_read_at = read_at, read_body = body, prev_read_body = read_body where id = ?`, [readAt, issueId] ); if (error) return {error}; } else { const {error: e1, issue: currentIssue} = await this.getIssue(issueId); if (e1) return {error: e1}; // prev_read_atをnullではなくupdated_atの直前にすることで、すべてのコメントが未読とならないようにする const currentUpdatedAt = new Date(currentIssue.updated_at); const prevReadAt = DateUtil.localToUTCString(new Date(currentUpdatedAt.getTime() - 1000)); const {error} = await DB.exec( `update issues set read_at = prev_read_at, prev_read_at = ?, unread_at = ?, read_body = prev_read_body, prev_read_body = null where id = ?`, [prevReadAt, DateUtil.localToUTCString(new Date()), issueId] ); if (error) return {error}; const {error: e2, issue} = await this.getIssue(issueId); if (e2) return {error: e2}; if (this.isRead(issue)) { await DB.exec(`update issues set read_at = prev_read_at, prev_read_at = null where id = ?`, [issueId]); } } const {error, issue} = await this.getIssue(issueId); if (error) return {error}; return {issue}; } async updateReads(issueIds: number[], date: Date): Promise<{error?: Error; issues?: IssueEntity[]}> { const readAt = DateUtil.localToUTCString(date); const {error} = await DB.exec(` update issues set read_at = ?, read_body = body, prev_read_body = read_body where id in (${issueIds.join(',')}) and (read_at is null or read_at < updated_at) `, [readAt]); if (error) return {error}; const {error: error2, issues} = await this.getIssues(issueIds); if (error2) return {error: error2}; return {issues}; } async updateReadAll(queryStreamId: number | null, defaultFilter: string, userFilter: string =''): Promise<{error?: Error}> { const readAt = DateUtil.localToUTCString(new Date()); const cond = FilterSQLRepo.getSQL(`${userFilter} ${defaultFilter}`); const sql = ` update issues set read_at = ?, read_body = body, prev_read_body = read_body where (read_at is null or read_at < updated_at) and ${cond.filter} ${queryStreamId !== null ? `and id in (select issue_id from streams_issues where stream_id = ${queryStreamId})` : ''} `; const {error} = await DB.exec(sql, [readAt]) if (error) return {error}; return {}; } async updateMark(issueId: number, date: Date): Promise<{error?: Error; issue?: IssueEntity}> { if (date) { const markedAt = DateUtil.localToUTCString(date); const {error} = await DB.exec('update issues set marked_at = ? where id = ?', [markedAt, issueId]); if (error) return {error}; } else { const {error} = await DB.exec('update issues set marked_at = null where id = ?', [issueId]); if (error) return {error}; } const {error, issue} = await this.getIssue(issueId); if (error) return {error}; return {issue}; } async updateArchive(issueId: number, date: Date): Promise<{error?: Error; issue?: IssueEntity}> { if (date) { const archivedAt = DateUtil.localToUTCString(date); const {error} = await DB.exec('update issues set archived_at = ? where id = ?', [archivedAt, issueId]); if (error) return {error}; } else { const {error} = await DB.exec('update issues set archived_at = null where id = ?', [issueId]); if (error) return {error}; } const {error, issue} = await this.getIssue(issueId); if (error) return {error}; return {issue}; } async updateMerged(issueId: number, mergedAt: string): Promise<{error?: Error; issue?: IssueEntity}> { const {error: e1} = await DB.exec('update issues set merged_at = ? where id = ?', [mergedAt, issueId]); if (e1) return {error: e1}; const {error: e2, issue} = await this.getIssue(issueId); if (e2) return {error: e2}; return {issue}; } private async buildSQL(streamId: number, filter: string, page: number, perPage: number): Promise<{issuesSQL: string; countSQL: string; unreadCountSQL: string}> { const cond = FilterSQLRepo.getSQL(filter); const wheres: string[] = []; if (cond.filter) wheres.push(cond.filter); // todo: stream_idは`in`じゃなくて`inner join`のほうが早いかも? // if (streamId !== null) wheres.push(`stream_id = ${streamId}`); if (streamId !== null) { wheres.push(`id in (select issue_id from streams_issues where stream_id = ${streamId})`); } else { wheres.push(`id in (select issue_id from streams_issues)`); } const where = wheres.join(' and '); return { issuesSQL: this.buildIssuesSQL(where, cond.sort, page, perPage), countSQL: this.buildCountSQL(where), unreadCountSQL: this.buildUnreadCountSQL(where), }; } private buildIssuesSQL(where: string, sortSQL, page: number, perPage: number): string { return ` select * from issues where ${where} order by ${sortSQL ? sortSQL : 'updated_at desc'} limit ${page * perPage}, ${perPage} `; } private buildCountSQL(where: string): string { return ` select count(1) as count from issues where ${where} `; } private buildUnreadCountSQL(where: string): string { return ` select count(1) as count from issues where ${where} and ((read_at is null) or (updated_at > read_at)) `; } async getAllRepositories(): Promise<{error?: Error; repositories?: RepositoryEntity[]}> { const {error, rows} = await DB.select<{repo: string}>('select repo from issues group by repo order by count(1) desc;'); if (error) return {error}; const repositories = rows.map((row, index) => ({id: index, fullName: row.repo})); return {repositories}; } } export const IssueRepo = new _IssueRepo();
the_stack
import { App, DropdownComponent, PluginSettingTab, Setting } from 'obsidian'; import type MemosPlugin from './index'; import memoService from './services/memoService'; import { t } from './translations/helper'; import { getDailyNotePath } from './helpers/utils'; export interface MemosSettings { StartDate: string; InsertAfter: string; UserName: string; ProcessEntriesBelow: string; Language: string; SaveMemoButtonLabel: string; SaveMemoButtonIcon: string; ShareFooterStart: string; ShareFooterEnd: string; UseDailyOrPeriodic: string; DefaultPrefix: string; InsertDateFormat: string; DefaultEditorLocation: string; UseButtonToShowEditor: boolean; FocusOnEditor: boolean; OpenDailyMemosWithMemos: boolean; HideDoneTasks: boolean; OpenMemosAutomatically: boolean; // EditorMaxHeight: string; ShowTime: boolean; ShowDate: boolean; AddBlankLineWhenDate: boolean; AutoSaveWhenOnMobile: boolean; DeleteFileName: string; QueryFileName: string; UseVaultTags: boolean; DefaultLightBackgroundImage: string; DefaultDarkBackgroundImage: string; DefaultMemoComposition: string; ShowTaskLabel: boolean; CommentOnMemos: boolean; CommentsInOriginalNotes: boolean; FetchMemosMark: string; FetchMemosFromNote: boolean; ShowCommentOnMemos: boolean; ShowLeftSideBar: boolean; } export const DEFAULT_SETTINGS: MemosSettings = { StartDate: 'Sunday', InsertAfter: '# Journal', UserName: 'MEMO 😉', ProcessEntriesBelow: '', Language: 'en', SaveMemoButtonLabel: 'NOTEIT', SaveMemoButtonIcon: '✍️', ShareFooterStart: '{MemosNum} Memos {UsedDay} Day', ShareFooterEnd: '✍️ by {UserName}', DefaultPrefix: 'List', UseDailyOrPeriodic: 'Daily', InsertDateFormat: 'Tasks', DefaultEditorLocation: 'Top', UseButtonToShowEditor: false, FocusOnEditor: true, OpenDailyMemosWithMemos: true, HideDoneTasks: false, ShowTaskLabel: false, OpenMemosAutomatically: false, // EditorMaxHeight: '250', ShowTime: true, ShowDate: true, AddBlankLineWhenDate: false, AutoSaveWhenOnMobile: false, DeleteFileName: 'delete', QueryFileName: 'query', UseVaultTags: false, DefaultLightBackgroundImage: '', DefaultDarkBackgroundImage: '', DefaultMemoComposition: '{TIME} {CONTENT}', CommentOnMemos: false, CommentsInOriginalNotes: false, FetchMemosMark: '#memo', FetchMemosFromNote: false, ShowCommentOnMemos: false, ShowLeftSideBar: false, }; export class MemosSettingTab extends PluginSettingTab { plugin: MemosPlugin; //eslint-disable-next-line private applyDebounceTimer: number = 0; constructor(app: App, plugin: MemosPlugin) { super(app, plugin); this.plugin = plugin; } applySettingsUpdate() { clearTimeout(this.applyDebounceTimer); const plugin = this.plugin; this.applyDebounceTimer = window.setTimeout(() => { plugin.saveSettings(); }, 100); memoService.updateTagsState(); } async changeFileName(originalFileName: string, fileName: string) { const filePath = getDailyNotePath(); const absolutePath = filePath + '/' + originalFileName + '.md'; const newFilePath = filePath + '/' + fileName + '.md'; const getFile = this.app.vault.getAbstractFileByPath(absolutePath); // const deleteFile = this.app.metadataCache.getFirstLinkpathDest('', absolutePath); await this.app.fileManager.renameFile(getFile, newFilePath); } //eslint-disable-next-line async hide() {} async display() { await this.plugin.loadSettings(); const { containerEl } = this; this.containerEl.empty(); this.containerEl.createEl('h1', { text: t('Basic Options') }); // containerEl.createDiv("", (el) => { // el.innerHTML = "Basic Options"; // }); new Setting(containerEl) .setName(t('User name in Memos')) .setDesc(t("Set your user name here. 'Memos 😏' By default")) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.UserName) .setValue(this.plugin.settings.UserName) .onChange(async (value) => { this.plugin.settings.UserName = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Insert after heading')) .setDesc( t('You should set the same heading below if you want to insert and process memos below the same heading.'), ) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.InsertAfter) .setValue(this.plugin.settings.InsertAfter) .onChange(async (value) => { this.plugin.settings.InsertAfter = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Process Memos below')) .setDesc( t( 'Only entries below this string/section in your notes will be processed. If it does not exist no notes will be processed for that file.', ), ) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.ProcessEntriesBelow) .setValue(this.plugin.settings.ProcessEntriesBelow) .onChange(async (value) => { this.plugin.settings.ProcessEntriesBelow = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Save Memo button label')) .setDesc(t("The text shown on the save Memo button in the UI. 'NOTEIT' by default.")) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.SaveMemoButtonLabel) .setValue(this.plugin.settings.SaveMemoButtonLabel) .onChange(async (value) => { this.plugin.settings.SaveMemoButtonLabel = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Save Memo button icon')) .setDesc(t('The icon shown on the save Memo button in the UI.')) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.SaveMemoButtonIcon) .setValue(this.plugin.settings.SaveMemoButtonIcon) .onChange(async (value) => { this.plugin.settings.SaveMemoButtonIcon = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Focus on editor when open memos')) .setDesc(t('Focus on editor when open memos. Focus by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.FocusOnEditor).onChange(async (value) => { this.plugin.settings.FocusOnEditor = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Open daily memos with open memos')) .setDesc(t('Open daily memos with open memos. Open by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.OpenDailyMemosWithMemos).onChange(async (value) => { this.plugin.settings.OpenDailyMemosWithMemos = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Open Memos when obsidian opens')) .setDesc(t('When enable this, Memos will open when Obsidian opens. False by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.OpenMemosAutomatically).onChange(async (value) => { this.plugin.settings.OpenMemosAutomatically = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Hide done tasks in Memo list')) .setDesc(t('Hide all done tasks in Memo list. Show done tasks by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.HideDoneTasks).onChange(async (value) => { this.plugin.settings.HideDoneTasks = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Show Tasks Label')) .setDesc(t('Show tasks label near the time text. False by default')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.ShowTaskLabel).onChange(async (value) => { this.plugin.settings.ShowTaskLabel = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Use Tags In Vault')) .setDesc(t('Use tags in vault rather than only in Memos. False by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.UseVaultTags).onChange(async (value) => { this.plugin.settings.UseVaultTags = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Always Show Leaf Sidebar on PC')) .setDesc(t('Show left sidebar on PC even when the leaf width is less than 875px. False by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.ShowLeftSideBar).onChange(async (value) => { this.plugin.settings.ShowLeftSideBar = value; this.applySettingsUpdate(); }), ); this.containerEl.createEl('h1', { text: t('Advanced Options') }); // new Setting(containerEl) // .setName('Set The Max-Height for Editor') // .setDesc("Set the max height for editor in Memos. '250' By default") // .addText((text) => // text // .setPlaceholder(DEFAULT_SETTINGS.EditorMaxHeight) // .setValue(this.plugin.settings.EditorMaxHeight) // .onChange(async (value) => { // this.plugin.settings.EditorMaxHeight = value; // this.applySettingsUpdate(); // }), // ); let dropdown: DropdownComponent; // new Setting(containerEl) // .setName(t('UI language for date')) // .setDesc(t("Translates the date UI language. Only 'en' and 'zh' are available.")) // .addDropdown(async (d: DropdownComponent) => { // dropdown = d; // dropdown.addOption('zh', '中文'); // dropdown.addOption('en', 'English'); // dropdown.setValue(this.plugin.settings.Language).onChange(async (value) => { // this.plugin.settings.Language = value; // this.applySettingsUpdate(); // }); // }); new Setting(containerEl) .setName(t('Default prefix')) .setDesc(t("Set the default prefix when create memo, 'List' by default.")) .addDropdown(async (d: DropdownComponent) => { dropdown = d; dropdown.addOption('List', t('List')); dropdown.addOption('Task', t('Task')); dropdown.setValue(this.plugin.settings.DefaultPrefix).onChange(async (value) => { this.plugin.settings.DefaultPrefix = value; this.applySettingsUpdate(); }); }); new Setting(containerEl) .setName(t('Default insert date format')) .setDesc(t("Set the default date format when insert date by @, 'Tasks' by default.")) .addDropdown(async (d: DropdownComponent) => { dropdown = d; dropdown.addOption('Tasks', 'Tasks'); dropdown.addOption('Dataview', 'Dataview'); dropdown.setValue(this.plugin.settings.InsertDateFormat).onChange(async (value) => { this.plugin.settings.InsertDateFormat = value; this.applySettingsUpdate(); }); }); new Setting(containerEl) .setName(t('Show Time When Copy Results')) .setDesc(t('Show time when you copy results, like 12:00. Copy time by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.ShowTime).onChange(async (value) => { this.plugin.settings.ShowTime = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Show Date When Copy Results')) .setDesc(t('Show date when you copy results, like [[2022-01-01]]. Copy date by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.ShowDate).onChange(async (value) => { this.plugin.settings.ShowDate = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Add Blank Line Between Different Date')) .setDesc(t('Add blank line when copy result with date. No blank line by default.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.AddBlankLineWhenDate).onChange(async (value) => { this.plugin.settings.AddBlankLineWhenDate = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('File Name of Recycle Bin')) .setDesc(t("Set the filename for recycle bin. 'delete' By default")) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.DeleteFileName) .setValue(this.plugin.settings.DeleteFileName) .onChange(async (value) => { await this.changeFileName(this.plugin.settings.DeleteFileName, value); this.plugin.settings.DeleteFileName = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('File Name of Query File')) .setDesc(t("Set the filename for query file. 'query' By default")) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.QueryFileName) .setValue(this.plugin.settings.QueryFileName) .onChange(async (value) => { await this.changeFileName(this.plugin.settings.QueryFileName, value); this.plugin.settings.QueryFileName = value; this.applySettingsUpdate(); }), ); this.containerEl.createEl('h1', { text: t('Mobile Options') }); new Setting(containerEl) .setName(t('Default editor position on mobile')) .setDesc(t("Set the default editor position on Mobile, 'Top' by default.")) .addDropdown(async (d: DropdownComponent) => { dropdown = d; dropdown.addOption('Top', t('Top')); dropdown.addOption('Bottom', t('Bottom')); dropdown.setValue(this.plugin.settings.DefaultEditorLocation).onChange(async (value) => { this.plugin.settings.DefaultEditorLocation = value; this.applySettingsUpdate(); }); }); new Setting(containerEl) .setName(t('Use button to show editor on mobile')) .setDesc(t('Set a float button to call editor on mobile. Only when editor located at the bottom works.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.UseButtonToShowEditor).onChange(async (value) => { this.plugin.settings.UseButtonToShowEditor = value; this.applySettingsUpdate(); }), ); this.containerEl.createEl('h1', { text: t('Share Options') }); new Setting(containerEl) .setName(t('Share Memos Image Footer Start')) .setDesc( t( "Set anything you want here, use {MemosNum} to display Number of memos, {UsedDay} for days. '{MemosNum} Memos {UsedDay} Days' By default", ), ) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.ShareFooterStart) .setValue(this.plugin.settings.ShareFooterStart) .onChange(async (value) => { this.plugin.settings.ShareFooterStart = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Share Memos Image Footer End')) .setDesc(t("Set anything you want here, use {UserName} as your username. '✍️ By {UserName}' By default")) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.ShareFooterEnd) .setValue(this.plugin.settings.ShareFooterEnd) .onChange(async (value) => { this.plugin.settings.ShareFooterEnd = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Background Image in Light Theme')) .setDesc(t('Set background image in light theme. Set something like "Daily/one.png"')) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.DefaultLightBackgroundImage) .setValue(this.plugin.settings.DefaultLightBackgroundImage) .onChange(async (value) => { this.plugin.settings.DefaultLightBackgroundImage = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Background Image in Dark Theme')) .setDesc(t('Set background image in dark theme. Set something like "Daily/one.png"')) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.DefaultDarkBackgroundImage) .setValue(this.plugin.settings.DefaultDarkBackgroundImage) .onChange(async (value) => { this.plugin.settings.DefaultDarkBackgroundImage = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Save Shared Image To Folder For Mobile')) .setDesc(t('Save image to folder for mobile. False by Default')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.AutoSaveWhenOnMobile).onChange(async (value) => { this.plugin.settings.AutoSaveWhenOnMobile = value; this.applySettingsUpdate(); }), ); this.containerEl.createEl('h1', { text: t('Experimental Options') }); new Setting(containerEl) .setName(t("Use Which Plugin's Default Configuration")) .setDesc(t("Memos use the plugin's default configuration to fetch memos from daily, 'Daily' by default.")) .addDropdown(async (d: DropdownComponent) => { dropdown = d; dropdown.addOption('Daily', t('Daily')); dropdown.addOption('Periodic', 'Periodic'); dropdown.setValue(this.plugin.settings.UseDailyOrPeriodic).onChange(async (value) => { this.plugin.settings.UseDailyOrPeriodic = value; this.applySettingsUpdate(); }); }); new Setting(containerEl) .setName(t('Default Memo Composition')) .setDesc( t( 'Set default memo composition, you should use {TIME} as "HH:mm" and {CONTENT} as content. "{TIME} {CONTENT}" by default', ), ) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.DefaultMemoComposition) .setValue(this.plugin.settings.DefaultMemoComposition) .onChange(async (value) => { this.plugin.settings.DefaultMemoComposition = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Allow Comments On Memos')) .setDesc(t('You can comment on memos. False by default')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.CommentOnMemos).onChange(async (value) => { this.plugin.settings.CommentOnMemos = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Always Show Memo Comments')) .setDesc(t('Always show memo comments on memos. False by default')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.ShowCommentOnMemos).onChange(async (value) => { this.plugin.settings.ShowCommentOnMemos = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Comments In Original DailyNotes/Notes')) .setDesc(t('You should install Dataview Plugin ver 0.5.9 or later to use this feature.')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.CommentsInOriginalNotes).onChange(async (value) => { this.plugin.settings.CommentsInOriginalNotes = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Allow Memos to Fetch Memo from Notes')) .setDesc(t('Use Memos to manage all memos in your notes, not only in daily notes. False by default')) .addToggle((toggle) => toggle.setValue(this.plugin.settings.FetchMemosFromNote).onChange(async (value) => { this.plugin.settings.FetchMemosFromNote = value; this.applySettingsUpdate(); }), ); new Setting(containerEl) .setName(t('Fetch Memos From Particular Notes')) .setDesc( t( 'You can set any Dataview Query for memos to fetch it. All memos in those notes will show on list. "#memo" by default', ), ) .addText((text) => text .setPlaceholder(DEFAULT_SETTINGS.FetchMemosMark) .setValue(this.plugin.settings.FetchMemosMark) .onChange(async (value) => { this.plugin.settings.FetchMemosMark = value; if (value === '') { this.plugin.settings.FetchMemosMark = DEFAULT_SETTINGS.FetchMemosMark; } this.applySettingsUpdate(); }), ); this.containerEl.createEl('h1', { text: t('Say Thank You') }); new Setting(containerEl) .setName(t('Donate')) .setDesc(t('If you like this plugin, consider donating to support continued development:')) // .setClass("AT-extra") .addButton((bt) => { bt.buttonEl.outerHTML = `<a href="https://www.buymeacoffee.com/boninall"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=boninall&button_colour=6495ED&font_colour=ffffff&font_family=Inter&outline_colour=000000&coffee_colour=FFDD00"></a>`; }); } }
the_stack
* Interface implemented by TypeScript objects that have an HTML rendering. * This returns the root of the HTML rendering. */ export interface IHtmlElement { getHTMLRepresentation(): HTMLElement; } export interface IAppendChild { appendChild(elem: HTMLElement): void; } export interface ErrorReporter { reportError(message: string): void; } enum Direction { Up, Down, None } export class SpecialChars { public static upArrow = "▲"; public static downArrow = "▼"; public static clipboard = "\uD83D\uDCCB"; public static expand = "+"; public static shrink = "\u2501"; // heavy line public static childAndNext = "├"; public static vertical = "│"; public static child = "└"; } /** * Converts a number to a more readable representation. * Negative numbers are shown as empty strings. */ export function formatPositiveNumber(n: number): string { if (n < 0) return ""; return n.toLocaleString(); } export function px(dim: number): string { if (dim === 0) return dim.toString(); return dim.toString() + "px"; } function createSvgElement(tag: string): SVGElement { return document.createElementNS("http://www.w3.org/2000/svg", tag); } /** * Convert a number to an string by keeping only the most significant digits * and adding a suffix. Similar to the previous function, but returns a pure string. */ export function significantDigits(n: number): string { let suffix = ""; if (n === 0) return "0"; const absn = Math.abs(n); if (absn > 1e12) { suffix = "T"; n = n / 1e12; } else if (absn > 1e9) { suffix = "B"; n = n / 1e9; } else if (absn > 1e6) { suffix = "M"; n = n / 1e6; } else if (absn > 1e3) { suffix = "K"; n = n / 1e3; } else if (absn < .001) { let expo = 0; while (n < 1) { n = n * 10; expo++; } suffix = " * 10e-" + expo; } if (absn > 1) n = Math.round(n * 100) / 100; else n = Math.round(n * 1000) / 1000; return String(n) + suffix; } export function percentString(n: number): string { n = Math.round(n * 1000) / 10; return significantDigits(n) + "%"; } /** * A horizontal rectangle that displays a data range within an interval 0-max. */ export class DataRangeUI { private readonly topLevel: Element; public static readonly width = 80; // pixels /** * @param position: Beginning of data range. * @param count: Size of data range. * @param totalCount: Maximum value of interval. */ constructor(position: number, count: number, totalCount: number) { this.topLevel = createSvgElement("svg"); this.topLevel.classList.add("dataRange"); this.topLevel.setAttribute("width", px(DataRangeUI.width)); this.topLevel.setAttribute("height", px(10)); // If the range is no 0 but represents < 1 % of the total count, use 1% of the // bar's width, s.t. it is still visible. const w = count > 0 ? Math.max(0.01, count / totalCount) : count; let x = position / totalCount; if (x + w > 1) x = 1 - w; const g = createSvgElement("g"); this.topLevel.appendChild(g); const title = createSvgElement("title"); title.textContent = "(" + significantDigits(position) + " + " + significantDigits(count) + ") / " + significantDigits(totalCount) + "\n" + percentString(position / totalCount) + " + " + percentString(count / totalCount); g.appendChild(title); const rect1 = createSvgElement("rect"); g.appendChild(rect1); rect1.setAttribute("x", x.toString() + "%"); rect1.setAttribute("y", "0"); rect1.setAttribute("fill", "black"); rect1.setAttribute("width", w.toString() + "%"); rect1.setAttribute("height", "1"); } public getDOMRepresentation(): Element { return this.topLevel; } } /** * HTML strings are strings that represent an HTML fragment. * They are usually assigned to innerHTML of a DOM object. * These strings should be "safe": i.e., the HTML they contain should * be produced internally, and they should not come * from external sources, because they can cause DOM injection attacks. */ export class HtmlString implements IHtmlElement { private safeValue: string; constructor(private arg: string) { // Escape the argument string. const div = document.createElement("div"); div.innerText = arg; this.safeValue = div.innerHTML; } public appendSafeString(str: string): void { this.safeValue += str; } public append(message: HtmlString): void { this.safeValue += message.safeValue; } public prependSafeString(str: string): void { this.safeValue = str + this.safeValue; } public setInnerHtml(elem: HTMLElement): void { elem.innerHTML = this.safeValue; } public clear(): void { this.safeValue = ""; } public getHTMLRepresentation(): HTMLElement { const div = document.createElement("div"); div.innerText = this.safeValue; return div; } } /** * Remove all children of an HTML DOM object.. */ export function removeAllChildren(h: HTMLElement): void { while (h.lastChild != null) h.removeChild(h.lastChild); } /** * convert a number to a string and prepend zeros if necessary to * bring the integer part to the specified number of digits */ export function zeroPad(num: number, length: number): string { const n = Math.abs(num); const zeros = Math.max(0, length - Math.floor(n).toString().length ); let zeroString = Math.pow(10, zeros).toString().substr(1); if (num < 0) { zeroString = "-" + zeroString; } return zeroString + n; } /** * A location inside source code. * Used for parsing the JSON input. */ interface Location { file: string, pos: [number, number, number, number] } /** * A row in a profile dataset. */ interface ProfileRow { opid: number, cpu_us: number, invocations: number; size: number; locations: Location[], descr: string, short_descr: string, dd_op: string, children: Partial<ProfileRow>[] } interface Profile { type: string, name: string, records: Partial<ProfileRow>[] } /** * A div with two buttons: to close it, and to copy its content to the * clipboard. */ export class ClosableCopyableContent implements IHtmlElement, IAppendChild { protected topLevel: HTMLElement; protected contents: HTMLDivElement; protected clearButton: HTMLElement; protected copyButton: HTMLElement; /** * Build a ClosableCopyableContent object. * @param onclose Callback to invoke when the close button is pressed. */ constructor(protected onclose: () => void) { this.topLevel = document.createElement("div"); this.contents = document.createElement("div"); const container = document.createElement("span"); this.topLevel.appendChild(container); this.copyButton = document.createElement("span"); this.copyButton.innerHTML = SpecialChars.clipboard; this.copyButton.title = "copy contents to clipboard"; this.copyButton.style.display = "none"; this.copyButton.classList.add("clickable"); this.copyButton.onclick = () => this.copyToClipboard(); this.copyButton.style.cssFloat = "right"; this.copyButton.style.zIndex = "10"; this.clearButton = document.createElement("span"); this.clearButton.classList.add("close"); this.clearButton.innerHTML = "&times;"; this.clearButton.title = "clear message"; this.clearButton.style.display = "none"; this.clearButton.onclick = () => this.clear(); this.clearButton.style.zIndex = "10"; container.appendChild(this.clearButton); container.appendChild(this.copyButton); container.appendChild(this.contents); } public copyToClipboard(): void { navigator.clipboard.writeText(this.contents.innerText); } public getHTMLRepresentation(): HTMLElement { return this.topLevel; } protected showButtons(): void { this.clearButton.style.display = "block"; this.copyButton.style.display = "block"; } public setContent(message: string): void { this.contents.innerText = message; this.showButtons(); } public appendChild(elem: HTMLElement): void { this.contents.appendChild(elem); this.showButtons(); } protected hideButtons(): void { this.clearButton.style.display = "none"; this.copyButton.style.display = "none"; } public clear(): void { this.contents.textContent = ""; this.hideButtons(); this.onclose(); } /** * css class to add to the content box. */ public addContentClass(className: string): void { this.contents.classList.add(className); } } /** * This class is used to display error messages in the browser window. */ export class ErrorDisplay implements ErrorReporter, IHtmlElement { protected content: ClosableCopyableContent; constructor() { this.content = new ClosableCopyableContent(() => {}); this.content.addContentClass("console"); this.content.addContentClass("error"); } public getHTMLRepresentation(): HTMLElement { return this.content.getHTMLRepresentation(); } public reportError(message: string): void { console.log("Error: " + message); this.content.setContent(message); } public clear(): void { this.content.clear(); } } /** * A class that knows how to display profile data. */ class ProfileTable implements IHtmlElement { protected tbody: HTMLTableSectionElement; protected table: HTMLTableElement; readonly showCpuHistogram = true; readonly showMemHistogram = false; protected static readonly cpuColumns: string[] = [ "opid", SpecialChars.expand, "cpu_us", "histogram", "invocations", "short_descr", "dd_op" ]; protected static readonly memoryColumns: string[] = [ "opid", SpecialChars.expand, "size", "histogram", "short_descr", "dd_op" ]; // how to rename column names in the table heading protected static readonly cellNames = new Map<string, string>([ ["opid", ""], [SpecialChars.expand, ""], ["cpu_us", "μs"], ["histogram", "histogram"], ["invocations", "calls"], ["size", "size"], ["short_descr", "description"], ["dd_op", "DD operator"] ]); protected displayedColumns: string[]; protected total: number = 0; private data: Partial<ProfileRow>[]; constructor(protected errorReporter: ErrorReporter, protected name: string, protected isCpu: boolean) { this.table = document.createElement("table"); this.data = []; const thead = this.table.createTHead(); const header = thead.insertRow(); let columns; this.displayedColumns = []; if (isCpu) columns = ProfileTable.cpuColumns; else columns = ProfileTable.memoryColumns; for (let c of columns) { if (c == "histogram") { if (isCpu && !this.showCpuHistogram) continue; if (!isCpu && !this.showMemHistogram) continue; } this.displayedColumns.push(c); const cell = header.insertCell(); cell.textContent = ProfileTable.cellNames.get(c)!; cell.classList.add(c); } this.tbody = this.table.createTBody(); } protected getId(row: Partial<ProfileRow>): string { let id = row.opid; let ids; if (id == null) ids = "0"; else ids = id.toString(); return this.name.replace(/[^a-zA-Z0-9]/g, "_").toLowerCase() + "_" + ids; } protected addDataRow(indent: number, rowIndex: number, row: Partial<ProfileRow>, lastInSequence: boolean, histogramStart: number): void { const trow = this.tbody.insertRow(rowIndex); // Fix undefined values let safeRow: ProfileRow = { locations: row.locations === undefined ? [] : row.locations, descr: row.descr === undefined ? "" : row.descr, size: row.size === undefined ? -1 : row.size, cpu_us: row.cpu_us === undefined ? -1 : row.cpu_us, children: row.children === undefined ? [] : row.children, dd_op: row.dd_op === undefined ? "" : row.dd_op, invocations: row.invocations === undefined ? -1 : row.invocations, opid: row.opid === undefined ? 0 : row.opid, short_descr: row.short_descr === undefined ? "" : row.short_descr }; let id = this.getId(safeRow); for (let k of this.displayedColumns) { let key = k as keyof ProfileRow; let value = safeRow[key]; if (k === SpecialChars.expand || k === "histogram") { // These columns do not really exist in the data continue; } let htmlValue: HtmlString; if (k === "cpu_us" || k === "invocations" || k === "size") { htmlValue = new HtmlString(formatPositiveNumber(value as number)); //htmlValue = significantDigitsHtml(value as number); } else { htmlValue = new HtmlString(value.toString()); } const cell = trow.insertCell(); cell.classList.add(k); if (k === "opid") { htmlValue.clear(); let prefix = ""; if (indent > 0) { for (let i = 0; i < indent - 1; i++) prefix += SpecialChars.vertical; const end = lastInSequence ? SpecialChars.child : SpecialChars.childAndNext; htmlValue = new HtmlString(prefix + end); } } else if (k === "ddlog_op") { const a = document.createElement("a"); a.text = value.toString(); cell.appendChild(a); continue; } else if (k === "short_descr") { const str = value.toString(); const direction = (safeRow.descr != "" || safeRow.locations.length > 0) ? Direction.Down : Direction.None; ProfileTable.makeDescriptionContents(cell, str, direction); if (direction != Direction.None) { cell.classList.add("clickable"); cell.onclick = () => this.showDescription(trow, cell, str, safeRow); } continue; } htmlValue.setInnerHtml(cell); if (k === "opid") { // Add an adjacent cell for expanding the row children const cell = trow.insertCell(); const children = safeRow.children; if (children.length > 0) { cell.textContent = SpecialChars.expand; cell.title = "Expand"; cell.classList.add("clickable"); cell.onclick = () => this.expand(indent + 1, trow, cell, children, histogramStart); } if (id != null) { cell.id = id!; cell.title = id; } } if ((k === "size" && this.showMemHistogram) || (k == "cpu_us" && this.showCpuHistogram)) { // Add an adjacent cell for the histogram const cell = trow.insertCell(); const numberValue = value as number; const rangeUI = new DataRangeUI(histogramStart, numberValue, this.total); cell.appendChild(rangeUI.getDOMRepresentation()); } } } /** * Add the description as a child to the expandCell * @param expandCell Cell to add the description to. * @param htmlContents HTML string containing the desired contents. * @param direction If true add a down arrow, else an up arrow. */ static makeDescriptionContents(expandCell: HTMLElement, htmlContents: string, direction: Direction): void { const contents = document.createElement("span"); contents.innerHTML = htmlContents; if (direction == Direction.None) { removeAllChildren(expandCell); expandCell.appendChild(contents); } else { const down = direction == Direction.Down; const arrow = makeSpan((down ? SpecialChars.downArrow : SpecialChars.upArrow) + " "); arrow.title = down ? "Show source code" : "Hide source code"; const span = document.createElement("span"); span.appendChild(arrow); span.appendChild(contents); removeAllChildren(expandCell); expandCell.appendChild(span); } } protected showDescription(tRow: HTMLTableRowElement, expandCell: HTMLTableCellElement, description: string, row: Partial<ProfileRow>): void { const descr = description; ProfileTable.makeDescriptionContents(expandCell, descr, Direction.Up); const newRow = this.tbody.insertRow(tRow.rowIndex); // no +1, since tbody has one fewer rows than the table newRow.insertCell(); // unused. const cell = newRow.insertCell(); cell.colSpan = this.displayedColumns.length - 1; const contents = new ClosableCopyableContent( () => this.hideDescription(tRow, expandCell, descr, row)); cell.appendChild(contents.getHTMLRepresentation()); if (row.descr != "") { const description = makeSpan(""); description.innerHTML = row.descr + "<br>"; contents.appendChild(description); if (row.locations!.length > 0) contents.appendChild(document.createElement("hr")); } expandCell.onclick = () => this.hideDescription(tRow, expandCell, descr, row); for (let loc of row.locations!) { ScriptLoader.instance.loadScript(loc.file, (data: SourceFile) => { this.appendSourceCode(data, loc, contents); }, this.errorReporter) } } protected hideDescription(tRow: HTMLTableRowElement, expandCell: HTMLTableCellElement, description: string, row: Partial<ProfileRow>): void { ProfileTable.makeDescriptionContents(expandCell, description, Direction.Down); this.table.deleteRow(tRow.rowIndex + 1); expandCell.onclick = () => this.showDescription(tRow, expandCell, description, row); } protected appendSourceCode(contents: SourceFile, loc: Location, contentHolder: IAppendChild): void { const snippet = document.createElement("div"); snippet.classList.add("console"); contentHolder.appendChild(snippet); contents.insertSnippet(snippet, loc, 1, 1, this.errorReporter); } protected getDataSize(row: Partial<ProfileRow>): number { if (row.cpu_us) return row.cpu_us; if (row.size) return row.size; return 0; } protected expand(indent: number, tRow: HTMLTableRowElement, expandCell: HTMLTableCellElement, rows: Partial<ProfileRow>[], histogramStart: number): void { expandCell.textContent = SpecialChars.shrink; expandCell.title = "Shrink"; const start = histogramStart; expandCell.onclick = () => this.shrink(indent - 1, tRow, expandCell, rows, start); let index = tRow.rowIndex; for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) { const row = rows[rowIndex]; this.addDataRow(indent, index++, row, rowIndex == rows.length - 1, histogramStart); histogramStart += this.getDataSize(row); } } protected shrink(indent: number, tRow: HTMLTableRowElement, expandCell: HTMLTableCellElement, rows: Partial<ProfileRow>[], histogramStart: number): void { let index = tRow.rowIndex; expandCell.textContent = SpecialChars.expand; expandCell.title = "Expand"; const start = histogramStart; expandCell.onclick = () => this.expand(indent + 1, tRow, expandCell, rows, start); while (true) { const row = this.table.rows[index + 1]; if (row == null) break; if (row.cells.length < this.displayedColumns.length) { // This is a description row. this.table.deleteRow(index + 1); continue; } const text = row.cells[0].textContent; const c = text![indent]; // Based on c we can tell whether this is one of our // children or a new parent. if (c == SpecialChars.child || c == SpecialChars.childAndNext || c == SpecialChars.vertical) this.table.deleteRow(index + 1); else break; } } public getHTMLRepresentation(): HTMLElement { return this.table; } /** * Populate the view with the specified data. * Whatever used to be displayed is removed. */ public setData(rows: Partial<ProfileRow>[]): void { this.data = rows; this.table.removeChild(this.tbody); this.tbody = this.table.createTBody(); for (const row of rows) this.total += this.getDataSize(row); let histogramStart = 0; for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) { const row = rows[rowIndex]; this.addDataRow(0, -1, row, rowIndex == rows.length - 1, histogramStart); histogramStart += this.getDataSize(row); } } protected findPathFromRow(r: Partial<ProfileRow>, id: string): string[] | null { let thisId = this.getId(r); if (thisId == id) { return [thisId]; } if (r.children == null) return null; for (let c of r.children) { let p = this.findPathFromRow(c, id); if (p != null) { p.push(thisId); return p; } } return null; } /** * Find a path of rows that leads to the element with the specified id. */ protected findPath(toId: string): string[] | null { for (let r of this.data) { let path = this.findPathFromRow(r, toId); if (path != null) return path; } return null; } protected expandPath(path: string[]): void { path.reverse(); for (let p of path) { let elem = document.getElementById(p)!; elem.click(); elem.parentElement!.classList.add("highlight"); } let last = document.getElementById(path[path.length - 1]); last!.parentElement!.classList.add("show"); last!.scrollIntoView(); } /** * Find the node with the specified id and make sure it is visible. * If no such node exists, then return false; * @param id */ navigate(id: string): boolean { let path = this.findPath(id); if (path == null) return false; this.expandPath(path); return true; } } /** * Returns a span element containing the specified text. * @param text Text to insert in span. * @param highlight If true the span has class highlight. */ export function makeSpan(text: string | null, highlight: boolean = false): HTMLElement { const span = document.createElement("span"); if (text != null) span.textContent = text; if (highlight) span.className = "highlight"; return span; } // This function is defined in JavaScript declare function getGlobalMapValue(key: string): string | null; /** * Keeps a source file parsed into lines. */ class SourceFile { protected lines: string[]; // number of lines to expand on each click readonly expandLines = 10; constructor(protected filename: string, data: string | null) { if (data == null) { // This can happen on error. this.lines = []; return; } this.lines = data.split("\n"); } /** * Return a snippet of the source file as indicated by the location. * @param parent make the snippet the only child of this element * @param loc source code location of snippet * @param before lines to show before snippet * @param after lines to show after snippet * @param reporter used to report errors */ public insertSnippet(parent: HTMLElement, loc: Location, before: number, after: number, reporter: ErrorReporter): void { removeAllChildren(parent); // Line and column numbers are 1-based const startLine = loc.pos[0] - 1; const endLine = loc.pos[2] - 1; const startColumn = loc.pos[1] - 1; const endColumn = loc.pos[3] - 1; const len = (endLine + 1).toString().length; if (startLine >= this.lines.length) { reporter.reportError("File " + this.filename + " does not have " + startLine + " lines, but only " + this.lines.length); } const fileRow = makeSpan(loc.file); fileRow.classList.add("filename"); parent.appendChild(fileRow); parent.appendChild(document.createElement("br")); let lastLineDisplayed = endLine + 1 + after; if (endColumn == 0) // no data at all from last line, so show one fewer lastLineDisplayed--; const firstLineDisplayed = Math.max(startLine - before, 0); lastLineDisplayed = Math.min(lastLineDisplayed, this.lines.length); if (firstLineDisplayed > 0) { const expandUp = makeSpan(SpecialChars.upArrow); expandUp.title = "Show lines before"; expandUp.classList.add("clickable"); expandUp.onclick = () => this.insertSnippet(parent, loc, before + this.expandLines, after, reporter); parent.appendChild(expandUp); parent.appendChild(document.createElement("br")); } for (let line = firstLineDisplayed; line < lastLineDisplayed; line++) { let l = this.lines[line]; const lineno = zeroPad(line + 1, len); parent.appendChild(makeSpan(lineno + "| ")); if (line == startLine) { parent.appendChild(makeSpan(l.substr(0, startColumn))); if (line == endLine) { parent.appendChild(makeSpan(l.substr(startColumn, endColumn - startColumn), true)); parent.appendChild(makeSpan(l.substr(endColumn))); } else { parent.appendChild(makeSpan(l.substr(startColumn), true)); } } if (line != startLine && line != endLine) { parent.appendChild(makeSpan(l, line >= startLine && line <= endLine)); } if (line == endLine && line != startLine) { parent.appendChild(makeSpan(l.substr(0, endColumn), true)); parent.appendChild(makeSpan(l.substr(endColumn))); } parent.appendChild( document.createElement("br")); } if (lastLineDisplayed < this.lines.length) { const expandDown = makeSpan(SpecialChars.downArrow); expandDown.classList.add("clickable"); expandDown.title = "Show lines after"; expandDown.onclick = () => this.insertSnippet(parent, loc, before, after + this.expandLines, reporter); parent.appendChild(expandDown); parent.appendChild(document.createElement("br")); } } } /** * This class manage loading JavaScript at runtime. * The assumption is that each of these scripts will insert a value * into a global variable called globalMap using a key that is the filename itself. */ class ScriptLoader { public static instance: ScriptLoader = new ScriptLoader(); protected data: Map<string, SourceFile>; private constructor() { this.data = new Map<string, SourceFile>(); } /** * Load a js script file with this name. The script is supposed to * insert a key-value pair into the global variable globalMap. * The key is the file name. The value is a string that is parsed into a SourceFile. * @param filename Filename to load. * @param onload Callback to invoke when file is loaded. The SourceFile * associated to the filename is passed to the callback. * @param reporter Reporter invoked on error. */ public loadScript(filename: string, onload: (source: SourceFile) => void, reporter: ErrorReporter): void { console.log("Attempting to load " + filename); const value = this.data.get(filename); if (value !== undefined) { onload(value); return; } const script = document.createElement("script"); script.src = "./src/" + filename + ".js"; script.onload = () => { const value = getGlobalMapValue(filename); const source = new SourceFile(filename, value); this.data.set(filename, source); if (value == null) { reporter.reportError("Loading file " + filename + " did not produce the expected result"); } else { onload(source); } }; document.head.append(script); } } /** * Main UI to display profile information. */ class ProfileUI implements IHtmlElement { protected topLevel: HTMLElement; protected errorReporter: ErrorDisplay; protected profiles: ProfileTable[]; constructor() { this.topLevel = document.createElement("div"); this.errorReporter = new ErrorDisplay(); this.topLevel.appendChild(this.errorReporter.getHTMLRepresentation()); this.profiles = []; } /** * Returns the html representation of the UI. */ public getHTMLRepresentation(): HTMLElement { return this.topLevel; } protected addProfile(profile: Profile): void { const h1 = document.createElement("h1"); h1.textContent = profile.name; this.topLevel.appendChild(h1); const profileTable = new ProfileTable(this.errorReporter, profile.name,profile.type.toLowerCase() === "cpu"); this.topLevel.appendChild(profileTable.getHTMLRepresentation()); this.profiles.push(profileTable); profileTable.setData(profile.records); } public setData(profiles: Profile[]): void { for (let profile of profiles) { this.addProfile(profile); } } /** * Find the element with the specified id and make sure it is visible. * @param id Element id to search for. */ navigate(id: string) { id = id.replace("#", ""); for (let p of this.profiles) if (p.navigate(id)) break; } } /** * Main function exported by this module: instantiates the user interface. */ export default function createUI(profiles: Profile[]): void { const top = document.getElementById("top"); if (top == null) { console.log("Could not find 'top' element in document"); return; } const ui = new ProfileUI(); top.appendChild(ui.getHTMLRepresentation()); ui.setData(profiles); ui.navigate(window.location.hash); }
the_stack
import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { FailedPredicateException } from "antlr4ts/FailedPredicateException"; import { NotNull } from "antlr4ts/Decorators"; import { NoViableAltException } from "antlr4ts/NoViableAltException"; import { Override } from "antlr4ts/Decorators"; import { Parser } from "antlr4ts/Parser"; import { ParserRuleContext } from "antlr4ts/ParserRuleContext"; import { ParserATNSimulator } from "antlr4ts/atn/ParserATNSimulator"; import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { RecognitionException } from "antlr4ts/RecognitionException"; import { RuleContext } from "antlr4ts/RuleContext"; //import { RuleVersion } from "antlr4ts/RuleVersion"; import { TerminalNode } from "antlr4ts/tree/TerminalNode"; import { Token } from "antlr4ts/Token"; import { TokenStream } from "antlr4ts/TokenStream"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; import { LessParserListener } from "./LessParserListener"; import { LessParserVisitor } from "./LessParserVisitor"; export class LessParser extends Parser { public static readonly NULL = 1; public static readonly IN = 2; public static readonly Unit = 3; public static readonly Ellipsis = 4; public static readonly InterpolationStart = 5; public static readonly LPAREN = 6; public static readonly RPAREN = 7; public static readonly BlockStart = 8; public static readonly BlockEnd = 9; public static readonly LBRACK = 10; public static readonly RBRACK = 11; public static readonly GT = 12; public static readonly TIL = 13; public static readonly LT = 14; public static readonly COLON = 15; public static readonly SEMI = 16; public static readonly COMMA = 17; public static readonly DOT = 18; public static readonly DOLLAR = 19; public static readonly AT = 20; public static readonly PARENTREF = 21; public static readonly HASH = 22; public static readonly COLONCOLON = 23; public static readonly PLUS = 24; public static readonly TIMES = 25; public static readonly DIV = 26; public static readonly MINUS = 27; public static readonly PERC = 28; public static readonly EQEQ = 29; public static readonly GTEQ = 30; public static readonly LTEQ = 31; public static readonly NOTEQ = 32; public static readonly EQ = 33; public static readonly PIPE_EQ = 34; public static readonly TILD_EQ = 35; public static readonly URL = 36; public static readonly UrlStart = 37; public static readonly IMPORT = 38; public static readonly MEDIA = 39; public static readonly MEDIAONLY = 40; public static readonly EXTEND = 41; public static readonly IMPORTANT = 42; public static readonly ARGUMENTS = 43; public static readonly REST = 44; public static readonly REFERENCE = 45; public static readonly INLINE = 46; public static readonly LESS = 47; public static readonly CSS = 48; public static readonly ONCE = 49; public static readonly MULTIPLE = 50; public static readonly WHEN = 51; public static readonly NOT = 52; public static readonly AND = 53; public static readonly Identifier = 54; public static readonly StringLiteral = 55; public static readonly Number = 56; public static readonly Color = 57; public static readonly WS = 58; public static readonly SL_COMMENT = 59; public static readonly COMMENT = 60; public static readonly FUNCTION_NAME = 61; public static readonly COLOR = 62; public static readonly CONVERT = 63; public static readonly DATA_URI = 64; public static readonly DEFAULT = 65; public static readonly UNIT = 66; public static readonly GET_UNIT = 67; public static readonly SVG_GRADIENT = 68; public static readonly ESCAPE = 69; public static readonly E = 70; public static readonly REPLACE = 71; public static readonly LENGTH = 72; public static readonly EXTRACT = 73; public static readonly CEIL = 74; public static readonly FLOOR = 75; public static readonly PERCENTAGE = 76; public static readonly ROUND = 77; public static readonly SQRT = 78; public static readonly ABS = 79; public static readonly SIN = 80; public static readonly ASIN = 81; public static readonly COS = 82; public static readonly ACOS = 83; public static readonly TAN = 84; public static readonly ATAN = 85; public static readonly PI = 86; public static readonly POW = 87; public static readonly MOD = 88; public static readonly MIN = 89; public static readonly MAX = 90; public static readonly ISNUMBER = 91; public static readonly ISSTRING = 92; public static readonly ISCOLOR = 93; public static readonly ISKEYWORD = 94; public static readonly ISURL = 95; public static readonly ISPIXEL = 96; public static readonly ISEM = 97; public static readonly ISPERCENTAGE = 98; public static readonly ISUNIT = 99; public static readonly RGB = 100; public static readonly RGBA = 101; public static readonly ARGB = 102; public static readonly HSL = 103; public static readonly HSLA = 104; public static readonly HSV = 105; public static readonly HSVA = 106; public static readonly HUE = 107; public static readonly SATURATION = 108; public static readonly LIGHTNESS = 109; public static readonly HSVHUE = 110; public static readonly HSVSATURATION = 111; public static readonly HSVVALUE = 112; public static readonly RED = 113; public static readonly GREEN = 114; public static readonly BLUE = 115; public static readonly ALPHA = 116; public static readonly LUMA = 117; public static readonly LUMINANCE = 118; public static readonly SATURATE = 119; public static readonly DESATURATE = 120; public static readonly LIGHTEN = 121; public static readonly DARKEN = 122; public static readonly FADEIN = 123; public static readonly FADEOUT = 124; public static readonly FADE = 125; public static readonly SPIN = 126; public static readonly MIX = 127; public static readonly GREYSCALE = 128; public static readonly CONTRAST = 129; public static readonly MULTIPLY = 130; public static readonly SCREEN = 131; public static readonly OVERLAY = 132; public static readonly SOFTLIGHT = 133; public static readonly HARDLIGHT = 134; public static readonly DIFFERENCE = 135; public static readonly EXCLUSION = 136; public static readonly AVERAGE = 137; public static readonly NEGATION = 138; public static readonly UrlEnd = 139; public static readonly Url = 140; public static readonly SPACE = 141; public static readonly InterpolationStartAfter = 142; public static readonly IdentifierAfter = 143; public static readonly RULE_stylesheet = 0; public static readonly RULE_statement = 1; public static readonly RULE_media = 2; public static readonly RULE_mediaQueryList = 3; public static readonly RULE_mediaQuery = 4; public static readonly RULE_mediaType = 5; public static readonly RULE_mediaExpression = 6; public static readonly RULE_mediaFeature = 7; public static readonly RULE_variableName = 8; public static readonly RULE_commandStatement = 9; public static readonly RULE_mathCharacter = 10; public static readonly RULE_mathStatement = 11; public static readonly RULE_expression = 12; public static readonly RULE_func = 13; public static readonly RULE_conditions = 14; public static readonly RULE_condition = 15; public static readonly RULE_conditionStatement = 16; public static readonly RULE_variableDeclaration = 17; public static readonly RULE_importDeclaration = 18; public static readonly RULE_importOption = 19; public static readonly RULE_referenceUrl = 20; public static readonly RULE_mediaTypes = 21; public static readonly RULE_ruleset = 22; public static readonly RULE_block = 23; public static readonly RULE_blockItem = 24; public static readonly RULE_mixinDefinition = 25; public static readonly RULE_mixinGuard = 26; public static readonly RULE_mixinDefinitionParam = 27; public static readonly RULE_mixinReference = 28; public static readonly RULE_selectors = 29; public static readonly RULE_selector = 30; public static readonly RULE_attrib = 31; public static readonly RULE_negation = 32; public static readonly RULE_pseudo = 33; public static readonly RULE_element = 34; public static readonly RULE_selectorPrefix = 35; public static readonly RULE_attribRelate = 36; public static readonly RULE_identifier = 37; public static readonly RULE_identifierPart = 38; public static readonly RULE_identifierVariableName = 39; public static readonly RULE_property = 40; public static readonly RULE_values = 41; public static readonly RULE_url = 42; public static readonly RULE_measurement = 43; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ "stylesheet", "statement", "media", "mediaQueryList", "mediaQuery", "mediaType", "mediaExpression", "mediaFeature", "variableName", "commandStatement", "mathCharacter", "mathStatement", "expression", "func", "conditions", "condition", "conditionStatement", "variableDeclaration", "importDeclaration", "importOption", "referenceUrl", "mediaTypes", "ruleset", "block", "blockItem", "mixinDefinition", "mixinGuard", "mixinDefinitionParam", "mixinReference", "selectors", "selector", "attrib", "negation", "pseudo", "element", "selectorPrefix", "attribRelate", "identifier", "identifierPart", "identifierVariableName", "property", "values", "url", "measurement", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, "'null'", "'in'", undefined, "'...'", undefined, "'('", "')'", "'{'", "'}'", "'['", "']'", "'>'", "'~'", "'<'", "':'", "';'", "','", "'.'", "'$'", "'@'", "'&'", "'#'", "'::'", "'+'", "'*'", "'/'", "'-'", "'%'", "'=='", "'>='", "'<='", "'!='", "'='", "'|='", "'~='", "'url'", undefined, "'@import'", "'@media'", "'only'", "':extend'", "'!important'", "'@arguments'", "'@rest'", "'reference'", "'inline'", "'less'", "'css'", "'once'", "'multiple'", "'when'", "'not'", "'and'", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "'color'", "'convert'", "'data-uri'", "'default'", "'unit'", "'get-unit'", "'svg-gradient'", "'escape'", "'e'", "'replace'", "'length'", "'extract'", "'ceil'", "'floor'", "'percentage'", "'round'", "'sqrt'", "'abs'", "'sin'", "'asin'", "'cos'", "'acos'", "'tan'", "'atan'", "'pi'", "'pow'", "'mod'", "'min'", "'max'", "'isnumber'", "'isstring'", "'iscolor'", "'iskeyword'", "'isurl'", "'ispixel'", "'isem'", "'ispercentage'", "'isunit'", "'rgb'", "'rgba'", "'argb'", "'hsl'", "'hsla'", "'hsv'", "'hsva'", "'hue'", "'saturation'", "'lightness'", "'hsvhue'", "'hsvsaturation'", "'hsvvalue'", "'red'", "'green'", "'blue'", "'alpha'", "'luma'", "'luminance'", "'saturate'", "'desaturate'", "'lighten'", "'darken'", "'fadein'", "'fadeout'", "'fade'", "'spin'", "'mix'", "'greyscale'", "'contrast'", "'multiply'", "'screen'", "'overlay'", "'softlight'", "'hardlight'", "'difference'", "'exclusion'", "'average'", "'negation'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "NULL", "IN", "Unit", "Ellipsis", "InterpolationStart", "LPAREN", "RPAREN", "BlockStart", "BlockEnd", "LBRACK", "RBRACK", "GT", "TIL", "LT", "COLON", "SEMI", "COMMA", "DOT", "DOLLAR", "AT", "PARENTREF", "HASH", "COLONCOLON", "PLUS", "TIMES", "DIV", "MINUS", "PERC", "EQEQ", "GTEQ", "LTEQ", "NOTEQ", "EQ", "PIPE_EQ", "TILD_EQ", "URL", "UrlStart", "IMPORT", "MEDIA", "MEDIAONLY", "EXTEND", "IMPORTANT", "ARGUMENTS", "REST", "REFERENCE", "INLINE", "LESS", "CSS", "ONCE", "MULTIPLE", "WHEN", "NOT", "AND", "Identifier", "StringLiteral", "Number", "Color", "WS", "SL_COMMENT", "COMMENT", "FUNCTION_NAME", "COLOR", "CONVERT", "DATA_URI", "DEFAULT", "UNIT", "GET_UNIT", "SVG_GRADIENT", "ESCAPE", "E", "REPLACE", "LENGTH", "EXTRACT", "CEIL", "FLOOR", "PERCENTAGE", "ROUND", "SQRT", "ABS", "SIN", "ASIN", "COS", "ACOS", "TAN", "ATAN", "PI", "POW", "MOD", "MIN", "MAX", "ISNUMBER", "ISSTRING", "ISCOLOR", "ISKEYWORD", "ISURL", "ISPIXEL", "ISEM", "ISPERCENTAGE", "ISUNIT", "RGB", "RGBA", "ARGB", "HSL", "HSLA", "HSV", "HSVA", "HUE", "SATURATION", "LIGHTNESS", "HSVHUE", "HSVSATURATION", "HSVVALUE", "RED", "GREEN", "BLUE", "ALPHA", "LUMA", "LUMINANCE", "SATURATE", "DESATURATE", "LIGHTEN", "DARKEN", "FADEIN", "FADEOUT", "FADE", "SPIN", "MIX", "GREYSCALE", "CONTRAST", "MULTIPLY", "SCREEN", "OVERLAY", "SOFTLIGHT", "HARDLIGHT", "DIFFERENCE", "EXCLUSION", "AVERAGE", "NEGATION", "UrlEnd", "Url", "SPACE", "InterpolationStartAfter", "IdentifierAfter", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(LessParser._LITERAL_NAMES, LessParser._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return LessParser.VOCABULARY; } // tslint:enable:no-trailing-whitespace // @Override public get grammarFileName(): string { return "LessParser.g4"; } // @Override public get ruleNames(): string[] { return LessParser.ruleNames; } // @Override public get serializedATN(): string { return LessParser._serializedATN; } constructor(input: TokenStream) { super(input); this._interp = new ParserATNSimulator(LessParser._ATN, this); } // @RuleVersion(0) public stylesheet(): StylesheetContext { let _localctx: StylesheetContext = new StylesheetContext(this._ctx, this.state); this.enterRule(_localctx, 0, LessParser.RULE_stylesheet); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 91; this._errHandler.sync(this); _la = this._input.LA(1); while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << LessParser.InterpolationStart) | (1 << LessParser.GT) | (1 << LessParser.TIL) | (1 << LessParser.COLON) | (1 << LessParser.AT) | (1 << LessParser.PARENTREF) | (1 << LessParser.HASH) | (1 << LessParser.COLONCOLON) | (1 << LessParser.PLUS) | (1 << LessParser.TIMES))) !== 0) || ((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (LessParser.IMPORT - 38)) | (1 << (LessParser.MEDIA - 38)) | (1 << (LessParser.Identifier - 38)))) !== 0)) { { { this.state = 88; this.statement(); } } this.state = 93; this._errHandler.sync(this); _la = this._input.LA(1); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public statement(): StatementContext { let _localctx: StatementContext = new StatementContext(this._ctx, this.state); this.enterRule(_localctx, 2, LessParser.RULE_statement); try { this.state = 101; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 1, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 94; this.importDeclaration(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 95; this.ruleset(); } break; case 3: this.enterOuterAlt(_localctx, 3); { this.state = 96; this.variableDeclaration(); this.state = 97; this.match(LessParser.SEMI); } break; case 4: this.enterOuterAlt(_localctx, 4); { this.state = 99; this.mixinDefinition(); } break; case 5: this.enterOuterAlt(_localctx, 5); { this.state = 100; this.media(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public media(): MediaContext { let _localctx: MediaContext = new MediaContext(this._ctx, this.state); this.enterRule(_localctx, 4, LessParser.RULE_media); try { this.enterOuterAlt(_localctx, 1); { this.state = 103; this.match(LessParser.MEDIA); this.state = 104; this.mediaQueryList(); this.state = 105; this.block(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaQueryList(): MediaQueryListContext { let _localctx: MediaQueryListContext = new MediaQueryListContext(this._ctx, this.state); this.enterRule(_localctx, 6, LessParser.RULE_mediaQueryList); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 115; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.InterpolationStart || _la === LessParser.LPAREN || ((((_la - 40)) & ~0x1F) === 0 && ((1 << (_la - 40)) & ((1 << (LessParser.MEDIAONLY - 40)) | (1 << (LessParser.NOT - 40)) | (1 << (LessParser.Identifier - 40)))) !== 0)) { { this.state = 107; this.mediaQuery(); this.state = 112; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA) { { { this.state = 108; this.match(LessParser.COMMA); this.state = 109; this.mediaQuery(); } } this.state = 114; this._errHandler.sync(this); _la = this._input.LA(1); } } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaQuery(): MediaQueryContext { let _localctx: MediaQueryContext = new MediaQueryContext(this._ctx, this.state); this.enterRule(_localctx, 8, LessParser.RULE_mediaQuery); let _la: number; try { this.state = 136; this._errHandler.sync(this); switch (this._input.LA(1)) { case LessParser.InterpolationStart: case LessParser.MEDIAONLY: case LessParser.NOT: case LessParser.Identifier: this.enterOuterAlt(_localctx, 1); { this.state = 118; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.MEDIAONLY || _la === LessParser.NOT) { { this.state = 117; _la = this._input.LA(1); if (!(_la === LessParser.MEDIAONLY || _la === LessParser.NOT)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } this.state = 120; this.mediaType(); this.state = 125; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.AND) { { { this.state = 121; this.match(LessParser.AND); this.state = 122; this.mediaExpression(); } } this.state = 127; this._errHandler.sync(this); _la = this._input.LA(1); } } break; case LessParser.LPAREN: this.enterOuterAlt(_localctx, 2); { this.state = 128; this.mediaExpression(); this.state = 133; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.AND) { { { this.state = 129; this.match(LessParser.AND); this.state = 130; this.mediaExpression(); } } this.state = 135; this._errHandler.sync(this); _la = this._input.LA(1); } } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaType(): MediaTypeContext { let _localctx: MediaTypeContext = new MediaTypeContext(this._ctx, this.state); this.enterRule(_localctx, 10, LessParser.RULE_mediaType); try { this.enterOuterAlt(_localctx, 1); { this.state = 138; this.identifier(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaExpression(): MediaExpressionContext { let _localctx: MediaExpressionContext = new MediaExpressionContext(this._ctx, this.state); this.enterRule(_localctx, 12, LessParser.RULE_mediaExpression); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 140; this.match(LessParser.LPAREN); this.state = 141; this.mediaFeature(); this.state = 144; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.COLON) { { this.state = 142; this.match(LessParser.COLON); this.state = 143; this.expression(); } } this.state = 146; this.match(LessParser.RPAREN); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaFeature(): MediaFeatureContext { let _localctx: MediaFeatureContext = new MediaFeatureContext(this._ctx, this.state); this.enterRule(_localctx, 14, LessParser.RULE_mediaFeature); try { this.enterOuterAlt(_localctx, 1); { this.state = 148; this.identifier(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public variableName(): VariableNameContext { let _localctx: VariableNameContext = new VariableNameContext(this._ctx, this.state); this.enterRule(_localctx, 16, LessParser.RULE_variableName); try { this.state = 154; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 9, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 150; this.match(LessParser.AT); this.state = 151; this.variableName(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 152; this.match(LessParser.AT); this.state = 153; this.match(LessParser.Identifier); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public commandStatement(): CommandStatementContext { let _localctx: CommandStatementContext = new CommandStatementContext(this._ctx, this.state); this.enterRule(_localctx, 18, LessParser.RULE_commandStatement); let _la: number; try { this.enterOuterAlt(_localctx, 1); { { this.state = 157; this._errHandler.sync(this); _la = this._input.LA(1); do { { { this.state = 156; this.expression(); } } this.state = 159; this._errHandler.sync(this); _la = this._input.LA(1); } while (_la === LessParser.InterpolationStart || _la === LessParser.AT || ((((_la - 37)) & ~0x1F) === 0 && ((1 << (_la - 37)) & ((1 << (LessParser.UrlStart - 37)) | (1 << (LessParser.Identifier - 37)) | (1 << (LessParser.StringLiteral - 37)) | (1 << (LessParser.Number - 37)) | (1 << (LessParser.Color - 37)))) !== 0)); } this.state = 162; this._errHandler.sync(this); _la = this._input.LA(1); if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << LessParser.PLUS) | (1 << LessParser.TIMES) | (1 << LessParser.DIV) | (1 << LessParser.MINUS) | (1 << LessParser.PERC))) !== 0)) { { this.state = 161; this.mathStatement(); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mathCharacter(): MathCharacterContext { let _localctx: MathCharacterContext = new MathCharacterContext(this._ctx, this.state); this.enterRule(_localctx, 20, LessParser.RULE_mathCharacter); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 164; _la = this._input.LA(1); if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << LessParser.PLUS) | (1 << LessParser.TIMES) | (1 << LessParser.DIV) | (1 << LessParser.MINUS) | (1 << LessParser.PERC))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mathStatement(): MathStatementContext { let _localctx: MathStatementContext = new MathStatementContext(this._ctx, this.state); this.enterRule(_localctx, 22, LessParser.RULE_mathStatement); try { this.enterOuterAlt(_localctx, 1); { this.state = 166; this.mathCharacter(); this.state = 167; this.commandStatement(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public expression(): ExpressionContext { let _localctx: ExpressionContext = new ExpressionContext(this._ctx, this.state); this.enterRule(_localctx, 24, LessParser.RULE_expression); let _la: number; try { this.state = 190; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 13, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 169; this.measurement(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 170; this.identifier(); this.state = 171; this.match(LessParser.IMPORTANT); } break; case 3: this.enterOuterAlt(_localctx, 3); { this.state = 173; this.identifier(); } break; case 4: this.enterOuterAlt(_localctx, 4); { this.state = 174; this.identifier(); this.state = 175; this.match(LessParser.LPAREN); this.state = 177; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.InterpolationStart || _la === LessParser.AT || ((((_la - 37)) & ~0x1F) === 0 && ((1 << (_la - 37)) & ((1 << (LessParser.UrlStart - 37)) | (1 << (LessParser.Identifier - 37)) | (1 << (LessParser.StringLiteral - 37)) | (1 << (LessParser.Number - 37)) | (1 << (LessParser.Color - 37)))) !== 0)) { { this.state = 176; this.values(); } } this.state = 179; this.match(LessParser.RPAREN); } break; case 5: this.enterOuterAlt(_localctx, 5); { this.state = 181; this.match(LessParser.Color); this.state = 182; this.match(LessParser.IMPORTANT); } break; case 6: this.enterOuterAlt(_localctx, 6); { this.state = 183; this.match(LessParser.Color); } break; case 7: this.enterOuterAlt(_localctx, 7); { this.state = 184; this.match(LessParser.StringLiteral); } break; case 8: this.enterOuterAlt(_localctx, 8); { this.state = 185; this.url(); } break; case 9: this.enterOuterAlt(_localctx, 9); { this.state = 186; this.variableName(); this.state = 187; this.match(LessParser.IMPORTANT); } break; case 10: this.enterOuterAlt(_localctx, 10); { this.state = 189; this.variableName(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public func(): FuncContext { let _localctx: FuncContext = new FuncContext(this._ctx, this.state); this.enterRule(_localctx, 26, LessParser.RULE_func); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 192; this.match(LessParser.FUNCTION_NAME); this.state = 193; this.match(LessParser.LPAREN); this.state = 195; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.InterpolationStart || _la === LessParser.AT || ((((_la - 37)) & ~0x1F) === 0 && ((1 << (_la - 37)) & ((1 << (LessParser.UrlStart - 37)) | (1 << (LessParser.Identifier - 37)) | (1 << (LessParser.StringLiteral - 37)) | (1 << (LessParser.Number - 37)) | (1 << (LessParser.Color - 37)))) !== 0)) { { this.state = 194; this.values(); } } this.state = 197; this.match(LessParser.RPAREN); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public conditions(): ConditionsContext { let _localctx: ConditionsContext = new ConditionsContext(this._ctx, this.state); this.enterRule(_localctx, 28, LessParser.RULE_conditions); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 199; this.condition(); this.state = 204; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA || _la === LessParser.AND) { { { this.state = 200; _la = this._input.LA(1); if (!(_la === LessParser.COMMA || _la === LessParser.AND)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } this.state = 201; this.condition(); } } this.state = 206; this._errHandler.sync(this); _la = this._input.LA(1); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public condition(): ConditionContext { let _localctx: ConditionContext = new ConditionContext(this._ctx, this.state); this.enterRule(_localctx, 30, LessParser.RULE_condition); try { this.state = 216; this._errHandler.sync(this); switch (this._input.LA(1)) { case LessParser.LPAREN: this.enterOuterAlt(_localctx, 1); { this.state = 207; this.match(LessParser.LPAREN); this.state = 208; this.conditionStatement(); this.state = 209; this.match(LessParser.RPAREN); } break; case LessParser.NOT: this.enterOuterAlt(_localctx, 2); { this.state = 211; this.match(LessParser.NOT); this.state = 212; this.match(LessParser.LPAREN); this.state = 213; this.conditionStatement(); this.state = 214; this.match(LessParser.RPAREN); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public conditionStatement(): ConditionStatementContext { let _localctx: ConditionStatementContext = new ConditionStatementContext(this._ctx, this.state); this.enterRule(_localctx, 32, LessParser.RULE_conditionStatement); let _la: number; try { this.state = 223; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 17, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 218; this.commandStatement(); this.state = 219; _la = this._input.LA(1); if (!(((((_la - 12)) & ~0x1F) === 0 && ((1 << (_la - 12)) & ((1 << (LessParser.GT - 12)) | (1 << (LessParser.LT - 12)) | (1 << (LessParser.GTEQ - 12)) | (1 << (LessParser.LTEQ - 12)) | (1 << (LessParser.EQ - 12)))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } this.state = 220; this.commandStatement(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 222; this.commandStatement(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public variableDeclaration(): VariableDeclarationContext { let _localctx: VariableDeclarationContext = new VariableDeclarationContext(this._ctx, this.state); this.enterRule(_localctx, 34, LessParser.RULE_variableDeclaration); try { this.enterOuterAlt(_localctx, 1); { this.state = 225; this.variableName(); this.state = 226; this.match(LessParser.COLON); this.state = 227; this.values(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public importDeclaration(): ImportDeclarationContext { let _localctx: ImportDeclarationContext = new ImportDeclarationContext(this._ctx, this.state); this.enterRule(_localctx, 36, LessParser.RULE_importDeclaration); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 229; this.match(LessParser.IMPORT); this.state = 241; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.LPAREN) { { this.state = 230; this.match(LessParser.LPAREN); { this.state = 231; this.importOption(); this.state = 236; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA) { { { this.state = 232; this.match(LessParser.COMMA); this.state = 233; this.importOption(); } } this.state = 238; this._errHandler.sync(this); _la = this._input.LA(1); } } this.state = 239; this.match(LessParser.RPAREN); } } this.state = 243; this.referenceUrl(); this.state = 245; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.Identifier) { { this.state = 244; this.mediaTypes(); } } this.state = 247; this.match(LessParser.SEMI); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public importOption(): ImportOptionContext { let _localctx: ImportOptionContext = new ImportOptionContext(this._ctx, this.state); this.enterRule(_localctx, 38, LessParser.RULE_importOption); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 249; _la = this._input.LA(1); if (!(((((_la - 45)) & ~0x1F) === 0 && ((1 << (_la - 45)) & ((1 << (LessParser.REFERENCE - 45)) | (1 << (LessParser.INLINE - 45)) | (1 << (LessParser.LESS - 45)) | (1 << (LessParser.CSS - 45)) | (1 << (LessParser.ONCE - 45)) | (1 << (LessParser.MULTIPLE - 45)))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public referenceUrl(): ReferenceUrlContext { let _localctx: ReferenceUrlContext = new ReferenceUrlContext(this._ctx, this.state); this.enterRule(_localctx, 40, LessParser.RULE_referenceUrl); try { this.state = 255; this._errHandler.sync(this); switch (this._input.LA(1)) { case LessParser.StringLiteral: this.enterOuterAlt(_localctx, 1); { this.state = 251; this.match(LessParser.StringLiteral); } break; case LessParser.UrlStart: this.enterOuterAlt(_localctx, 2); { this.state = 252; this.match(LessParser.UrlStart); this.state = 253; this.match(LessParser.Url); this.state = 254; this.match(LessParser.UrlEnd); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mediaTypes(): MediaTypesContext { let _localctx: MediaTypesContext = new MediaTypesContext(this._ctx, this.state); this.enterRule(_localctx, 42, LessParser.RULE_mediaTypes); let _la: number; try { this.enterOuterAlt(_localctx, 1); { { this.state = 257; this.match(LessParser.Identifier); this.state = 262; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA) { { { this.state = 258; this.match(LessParser.COMMA); this.state = 259; this.match(LessParser.Identifier); } } this.state = 264; this._errHandler.sync(this); _la = this._input.LA(1); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public ruleset(): RulesetContext { let _localctx: RulesetContext = new RulesetContext(this._ctx, this.state); this.enterRule(_localctx, 44, LessParser.RULE_ruleset); try { this.enterOuterAlt(_localctx, 1); { this.state = 265; this.selectors(); this.state = 266; this.block(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public block(): BlockContext { let _localctx: BlockContext = new BlockContext(this._ctx, this.state); this.enterRule(_localctx, 46, LessParser.RULE_block); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 268; this.match(LessParser.BlockStart); this.state = 272; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 23, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 269; this.blockItem(); } } } this.state = 274; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 23, this._ctx); } this.state = 276; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.InterpolationStart || _la === LessParser.Identifier) { { this.state = 275; this.property(); } } this.state = 278; this.match(LessParser.BlockEnd); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public blockItem(): BlockItemContext { let _localctx: BlockItemContext = new BlockItemContext(this._ctx, this.state); this.enterRule(_localctx, 48, LessParser.RULE_blockItem); try { this.state = 285; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 25, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 280; this.property(); this.state = 281; this.match(LessParser.SEMI); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 283; this.statement(); } break; case 3: this.enterOuterAlt(_localctx, 3); { this.state = 284; this.mixinReference(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mixinDefinition(): MixinDefinitionContext { let _localctx: MixinDefinitionContext = new MixinDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 50, LessParser.RULE_mixinDefinition); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 287; this.selectors(); this.state = 288; this.match(LessParser.LPAREN); this.state = 297; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.AT) { { this.state = 289; this.mixinDefinitionParam(); this.state = 294; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.SEMI) { { { this.state = 290; this.match(LessParser.SEMI); this.state = 291; this.mixinDefinitionParam(); } } this.state = 296; this._errHandler.sync(this); _la = this._input.LA(1); } } } this.state = 300; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.Ellipsis) { { this.state = 299; this.match(LessParser.Ellipsis); } } this.state = 302; this.match(LessParser.RPAREN); this.state = 304; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.WHEN) { { this.state = 303; this.mixinGuard(); } } this.state = 306; this.block(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mixinGuard(): MixinGuardContext { let _localctx: MixinGuardContext = new MixinGuardContext(this._ctx, this.state); this.enterRule(_localctx, 52, LessParser.RULE_mixinGuard); try { this.enterOuterAlt(_localctx, 1); { this.state = 308; this.match(LessParser.WHEN); this.state = 309; this.conditions(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mixinDefinitionParam(): MixinDefinitionParamContext { let _localctx: MixinDefinitionParamContext = new MixinDefinitionParamContext(this._ctx, this.state); this.enterRule(_localctx, 54, LessParser.RULE_mixinDefinitionParam); try { this.state = 313; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 30, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 311; this.variableName(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 312; this.variableDeclaration(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public mixinReference(): MixinReferenceContext { let _localctx: MixinReferenceContext = new MixinReferenceContext(this._ctx, this.state); this.enterRule(_localctx, 56, LessParser.RULE_mixinReference); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 315; this.selector(); this.state = 316; this.match(LessParser.LPAREN); this.state = 318; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.InterpolationStart || _la === LessParser.AT || ((((_la - 37)) & ~0x1F) === 0 && ((1 << (_la - 37)) & ((1 << (LessParser.UrlStart - 37)) | (1 << (LessParser.Identifier - 37)) | (1 << (LessParser.StringLiteral - 37)) | (1 << (LessParser.Number - 37)) | (1 << (LessParser.Color - 37)))) !== 0)) { { this.state = 317; this.values(); } } this.state = 320; this.match(LessParser.RPAREN); this.state = 322; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.IMPORTANT) { { this.state = 321; this.match(LessParser.IMPORTANT); } } this.state = 324; this.match(LessParser.SEMI); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public selectors(): SelectorsContext { let _localctx: SelectorsContext = new SelectorsContext(this._ctx, this.state); this.enterRule(_localctx, 58, LessParser.RULE_selectors); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 326; this.selector(); this.state = 331; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA) { { { this.state = 327; this.match(LessParser.COMMA); this.state = 328; this.selector(); } } this.state = 333; this._errHandler.sync(this); _la = this._input.LA(1); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public selector(): SelectorContext { let _localctx: SelectorContext = new SelectorContext(this._ctx, this.state); this.enterRule(_localctx, 60, LessParser.RULE_selector); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 335; this._errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { this.state = 334; this.element(); } } break; default: throw new NoViableAltException(this); } this.state = 337; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 34, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); this.state = 342; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.LBRACK) { { { this.state = 339; this.attrib(); } } this.state = 344; this._errHandler.sync(this); _la = this._input.LA(1); } this.state = 346; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.COLON || _la === LessParser.COLONCOLON) { { this.state = 345; this.pseudo(); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public attrib(): AttribContext { let _localctx: AttribContext = new AttribContext(this._ctx, this.state); this.enterRule(_localctx, 62, LessParser.RULE_attrib); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 348; this.match(LessParser.LBRACK); this.state = 349; this.match(LessParser.Identifier); this.state = 353; this._errHandler.sync(this); _la = this._input.LA(1); if (((((_la - 33)) & ~0x1F) === 0 && ((1 << (_la - 33)) & ((1 << (LessParser.EQ - 33)) | (1 << (LessParser.PIPE_EQ - 33)) | (1 << (LessParser.TILD_EQ - 33)))) !== 0)) { { this.state = 350; this.attribRelate(); this.state = 351; _la = this._input.LA(1); if (!(_la === LessParser.Identifier || _la === LessParser.StringLiteral)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } this.state = 355; this.match(LessParser.RBRACK); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public negation(): NegationContext { let _localctx: NegationContext = new NegationContext(this._ctx, this.state); this.enterRule(_localctx, 64, LessParser.RULE_negation); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 357; this.match(LessParser.COLON); this.state = 358; this.match(LessParser.NOT); this.state = 359; this.match(LessParser.LPAREN); this.state = 361; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.LBRACK) { { this.state = 360; this.match(LessParser.LBRACK); } } this.state = 363; this.selectors(); this.state = 365; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.RBRACK) { { this.state = 364; this.match(LessParser.RBRACK); } } this.state = 367; this.match(LessParser.RPAREN); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public pseudo(): PseudoContext { let _localctx: PseudoContext = new PseudoContext(this._ctx, this.state); this.enterRule(_localctx, 66, LessParser.RULE_pseudo); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 369; _la = this._input.LA(1); if (!(_la === LessParser.COLON || _la === LessParser.COLONCOLON)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } this.state = 370; this.match(LessParser.Identifier); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public element(): ElementContext { let _localctx: ElementContext = new ElementContext(this._ctx, this.state); this.enterRule(_localctx, 68, LessParser.RULE_element); try { this.state = 382; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 40, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 372; this.selectorPrefix(); this.state = 373; this.identifier(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 375; this.identifier(); } break; case 3: this.enterOuterAlt(_localctx, 3); { this.state = 376; this.match(LessParser.HASH); this.state = 377; this.identifier(); } break; case 4: this.enterOuterAlt(_localctx, 4); { this.state = 378; this.pseudo(); } break; case 5: this.enterOuterAlt(_localctx, 5); { this.state = 379; this.negation(); } break; case 6: this.enterOuterAlt(_localctx, 6); { this.state = 380; this.match(LessParser.PARENTREF); } break; case 7: this.enterOuterAlt(_localctx, 7); { this.state = 381; this.match(LessParser.TIMES); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public selectorPrefix(): SelectorPrefixContext { let _localctx: SelectorPrefixContext = new SelectorPrefixContext(this._ctx, this.state); this.enterRule(_localctx, 70, LessParser.RULE_selectorPrefix); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 384; _la = this._input.LA(1); if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << LessParser.GT) | (1 << LessParser.TIL) | (1 << LessParser.PLUS))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public attribRelate(): AttribRelateContext { let _localctx: AttribRelateContext = new AttribRelateContext(this._ctx, this.state); this.enterRule(_localctx, 72, LessParser.RULE_attribRelate); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 386; _la = this._input.LA(1); if (!(((((_la - 33)) & ~0x1F) === 0 && ((1 << (_la - 33)) & ((1 << (LessParser.EQ - 33)) | (1 << (LessParser.PIPE_EQ - 33)) | (1 << (LessParser.TILD_EQ - 33)))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public identifier(): IdentifierContext { let _localctx: IdentifierContext = new IdentifierContext(this._ctx, this.state); this.enterRule(_localctx, 74, LessParser.RULE_identifier); let _la: number; try { this.state = 404; this._errHandler.sync(this); switch (this._input.LA(1)) { case LessParser.Identifier: this.enterOuterAlt(_localctx, 1); { this.state = 388; this.match(LessParser.Identifier); this.state = 392; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.InterpolationStartAfter || _la === LessParser.IdentifierAfter) { { { this.state = 389; this.identifierPart(); } } this.state = 394; this._errHandler.sync(this); _la = this._input.LA(1); } } break; case LessParser.InterpolationStart: this.enterOuterAlt(_localctx, 2); { this.state = 395; this.match(LessParser.InterpolationStart); this.state = 396; this.identifierVariableName(); this.state = 397; this.match(LessParser.BlockEnd); this.state = 401; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.InterpolationStartAfter || _la === LessParser.IdentifierAfter) { { { this.state = 398; this.identifierPart(); } } this.state = 403; this._errHandler.sync(this); _la = this._input.LA(1); } } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public identifierPart(): IdentifierPartContext { let _localctx: IdentifierPartContext = new IdentifierPartContext(this._ctx, this.state); this.enterRule(_localctx, 76, LessParser.RULE_identifierPart); try { this.state = 411; this._errHandler.sync(this); switch (this._input.LA(1)) { case LessParser.InterpolationStartAfter: this.enterOuterAlt(_localctx, 1); { this.state = 406; this.match(LessParser.InterpolationStartAfter); this.state = 407; this.identifierVariableName(); this.state = 408; this.match(LessParser.BlockEnd); } break; case LessParser.IdentifierAfter: this.enterOuterAlt(_localctx, 2); { this.state = 410; this.match(LessParser.IdentifierAfter); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public identifierVariableName(): IdentifierVariableNameContext { let _localctx: IdentifierVariableNameContext = new IdentifierVariableNameContext(this._ctx, this.state); this.enterRule(_localctx, 78, LessParser.RULE_identifierVariableName); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 413; _la = this._input.LA(1); if (!(_la === LessParser.Identifier || _la === LessParser.IdentifierAfter)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public property(): PropertyContext { let _localctx: PropertyContext = new PropertyContext(this._ctx, this.state); this.enterRule(_localctx, 80, LessParser.RULE_property); try { this.enterOuterAlt(_localctx, 1); { this.state = 415; this.identifier(); this.state = 416; this.match(LessParser.COLON); this.state = 417; this.values(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public values(): ValuesContext { let _localctx: ValuesContext = new ValuesContext(this._ctx, this.state); this.enterRule(_localctx, 82, LessParser.RULE_values); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 419; this.commandStatement(); this.state = 424; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LessParser.COMMA) { { { this.state = 420; this.match(LessParser.COMMA); this.state = 421; this.commandStatement(); } } this.state = 426; this._errHandler.sync(this); _la = this._input.LA(1); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public url(): UrlContext { let _localctx: UrlContext = new UrlContext(this._ctx, this.state); this.enterRule(_localctx, 84, LessParser.RULE_url); try { this.enterOuterAlt(_localctx, 1); { this.state = 427; this.match(LessParser.UrlStart); this.state = 428; this.match(LessParser.Url); this.state = 429; this.match(LessParser.UrlEnd); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public measurement(): MeasurementContext { let _localctx: MeasurementContext = new MeasurementContext(this._ctx, this.state); this.enterRule(_localctx, 86, LessParser.RULE_measurement); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 431; this.match(LessParser.Number); this.state = 433; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LessParser.Unit) { { this.state = 432; this.match(LessParser.Unit); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x91\u01B6\x04" + "\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04" + "\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r" + "\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12" + "\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t\x17" + "\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t\x1C" + "\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04 \t \x04!\t!\x04\"\t\"\x04" + "#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(\t(\x04)\t)\x04*\t*\x04+\t" + "+\x04,\t,\x04-\t-\x03\x02\x07\x02\\\n\x02\f\x02\x0E\x02_\v\x02\x03\x03" + "\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x05\x03h\n\x03\x03\x04" + "\x03\x04\x03\x04\x03\x04\x03\x05\x03\x05\x03\x05\x07\x05q\n\x05\f\x05" + "\x0E\x05t\v\x05\x05\x05v\n\x05\x03\x06\x05\x06y\n\x06\x03\x06\x03\x06" + "\x03\x06\x07\x06~\n\x06\f\x06\x0E\x06\x81\v\x06\x03\x06\x03\x06\x03\x06" + "\x07\x06\x86\n\x06\f\x06\x0E\x06\x89\v\x06\x05\x06\x8B\n\x06\x03\x07\x03" + "\x07\x03\b\x03\b\x03\b\x03\b\x05\b\x93\n\b\x03\b\x03\b\x03\t\x03\t\x03" + "\n\x03\n\x03\n\x03\n\x05\n\x9D\n\n\x03\v\x06\v\xA0\n\v\r\v\x0E\v\xA1\x03" + "\v\x05\v\xA5\n\v\x03\f\x03\f\x03\r\x03\r\x03\r\x03\x0E\x03\x0E\x03\x0E" + "\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x05\x0E\xB4\n\x0E\x03\x0E\x03" + "\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03" + "\x0E\x05\x0E\xC1\n\x0E\x03\x0F\x03\x0F\x03\x0F\x05\x0F\xC6\n\x0F\x03\x0F" + "\x03\x0F\x03\x10\x03\x10\x03\x10\x07\x10\xCD\n\x10\f\x10\x0E\x10\xD0\v" + "\x10\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03" + "\x11\x05\x11\xDB\n\x11\x03\x12\x03\x12\x03\x12\x03\x12\x03\x12\x05\x12" + "\xE2\n\x12\x03\x13\x03\x13\x03\x13\x03\x13\x03\x14\x03\x14\x03\x14\x03" + "\x14\x03\x14\x07\x14\xED\n\x14\f\x14\x0E\x14\xF0\v\x14\x03\x14\x03\x14" + "\x05\x14\xF4\n\x14\x03\x14\x03\x14\x05\x14\xF8\n\x14\x03\x14\x03\x14\x03" + "\x15\x03\x15\x03\x16\x03\x16\x03\x16\x03\x16\x05\x16\u0102\n\x16\x03\x17" + "\x03\x17\x03\x17\x07\x17\u0107\n\x17\f\x17\x0E\x17\u010A\v\x17\x03\x18" + "\x03\x18\x03\x18\x03\x19\x03\x19\x07\x19\u0111\n\x19\f\x19\x0E\x19\u0114" + "\v\x19\x03\x19\x05\x19\u0117\n\x19\x03\x19\x03\x19\x03\x1A\x03\x1A\x03" + "\x1A\x03\x1A\x03\x1A\x05\x1A\u0120\n\x1A\x03\x1B\x03\x1B\x03\x1B\x03\x1B" + "\x03\x1B\x07\x1B\u0127\n\x1B\f\x1B\x0E\x1B\u012A\v\x1B\x05\x1B\u012C\n" + "\x1B\x03\x1B\x05\x1B\u012F\n\x1B\x03\x1B\x03\x1B\x05\x1B\u0133\n\x1B\x03" + "\x1B\x03\x1B\x03\x1C\x03\x1C\x03\x1C\x03\x1D\x03\x1D\x05\x1D\u013C\n\x1D" + "\x03\x1E\x03\x1E\x03\x1E\x05\x1E\u0141\n\x1E\x03\x1E\x03\x1E\x05\x1E\u0145" + "\n\x1E\x03\x1E\x03\x1E\x03\x1F\x03\x1F\x03\x1F\x07\x1F\u014C\n\x1F\f\x1F" + "\x0E\x1F\u014F\v\x1F\x03 \x06 \u0152\n \r \x0E \u0153\x03 \x07 \u0157" + "\n \f \x0E \u015A\v \x03 \x05 \u015D\n \x03!\x03!\x03!\x03!\x03!\x05!" + "\u0164\n!\x03!\x03!\x03\"\x03\"\x03\"\x03\"\x05\"\u016C\n\"\x03\"\x03" + "\"\x05\"\u0170\n\"\x03\"\x03\"\x03#\x03#\x03#\x03$\x03$\x03$\x03$\x03" + "$\x03$\x03$\x03$\x03$\x03$\x05$\u0181\n$\x03%\x03%\x03&\x03&\x03\'\x03" + "\'\x07\'\u0189\n\'\f\'\x0E\'\u018C\v\'\x03\'\x03\'\x03\'\x03\'\x07\'\u0192" + "\n\'\f\'\x0E\'\u0195\v\'\x05\'\u0197\n\'\x03(\x03(\x03(\x03(\x03(\x05" + "(\u019E\n(\x03)\x03)\x03*\x03*\x03*\x03*\x03+\x03+\x03+\x07+\u01A9\n+" + "\f+\x0E+\u01AC\v+\x03,\x03,\x03,\x03,\x03-\x03-\x05-\u01B4\n-\x03-\x02" + "\x02\x02.\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10\x02\x12" + "\x02\x14\x02\x16\x02\x18\x02\x1A\x02\x1C\x02\x1E\x02 \x02\"\x02$\x02&" + "\x02(\x02*\x02,\x02.\x020\x022\x024\x026\x028\x02:\x02<\x02>\x02@\x02" + "B\x02D\x02F\x02H\x02J\x02L\x02N\x02P\x02R\x02T\x02V\x02X\x02\x02\f\x04" + "\x02**66\x03\x02\x1A\x1E\x04\x02\x13\x1377\x06\x02\x0E\x0E\x10\x10 !#" + "#\x03\x02/4\x03\x0289\x04\x02\x11\x11\x19\x19\x04\x02\x0E\x0F\x1A\x1A" + "\x03\x02#%\x04\x0288\x91\x91\x02\u01C9\x02]\x03\x02\x02\x02\x04g\x03\x02" + "\x02\x02\x06i\x03\x02\x02\x02\bu\x03\x02\x02\x02\n\x8A\x03\x02\x02\x02" + "\f\x8C\x03\x02\x02\x02\x0E\x8E\x03\x02\x02\x02\x10\x96\x03\x02\x02\x02" + "\x12\x9C\x03\x02\x02\x02\x14\x9F\x03\x02\x02\x02\x16\xA6\x03\x02\x02\x02" + "\x18\xA8\x03\x02\x02\x02\x1A\xC0\x03\x02\x02\x02\x1C\xC2\x03\x02\x02\x02" + "\x1E\xC9\x03\x02\x02\x02 \xDA\x03\x02\x02\x02\"\xE1\x03\x02\x02\x02$\xE3" + "\x03\x02\x02\x02&\xE7\x03\x02\x02\x02(\xFB\x03\x02\x02\x02*\u0101\x03" + "\x02\x02\x02,\u0103\x03\x02\x02\x02.\u010B\x03\x02\x02\x020\u010E\x03" + "\x02\x02\x022\u011F\x03\x02\x02\x024\u0121\x03\x02\x02\x026\u0136\x03" + "\x02\x02\x028\u013B\x03\x02\x02\x02:\u013D\x03\x02\x02\x02<\u0148\x03" + "\x02\x02\x02>\u0151\x03\x02\x02\x02@\u015E\x03\x02\x02\x02B\u0167\x03" + "\x02\x02\x02D\u0173\x03\x02\x02\x02F\u0180\x03\x02\x02\x02H\u0182\x03" + "\x02\x02\x02J\u0184\x03\x02\x02\x02L\u0196\x03\x02\x02\x02N\u019D\x03" + "\x02\x02\x02P\u019F\x03\x02\x02\x02R\u01A1\x03\x02\x02\x02T\u01A5\x03" + "\x02\x02\x02V\u01AD\x03\x02\x02\x02X\u01B1\x03\x02\x02\x02Z\\\x05\x04" + "\x03\x02[Z\x03\x02\x02\x02\\_\x03\x02\x02\x02][\x03\x02\x02\x02]^\x03" + "\x02\x02\x02^\x03\x03\x02\x02\x02_]\x03\x02\x02\x02`h\x05&\x14\x02ah\x05" + ".\x18\x02bc\x05$\x13\x02cd\x07\x12\x02\x02dh\x03\x02\x02\x02eh\x054\x1B" + "\x02fh\x05\x06\x04\x02g`\x03\x02\x02\x02ga\x03\x02\x02\x02gb\x03\x02\x02" + "\x02ge\x03\x02\x02\x02gf\x03\x02\x02\x02h\x05\x03\x02\x02\x02ij\x07)\x02" + "\x02jk\x05\b\x05\x02kl\x050\x19\x02l\x07\x03\x02\x02\x02mr\x05\n\x06\x02" + "no\x07\x13\x02\x02oq\x05\n\x06\x02pn\x03\x02\x02\x02qt\x03\x02\x02\x02" + "rp\x03\x02\x02\x02rs\x03\x02\x02\x02sv\x03\x02\x02\x02tr\x03\x02\x02\x02" + "um\x03\x02\x02\x02uv\x03\x02\x02\x02v\t\x03\x02\x02\x02wy\t\x02\x02\x02" + "xw\x03\x02\x02\x02xy\x03\x02\x02\x02yz\x03\x02\x02\x02z\x7F\x05\f\x07" + "\x02{|\x077\x02\x02|~\x05\x0E\b\x02}{\x03\x02\x02\x02~\x81\x03\x02\x02" + "\x02\x7F}\x03\x02\x02\x02\x7F\x80\x03\x02\x02\x02\x80\x8B\x03\x02\x02" + "\x02\x81\x7F\x03\x02\x02\x02\x82\x87\x05\x0E\b\x02\x83\x84\x077\x02\x02" + "\x84\x86\x05\x0E\b\x02\x85\x83\x03\x02\x02\x02\x86\x89\x03\x02\x02\x02" + "\x87\x85\x03\x02\x02\x02\x87\x88\x03\x02\x02\x02\x88\x8B\x03\x02\x02\x02" + "\x89\x87\x03\x02\x02\x02\x8Ax\x03\x02\x02\x02\x8A\x82\x03\x02\x02\x02" + "\x8B\v\x03\x02\x02\x02\x8C\x8D\x05L\'\x02\x8D\r\x03\x02\x02\x02\x8E\x8F" + "\x07\b\x02\x02\x8F\x92\x05\x10\t\x02\x90\x91\x07\x11\x02\x02\x91\x93\x05" + "\x1A\x0E\x02\x92\x90\x03\x02\x02\x02\x92\x93\x03\x02\x02\x02\x93\x94\x03" + "\x02\x02\x02\x94\x95\x07\t\x02\x02\x95\x0F\x03\x02\x02\x02\x96\x97\x05" + "L\'\x02\x97\x11\x03\x02\x02\x02\x98\x99\x07\x16\x02\x02\x99\x9D\x05\x12" + "\n\x02\x9A\x9B\x07\x16\x02\x02\x9B\x9D\x078\x02\x02\x9C\x98\x03\x02\x02" + "\x02\x9C\x9A\x03\x02\x02\x02\x9D\x13\x03\x02\x02\x02\x9E\xA0\x05\x1A\x0E" + "\x02\x9F\x9E\x03\x02\x02\x02\xA0\xA1\x03\x02\x02\x02\xA1\x9F\x03\x02\x02" + "\x02\xA1\xA2\x03\x02\x02\x02\xA2\xA4\x03\x02\x02\x02\xA3\xA5\x05\x18\r" + "\x02\xA4\xA3\x03\x02\x02\x02\xA4\xA5\x03\x02\x02\x02\xA5\x15\x03\x02\x02" + "\x02\xA6\xA7\t\x03\x02\x02\xA7\x17\x03\x02\x02\x02\xA8\xA9\x05\x16\f\x02" + "\xA9\xAA\x05\x14\v\x02\xAA\x19\x03\x02\x02\x02\xAB\xC1\x05X-\x02\xAC\xAD" + "\x05L\'\x02\xAD\xAE\x07,\x02\x02\xAE\xC1\x03\x02\x02\x02\xAF\xC1\x05L" + "\'\x02\xB0\xB1\x05L\'\x02\xB1\xB3\x07\b\x02\x02\xB2\xB4\x05T+\x02\xB3" + "\xB2\x03\x02\x02\x02\xB3\xB4\x03\x02\x02\x02\xB4\xB5\x03\x02\x02\x02\xB5" + "\xB6\x07\t\x02\x02\xB6\xC1\x03\x02\x02\x02\xB7\xB8\x07;\x02\x02\xB8\xC1" + "\x07,\x02\x02\xB9\xC1\x07;\x02\x02\xBA\xC1\x079\x02\x02\xBB\xC1\x05V," + "\x02\xBC\xBD\x05\x12\n\x02\xBD\xBE\x07,\x02\x02\xBE\xC1\x03\x02\x02\x02" + "\xBF\xC1\x05\x12\n\x02\xC0\xAB\x03\x02\x02\x02\xC0\xAC\x03\x02\x02\x02" + "\xC0\xAF\x03\x02\x02\x02\xC0\xB0\x03\x02\x02\x02\xC0\xB7\x03\x02\x02\x02" + "\xC0\xB9\x03\x02\x02\x02\xC0\xBA\x03\x02\x02\x02\xC0\xBB\x03\x02\x02\x02" + "\xC0\xBC\x03\x02\x02\x02\xC0\xBF\x03\x02\x02\x02\xC1\x1B\x03\x02\x02\x02" + "\xC2\xC3\x07?\x02\x02\xC3\xC5\x07\b\x02\x02\xC4\xC6\x05T+\x02\xC5\xC4" + "\x03\x02\x02\x02\xC5\xC6\x03\x02\x02\x02\xC6\xC7\x03\x02\x02\x02\xC7\xC8" + "\x07\t\x02\x02\xC8\x1D\x03\x02\x02\x02\xC9\xCE\x05 \x11\x02\xCA\xCB\t" + "\x04\x02\x02\xCB\xCD\x05 \x11\x02\xCC\xCA\x03\x02\x02\x02\xCD\xD0\x03" + "\x02\x02\x02\xCE\xCC\x03\x02\x02\x02\xCE\xCF\x03\x02\x02\x02\xCF\x1F\x03" + "\x02\x02\x02\xD0\xCE\x03\x02\x02\x02\xD1\xD2\x07\b\x02\x02\xD2\xD3\x05" + "\"\x12\x02\xD3\xD4\x07\t\x02\x02\xD4\xDB\x03\x02\x02\x02\xD5\xD6\x076" + "\x02\x02\xD6\xD7\x07\b\x02\x02\xD7\xD8\x05\"\x12\x02\xD8\xD9\x07\t\x02" + "\x02\xD9\xDB\x03\x02\x02\x02\xDA\xD1\x03\x02\x02\x02\xDA\xD5\x03\x02\x02" + "\x02\xDB!\x03\x02\x02\x02\xDC\xDD\x05\x14\v\x02\xDD\xDE\t\x05\x02\x02" + "\xDE\xDF\x05\x14\v\x02\xDF\xE2\x03\x02\x02\x02\xE0\xE2\x05\x14\v\x02\xE1" + "\xDC\x03\x02\x02\x02\xE1\xE0\x03\x02\x02\x02\xE2#\x03\x02\x02\x02\xE3" + "\xE4\x05\x12\n\x02\xE4\xE5\x07\x11\x02\x02\xE5\xE6\x05T+\x02\xE6%\x03" + "\x02\x02\x02\xE7\xF3\x07(\x02\x02\xE8\xE9\x07\b\x02\x02\xE9\xEE\x05(\x15" + "\x02\xEA\xEB\x07\x13\x02\x02\xEB\xED\x05(\x15\x02\xEC\xEA\x03\x02\x02" + "\x02\xED\xF0\x03\x02\x02\x02\xEE\xEC\x03\x02\x02\x02\xEE\xEF\x03\x02\x02" + "\x02\xEF\xF1\x03\x02\x02\x02\xF0\xEE\x03\x02\x02\x02\xF1\xF2\x07\t\x02" + "\x02\xF2\xF4\x03\x02\x02\x02\xF3\xE8\x03\x02\x02\x02\xF3\xF4\x03\x02\x02" + "\x02\xF4\xF5\x03\x02\x02\x02\xF5\xF7\x05*\x16\x02\xF6\xF8\x05,\x17\x02" + "\xF7\xF6\x03\x02\x02\x02\xF7\xF8\x03\x02\x02\x02\xF8\xF9\x03\x02\x02\x02" + "\xF9\xFA\x07\x12\x02\x02\xFA\'\x03\x02\x02\x02\xFB\xFC\t\x06\x02\x02\xFC" + ")\x03\x02\x02\x02\xFD\u0102\x079\x02\x02\xFE\xFF\x07\'\x02\x02\xFF\u0100" + "\x07\x8E\x02\x02\u0100\u0102\x07\x8D\x02\x02\u0101\xFD\x03\x02\x02\x02" + "\u0101\xFE\x03\x02\x02\x02\u0102+\x03\x02\x02\x02\u0103\u0108\x078\x02" + "\x02\u0104\u0105\x07\x13\x02\x02\u0105\u0107\x078\x02\x02\u0106\u0104" + "\x03\x02\x02\x02\u0107\u010A\x03\x02\x02\x02\u0108\u0106\x03\x02\x02\x02" + "\u0108\u0109\x03\x02\x02\x02\u0109-\x03\x02\x02\x02\u010A\u0108\x03\x02" + "\x02\x02\u010B\u010C\x05<\x1F\x02\u010C\u010D\x050\x19\x02\u010D/\x03" + "\x02\x02\x02\u010E\u0112\x07\n\x02\x02\u010F\u0111\x052\x1A\x02\u0110" + "\u010F\x03\x02\x02\x02\u0111\u0114\x03\x02\x02\x02\u0112\u0110\x03\x02" + "\x02\x02\u0112\u0113\x03\x02\x02\x02\u0113\u0116\x03\x02\x02\x02\u0114" + "\u0112\x03\x02\x02\x02\u0115\u0117\x05R*\x02\u0116\u0115\x03\x02\x02\x02" + "\u0116\u0117\x03\x02\x02\x02\u0117\u0118\x03\x02\x02\x02\u0118\u0119\x07" + "\v\x02\x02\u01191\x03\x02\x02\x02\u011A\u011B\x05R*\x02\u011B\u011C\x07" + "\x12\x02\x02\u011C\u0120\x03\x02\x02\x02\u011D\u0120\x05\x04\x03\x02\u011E" + "\u0120\x05:\x1E\x02\u011F\u011A\x03\x02\x02\x02\u011F\u011D\x03\x02\x02" + "\x02\u011F\u011E\x03\x02\x02\x02\u01203\x03\x02\x02\x02\u0121\u0122\x05" + "<\x1F\x02\u0122\u012B\x07\b\x02\x02\u0123\u0128\x058\x1D\x02\u0124\u0125" + "\x07\x12\x02\x02\u0125\u0127\x058\x1D\x02\u0126\u0124\x03\x02\x02\x02" + "\u0127\u012A\x03\x02\x02\x02\u0128\u0126\x03\x02\x02\x02\u0128\u0129\x03" + "\x02\x02\x02\u0129\u012C\x03\x02\x02\x02\u012A\u0128\x03\x02\x02\x02\u012B" + "\u0123\x03\x02\x02\x02\u012B\u012C\x03\x02\x02\x02\u012C\u012E\x03\x02" + "\x02\x02\u012D\u012F\x07\x06\x02\x02\u012E\u012D\x03\x02\x02\x02\u012E" + "\u012F\x03\x02\x02\x02\u012F\u0130\x03\x02\x02\x02\u0130\u0132\x07\t\x02" + "\x02\u0131\u0133\x056\x1C\x02\u0132\u0131\x03\x02\x02\x02\u0132\u0133" + "\x03\x02\x02\x02\u0133\u0134\x03\x02\x02\x02\u0134\u0135\x050\x19\x02" + "\u01355\x03\x02\x02\x02\u0136\u0137\x075\x02\x02\u0137\u0138\x05\x1E\x10" + "\x02\u01387\x03\x02\x02\x02\u0139\u013C\x05\x12\n\x02\u013A\u013C\x05" + "$\x13\x02\u013B\u0139\x03\x02\x02\x02\u013B\u013A\x03\x02\x02\x02\u013C" + "9\x03\x02\x02\x02\u013D\u013E\x05> \x02\u013E\u0140\x07\b\x02\x02\u013F" + "\u0141\x05T+\x02\u0140\u013F\x03\x02\x02\x02\u0140\u0141\x03\x02\x02\x02" + "\u0141\u0142\x03\x02\x02\x02\u0142\u0144\x07\t\x02\x02\u0143\u0145\x07" + ",\x02\x02\u0144\u0143\x03\x02\x02\x02\u0144\u0145\x03\x02\x02\x02\u0145" + "\u0146\x03\x02\x02\x02\u0146\u0147\x07\x12\x02\x02\u0147;\x03\x02\x02" + "\x02\u0148\u014D\x05> \x02\u0149\u014A\x07\x13\x02\x02\u014A\u014C\x05" + "> \x02\u014B\u0149\x03\x02\x02\x02\u014C\u014F\x03\x02\x02\x02\u014D\u014B" + "\x03\x02\x02\x02\u014D\u014E\x03\x02\x02\x02\u014E=\x03\x02\x02\x02\u014F" + "\u014D\x03\x02\x02\x02\u0150\u0152\x05F$\x02\u0151\u0150\x03\x02\x02\x02" + "\u0152\u0153\x03\x02\x02\x02\u0153\u0151\x03\x02\x02\x02\u0153\u0154\x03" + "\x02\x02\x02\u0154\u0158\x03\x02\x02\x02\u0155\u0157\x05@!\x02\u0156\u0155" + "\x03\x02\x02\x02\u0157\u015A\x03\x02\x02\x02\u0158\u0156\x03\x02\x02\x02" + "\u0158\u0159\x03\x02\x02\x02\u0159\u015C\x03\x02\x02\x02\u015A\u0158\x03" + "\x02\x02\x02\u015B\u015D\x05D#\x02\u015C\u015B\x03\x02\x02\x02\u015C\u015D" + "\x03\x02\x02\x02\u015D?\x03\x02\x02\x02\u015E\u015F\x07\f\x02\x02\u015F" + "\u0163\x078\x02\x02\u0160\u0161\x05J&\x02\u0161\u0162\t\x07\x02\x02\u0162" + "\u0164\x03\x02\x02\x02\u0163\u0160\x03\x02\x02\x02\u0163\u0164\x03\x02" + "\x02\x02\u0164\u0165\x03\x02\x02\x02\u0165\u0166\x07\r\x02\x02\u0166A" + "\x03\x02\x02\x02\u0167\u0168\x07\x11\x02\x02\u0168\u0169\x076\x02\x02" + "\u0169\u016B\x07\b\x02\x02\u016A\u016C\x07\f\x02\x02\u016B\u016A\x03\x02" + "\x02\x02\u016B\u016C\x03\x02\x02\x02\u016C\u016D\x03\x02\x02\x02\u016D" + "\u016F\x05<\x1F\x02\u016E\u0170\x07\r\x02\x02\u016F\u016E\x03\x02\x02" + "\x02\u016F\u0170\x03\x02\x02\x02\u0170\u0171\x03\x02\x02\x02\u0171\u0172" + "\x07\t\x02\x02\u0172C\x03\x02\x02\x02\u0173\u0174\t\b\x02\x02\u0174\u0175" + "\x078\x02\x02\u0175E\x03\x02\x02\x02\u0176\u0177\x05H%\x02\u0177\u0178" + "\x05L\'\x02\u0178\u0181\x03\x02\x02\x02\u0179\u0181\x05L\'\x02\u017A\u017B" + "\x07\x18\x02\x02\u017B\u0181\x05L\'\x02\u017C\u0181\x05D#\x02\u017D\u0181" + "\x05B\"\x02\u017E\u0181\x07\x17\x02\x02\u017F\u0181\x07\x1B\x02\x02\u0180" + "\u0176\x03\x02\x02\x02\u0180\u0179\x03\x02\x02\x02\u0180\u017A\x03\x02" + "\x02\x02\u0180\u017C\x03\x02\x02\x02\u0180\u017D\x03\x02\x02\x02\u0180" + "\u017E\x03\x02\x02\x02\u0180\u017F\x03\x02\x02\x02\u0181G\x03\x02\x02" + "\x02\u0182\u0183\t\t\x02\x02\u0183I\x03\x02\x02\x02\u0184\u0185\t\n\x02" + "\x02\u0185K\x03\x02\x02\x02\u0186\u018A\x078\x02\x02\u0187\u0189\x05N" + "(\x02\u0188\u0187\x03\x02\x02\x02\u0189\u018C\x03\x02\x02\x02\u018A\u0188" + "\x03\x02\x02\x02\u018A\u018B\x03\x02\x02\x02\u018B\u0197\x03\x02\x02\x02" + "\u018C\u018A\x03\x02\x02\x02\u018D\u018E\x07\x07\x02\x02\u018E\u018F\x05" + "P)\x02\u018F\u0193\x07\v\x02\x02\u0190\u0192\x05N(\x02\u0191\u0190\x03" + "\x02\x02\x02\u0192\u0195\x03\x02\x02\x02\u0193\u0191\x03\x02\x02\x02\u0193" + "\u0194\x03\x02\x02\x02\u0194\u0197\x03\x02\x02\x02\u0195\u0193\x03\x02" + "\x02\x02\u0196\u0186\x03\x02\x02\x02\u0196\u018D\x03\x02\x02\x02\u0197" + "M\x03\x02\x02\x02\u0198\u0199\x07\x90\x02\x02\u0199\u019A\x05P)\x02\u019A" + "\u019B\x07\v\x02\x02\u019B\u019E\x03\x02\x02\x02\u019C\u019E\x07\x91\x02" + "\x02\u019D\u0198\x03\x02\x02\x02\u019D\u019C\x03\x02\x02\x02\u019EO\x03" + "\x02\x02\x02\u019F\u01A0\t\v\x02\x02\u01A0Q\x03\x02\x02\x02\u01A1\u01A2" + "\x05L\'\x02\u01A2\u01A3\x07\x11\x02\x02\u01A3\u01A4\x05T+\x02\u01A4S\x03" + "\x02\x02\x02\u01A5\u01AA\x05\x14\v\x02\u01A6\u01A7\x07\x13\x02\x02\u01A7" + "\u01A9\x05\x14\v\x02\u01A8\u01A6\x03\x02\x02\x02\u01A9\u01AC\x03\x02\x02" + "\x02\u01AA\u01A8\x03\x02\x02\x02\u01AA\u01AB\x03\x02\x02\x02\u01ABU\x03" + "\x02\x02\x02\u01AC\u01AA\x03\x02\x02\x02\u01AD\u01AE\x07\'\x02\x02\u01AE" + "\u01AF\x07\x8E\x02\x02\u01AF\u01B0\x07\x8D\x02\x02\u01B0W\x03\x02\x02" + "\x02\u01B1\u01B3\x07:\x02\x02\u01B2\u01B4\x07\x05\x02\x02\u01B3\u01B2" + "\x03\x02\x02\x02\u01B3\u01B4\x03\x02\x02\x02\u01B4Y\x03\x02\x02\x021]" + "grux\x7F\x87\x8A\x92\x9C\xA1\xA4\xB3\xC0\xC5\xCE\xDA\xE1\xEE\xF3\xF7\u0101" + "\u0108\u0112\u0116\u011F\u0128\u012B\u012E\u0132\u013B\u0140\u0144\u014D" + "\u0153\u0158\u015C\u0163\u016B\u016F\u0180\u018A\u0193\u0196\u019D\u01AA" + "\u01B3"; public static __ATN: ATN; public static get _ATN(): ATN { if (!LessParser.__ATN) { LessParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(LessParser._serializedATN)); } return LessParser.__ATN; } } export class StylesheetContext extends ParserRuleContext { public statement(): StatementContext[]; public statement(i: number): StatementContext; public statement(i?: number): StatementContext | StatementContext[] { if (i === undefined) { return this.getRuleContexts(StatementContext); } else { return this.getRuleContext(i, StatementContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_stylesheet; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterStylesheet) { listener.enterStylesheet(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitStylesheet) { listener.exitStylesheet(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitStylesheet) { return visitor.visitStylesheet(this); } else { return visitor.visitChildren(this); } } } export class StatementContext extends ParserRuleContext { public importDeclaration(): ImportDeclarationContext | undefined { return this.tryGetRuleContext(0, ImportDeclarationContext); } public ruleset(): RulesetContext | undefined { return this.tryGetRuleContext(0, RulesetContext); } public variableDeclaration(): VariableDeclarationContext | undefined { return this.tryGetRuleContext(0, VariableDeclarationContext); } public SEMI(): TerminalNode | undefined { return this.tryGetToken(LessParser.SEMI, 0); } public mixinDefinition(): MixinDefinitionContext | undefined { return this.tryGetRuleContext(0, MixinDefinitionContext); } public media(): MediaContext | undefined { return this.tryGetRuleContext(0, MediaContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_statement; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterStatement) { listener.enterStatement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitStatement) { listener.exitStatement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitStatement) { return visitor.visitStatement(this); } else { return visitor.visitChildren(this); } } } export class MediaContext extends ParserRuleContext { public MEDIA(): TerminalNode { return this.getToken(LessParser.MEDIA, 0); } public mediaQueryList(): MediaQueryListContext { return this.getRuleContext(0, MediaQueryListContext); } public block(): BlockContext { return this.getRuleContext(0, BlockContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_media; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMedia) { listener.enterMedia(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMedia) { listener.exitMedia(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMedia) { return visitor.visitMedia(this); } else { return visitor.visitChildren(this); } } } export class MediaQueryListContext extends ParserRuleContext { public mediaQuery(): MediaQueryContext[]; public mediaQuery(i: number): MediaQueryContext; public mediaQuery(i?: number): MediaQueryContext | MediaQueryContext[] { if (i === undefined) { return this.getRuleContexts(MediaQueryContext); } else { return this.getRuleContext(i, MediaQueryContext); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaQueryList; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaQueryList) { listener.enterMediaQueryList(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaQueryList) { listener.exitMediaQueryList(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaQueryList) { return visitor.visitMediaQueryList(this); } else { return visitor.visitChildren(this); } } } export class MediaQueryContext extends ParserRuleContext { public mediaType(): MediaTypeContext | undefined { return this.tryGetRuleContext(0, MediaTypeContext); } public AND(): TerminalNode[]; public AND(i: number): TerminalNode; public AND(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.AND); } else { return this.getToken(LessParser.AND, i); } } public mediaExpression(): MediaExpressionContext[]; public mediaExpression(i: number): MediaExpressionContext; public mediaExpression(i?: number): MediaExpressionContext | MediaExpressionContext[] { if (i === undefined) { return this.getRuleContexts(MediaExpressionContext); } else { return this.getRuleContext(i, MediaExpressionContext); } } public MEDIAONLY(): TerminalNode | undefined { return this.tryGetToken(LessParser.MEDIAONLY, 0); } public NOT(): TerminalNode | undefined { return this.tryGetToken(LessParser.NOT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaQuery; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaQuery) { listener.enterMediaQuery(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaQuery) { listener.exitMediaQuery(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaQuery) { return visitor.visitMediaQuery(this); } else { return visitor.visitChildren(this); } } } export class MediaTypeContext extends ParserRuleContext { public identifier(): IdentifierContext { return this.getRuleContext(0, IdentifierContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaType; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaType) { listener.enterMediaType(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaType) { listener.exitMediaType(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaType) { return visitor.visitMediaType(this); } else { return visitor.visitChildren(this); } } } export class MediaExpressionContext extends ParserRuleContext { public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public mediaFeature(): MediaFeatureContext { return this.getRuleContext(0, MediaFeatureContext); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public COLON(): TerminalNode | undefined { return this.tryGetToken(LessParser.COLON, 0); } public expression(): ExpressionContext | undefined { return this.tryGetRuleContext(0, ExpressionContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaExpression; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaExpression) { listener.enterMediaExpression(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaExpression) { listener.exitMediaExpression(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaExpression) { return visitor.visitMediaExpression(this); } else { return visitor.visitChildren(this); } } } export class MediaFeatureContext extends ParserRuleContext { public identifier(): IdentifierContext { return this.getRuleContext(0, IdentifierContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaFeature; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaFeature) { listener.enterMediaFeature(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaFeature) { listener.exitMediaFeature(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaFeature) { return visitor.visitMediaFeature(this); } else { return visitor.visitChildren(this); } } } export class VariableNameContext extends ParserRuleContext { public AT(): TerminalNode { return this.getToken(LessParser.AT, 0); } public variableName(): VariableNameContext | undefined { return this.tryGetRuleContext(0, VariableNameContext); } public Identifier(): TerminalNode | undefined { return this.tryGetToken(LessParser.Identifier, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_variableName; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterVariableName) { listener.enterVariableName(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitVariableName) { listener.exitVariableName(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitVariableName) { return visitor.visitVariableName(this); } else { return visitor.visitChildren(this); } } } export class CommandStatementContext extends ParserRuleContext { public mathStatement(): MathStatementContext | undefined { return this.tryGetRuleContext(0, MathStatementContext); } public expression(): ExpressionContext[]; public expression(i: number): ExpressionContext; public expression(i?: number): ExpressionContext | ExpressionContext[] { if (i === undefined) { return this.getRuleContexts(ExpressionContext); } else { return this.getRuleContext(i, ExpressionContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_commandStatement; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterCommandStatement) { listener.enterCommandStatement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitCommandStatement) { listener.exitCommandStatement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitCommandStatement) { return visitor.visitCommandStatement(this); } else { return visitor.visitChildren(this); } } } export class MathCharacterContext extends ParserRuleContext { public TIMES(): TerminalNode | undefined { return this.tryGetToken(LessParser.TIMES, 0); } public PLUS(): TerminalNode | undefined { return this.tryGetToken(LessParser.PLUS, 0); } public DIV(): TerminalNode | undefined { return this.tryGetToken(LessParser.DIV, 0); } public MINUS(): TerminalNode | undefined { return this.tryGetToken(LessParser.MINUS, 0); } public PERC(): TerminalNode | undefined { return this.tryGetToken(LessParser.PERC, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mathCharacter; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMathCharacter) { listener.enterMathCharacter(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMathCharacter) { listener.exitMathCharacter(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMathCharacter) { return visitor.visitMathCharacter(this); } else { return visitor.visitChildren(this); } } } export class MathStatementContext extends ParserRuleContext { public mathCharacter(): MathCharacterContext { return this.getRuleContext(0, MathCharacterContext); } public commandStatement(): CommandStatementContext { return this.getRuleContext(0, CommandStatementContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mathStatement; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMathStatement) { listener.enterMathStatement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMathStatement) { listener.exitMathStatement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMathStatement) { return visitor.visitMathStatement(this); } else { return visitor.visitChildren(this); } } } export class ExpressionContext extends ParserRuleContext { public measurement(): MeasurementContext | undefined { return this.tryGetRuleContext(0, MeasurementContext); } public identifier(): IdentifierContext | undefined { return this.tryGetRuleContext(0, IdentifierContext); } public IMPORTANT(): TerminalNode | undefined { return this.tryGetToken(LessParser.IMPORTANT, 0); } public LPAREN(): TerminalNode | undefined { return this.tryGetToken(LessParser.LPAREN, 0); } public RPAREN(): TerminalNode | undefined { return this.tryGetToken(LessParser.RPAREN, 0); } public values(): ValuesContext | undefined { return this.tryGetRuleContext(0, ValuesContext); } public Color(): TerminalNode | undefined { return this.tryGetToken(LessParser.Color, 0); } public StringLiteral(): TerminalNode | undefined { return this.tryGetToken(LessParser.StringLiteral, 0); } public url(): UrlContext | undefined { return this.tryGetRuleContext(0, UrlContext); } public variableName(): VariableNameContext | undefined { return this.tryGetRuleContext(0, VariableNameContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_expression; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterExpression) { listener.enterExpression(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitExpression) { listener.exitExpression(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitExpression) { return visitor.visitExpression(this); } else { return visitor.visitChildren(this); } } } export class FuncContext extends ParserRuleContext { public FUNCTION_NAME(): TerminalNode { return this.getToken(LessParser.FUNCTION_NAME, 0); } public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public values(): ValuesContext | undefined { return this.tryGetRuleContext(0, ValuesContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_func; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterFunc) { listener.enterFunc(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitFunc) { listener.exitFunc(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitFunc) { return visitor.visitFunc(this); } else { return visitor.visitChildren(this); } } } export class ConditionsContext extends ParserRuleContext { public condition(): ConditionContext[]; public condition(i: number): ConditionContext; public condition(i?: number): ConditionContext | ConditionContext[] { if (i === undefined) { return this.getRuleContexts(ConditionContext); } else { return this.getRuleContext(i, ConditionContext); } } public AND(): TerminalNode[]; public AND(i: number): TerminalNode; public AND(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.AND); } else { return this.getToken(LessParser.AND, i); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_conditions; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterConditions) { listener.enterConditions(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitConditions) { listener.exitConditions(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitConditions) { return visitor.visitConditions(this); } else { return visitor.visitChildren(this); } } } export class ConditionContext extends ParserRuleContext { public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public conditionStatement(): ConditionStatementContext { return this.getRuleContext(0, ConditionStatementContext); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public NOT(): TerminalNode | undefined { return this.tryGetToken(LessParser.NOT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_condition; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterCondition) { listener.enterCondition(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitCondition) { listener.exitCondition(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitCondition) { return visitor.visitCondition(this); } else { return visitor.visitChildren(this); } } } export class ConditionStatementContext extends ParserRuleContext { public commandStatement(): CommandStatementContext[]; public commandStatement(i: number): CommandStatementContext; public commandStatement(i?: number): CommandStatementContext | CommandStatementContext[] { if (i === undefined) { return this.getRuleContexts(CommandStatementContext); } else { return this.getRuleContext(i, CommandStatementContext); } } public EQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.EQ, 0); } public LT(): TerminalNode | undefined { return this.tryGetToken(LessParser.LT, 0); } public GT(): TerminalNode | undefined { return this.tryGetToken(LessParser.GT, 0); } public GTEQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.GTEQ, 0); } public LTEQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.LTEQ, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_conditionStatement; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterConditionStatement) { listener.enterConditionStatement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitConditionStatement) { listener.exitConditionStatement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitConditionStatement) { return visitor.visitConditionStatement(this); } else { return visitor.visitChildren(this); } } } export class VariableDeclarationContext extends ParserRuleContext { public variableName(): VariableNameContext { return this.getRuleContext(0, VariableNameContext); } public COLON(): TerminalNode { return this.getToken(LessParser.COLON, 0); } public values(): ValuesContext { return this.getRuleContext(0, ValuesContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_variableDeclaration; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterVariableDeclaration) { listener.enterVariableDeclaration(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitVariableDeclaration) { listener.exitVariableDeclaration(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitVariableDeclaration) { return visitor.visitVariableDeclaration(this); } else { return visitor.visitChildren(this); } } } export class ImportDeclarationContext extends ParserRuleContext { public IMPORT(): TerminalNode { return this.getToken(LessParser.IMPORT, 0); } public referenceUrl(): ReferenceUrlContext { return this.getRuleContext(0, ReferenceUrlContext); } public SEMI(): TerminalNode { return this.getToken(LessParser.SEMI, 0); } public LPAREN(): TerminalNode | undefined { return this.tryGetToken(LessParser.LPAREN, 0); } public RPAREN(): TerminalNode | undefined { return this.tryGetToken(LessParser.RPAREN, 0); } public mediaTypes(): MediaTypesContext | undefined { return this.tryGetRuleContext(0, MediaTypesContext); } public importOption(): ImportOptionContext[]; public importOption(i: number): ImportOptionContext; public importOption(i?: number): ImportOptionContext | ImportOptionContext[] { if (i === undefined) { return this.getRuleContexts(ImportOptionContext); } else { return this.getRuleContext(i, ImportOptionContext); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_importDeclaration; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterImportDeclaration) { listener.enterImportDeclaration(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitImportDeclaration) { listener.exitImportDeclaration(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitImportDeclaration) { return visitor.visitImportDeclaration(this); } else { return visitor.visitChildren(this); } } } export class ImportOptionContext extends ParserRuleContext { public REFERENCE(): TerminalNode | undefined { return this.tryGetToken(LessParser.REFERENCE, 0); } public INLINE(): TerminalNode | undefined { return this.tryGetToken(LessParser.INLINE, 0); } public LESS(): TerminalNode | undefined { return this.tryGetToken(LessParser.LESS, 0); } public CSS(): TerminalNode | undefined { return this.tryGetToken(LessParser.CSS, 0); } public ONCE(): TerminalNode | undefined { return this.tryGetToken(LessParser.ONCE, 0); } public MULTIPLE(): TerminalNode | undefined { return this.tryGetToken(LessParser.MULTIPLE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_importOption; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterImportOption) { listener.enterImportOption(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitImportOption) { listener.exitImportOption(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitImportOption) { return visitor.visitImportOption(this); } else { return visitor.visitChildren(this); } } } export class ReferenceUrlContext extends ParserRuleContext { public StringLiteral(): TerminalNode | undefined { return this.tryGetToken(LessParser.StringLiteral, 0); } public UrlStart(): TerminalNode | undefined { return this.tryGetToken(LessParser.UrlStart, 0); } public Url(): TerminalNode | undefined { return this.tryGetToken(LessParser.Url, 0); } public UrlEnd(): TerminalNode | undefined { return this.tryGetToken(LessParser.UrlEnd, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_referenceUrl; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterReferenceUrl) { listener.enterReferenceUrl(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitReferenceUrl) { listener.exitReferenceUrl(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitReferenceUrl) { return visitor.visitReferenceUrl(this); } else { return visitor.visitChildren(this); } } } export class MediaTypesContext extends ParserRuleContext { public Identifier(): TerminalNode[]; public Identifier(i: number): TerminalNode; public Identifier(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.Identifier); } else { return this.getToken(LessParser.Identifier, i); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mediaTypes; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMediaTypes) { listener.enterMediaTypes(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMediaTypes) { listener.exitMediaTypes(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMediaTypes) { return visitor.visitMediaTypes(this); } else { return visitor.visitChildren(this); } } } export class RulesetContext extends ParserRuleContext { public selectors(): SelectorsContext { return this.getRuleContext(0, SelectorsContext); } public block(): BlockContext { return this.getRuleContext(0, BlockContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_ruleset; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterRuleset) { listener.enterRuleset(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitRuleset) { listener.exitRuleset(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitRuleset) { return visitor.visitRuleset(this); } else { return visitor.visitChildren(this); } } } export class BlockContext extends ParserRuleContext { public BlockStart(): TerminalNode { return this.getToken(LessParser.BlockStart, 0); } public BlockEnd(): TerminalNode { return this.getToken(LessParser.BlockEnd, 0); } public blockItem(): BlockItemContext[]; public blockItem(i: number): BlockItemContext; public blockItem(i?: number): BlockItemContext | BlockItemContext[] { if (i === undefined) { return this.getRuleContexts(BlockItemContext); } else { return this.getRuleContext(i, BlockItemContext); } } public property(): PropertyContext | undefined { return this.tryGetRuleContext(0, PropertyContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_block; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterBlock) { listener.enterBlock(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitBlock) { listener.exitBlock(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitBlock) { return visitor.visitBlock(this); } else { return visitor.visitChildren(this); } } } export class BlockItemContext extends ParserRuleContext { public property(): PropertyContext | undefined { return this.tryGetRuleContext(0, PropertyContext); } public SEMI(): TerminalNode | undefined { return this.tryGetToken(LessParser.SEMI, 0); } public statement(): StatementContext | undefined { return this.tryGetRuleContext(0, StatementContext); } public mixinReference(): MixinReferenceContext | undefined { return this.tryGetRuleContext(0, MixinReferenceContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_blockItem; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterBlockItem) { listener.enterBlockItem(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitBlockItem) { listener.exitBlockItem(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitBlockItem) { return visitor.visitBlockItem(this); } else { return visitor.visitChildren(this); } } } export class MixinDefinitionContext extends ParserRuleContext { public selectors(): SelectorsContext { return this.getRuleContext(0, SelectorsContext); } public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public block(): BlockContext { return this.getRuleContext(0, BlockContext); } public mixinDefinitionParam(): MixinDefinitionParamContext[]; public mixinDefinitionParam(i: number): MixinDefinitionParamContext; public mixinDefinitionParam(i?: number): MixinDefinitionParamContext | MixinDefinitionParamContext[] { if (i === undefined) { return this.getRuleContexts(MixinDefinitionParamContext); } else { return this.getRuleContext(i, MixinDefinitionParamContext); } } public Ellipsis(): TerminalNode | undefined { return this.tryGetToken(LessParser.Ellipsis, 0); } public mixinGuard(): MixinGuardContext | undefined { return this.tryGetRuleContext(0, MixinGuardContext); } public SEMI(): TerminalNode[]; public SEMI(i: number): TerminalNode; public SEMI(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.SEMI); } else { return this.getToken(LessParser.SEMI, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mixinDefinition; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMixinDefinition) { listener.enterMixinDefinition(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMixinDefinition) { listener.exitMixinDefinition(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMixinDefinition) { return visitor.visitMixinDefinition(this); } else { return visitor.visitChildren(this); } } } export class MixinGuardContext extends ParserRuleContext { public WHEN(): TerminalNode { return this.getToken(LessParser.WHEN, 0); } public conditions(): ConditionsContext { return this.getRuleContext(0, ConditionsContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mixinGuard; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMixinGuard) { listener.enterMixinGuard(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMixinGuard) { listener.exitMixinGuard(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMixinGuard) { return visitor.visitMixinGuard(this); } else { return visitor.visitChildren(this); } } } export class MixinDefinitionParamContext extends ParserRuleContext { public variableName(): VariableNameContext | undefined { return this.tryGetRuleContext(0, VariableNameContext); } public variableDeclaration(): VariableDeclarationContext | undefined { return this.tryGetRuleContext(0, VariableDeclarationContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mixinDefinitionParam; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMixinDefinitionParam) { listener.enterMixinDefinitionParam(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMixinDefinitionParam) { listener.exitMixinDefinitionParam(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMixinDefinitionParam) { return visitor.visitMixinDefinitionParam(this); } else { return visitor.visitChildren(this); } } } export class MixinReferenceContext extends ParserRuleContext { public selector(): SelectorContext { return this.getRuleContext(0, SelectorContext); } public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public SEMI(): TerminalNode { return this.getToken(LessParser.SEMI, 0); } public values(): ValuesContext | undefined { return this.tryGetRuleContext(0, ValuesContext); } public IMPORTANT(): TerminalNode | undefined { return this.tryGetToken(LessParser.IMPORTANT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_mixinReference; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMixinReference) { listener.enterMixinReference(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMixinReference) { listener.exitMixinReference(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMixinReference) { return visitor.visitMixinReference(this); } else { return visitor.visitChildren(this); } } } export class SelectorsContext extends ParserRuleContext { public selector(): SelectorContext[]; public selector(i: number): SelectorContext; public selector(i?: number): SelectorContext | SelectorContext[] { if (i === undefined) { return this.getRuleContexts(SelectorContext); } else { return this.getRuleContext(i, SelectorContext); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_selectors; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterSelectors) { listener.enterSelectors(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitSelectors) { listener.exitSelectors(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitSelectors) { return visitor.visitSelectors(this); } else { return visitor.visitChildren(this); } } } export class SelectorContext extends ParserRuleContext { public element(): ElementContext[]; public element(i: number): ElementContext; public element(i?: number): ElementContext | ElementContext[] { if (i === undefined) { return this.getRuleContexts(ElementContext); } else { return this.getRuleContext(i, ElementContext); } } public attrib(): AttribContext[]; public attrib(i: number): AttribContext; public attrib(i?: number): AttribContext | AttribContext[] { if (i === undefined) { return this.getRuleContexts(AttribContext); } else { return this.getRuleContext(i, AttribContext); } } public pseudo(): PseudoContext | undefined { return this.tryGetRuleContext(0, PseudoContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_selector; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterSelector) { listener.enterSelector(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitSelector) { listener.exitSelector(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitSelector) { return visitor.visitSelector(this); } else { return visitor.visitChildren(this); } } } export class AttribContext extends ParserRuleContext { public LBRACK(): TerminalNode { return this.getToken(LessParser.LBRACK, 0); } public Identifier(): TerminalNode[]; public Identifier(i: number): TerminalNode; public Identifier(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.Identifier); } else { return this.getToken(LessParser.Identifier, i); } } public RBRACK(): TerminalNode { return this.getToken(LessParser.RBRACK, 0); } public attribRelate(): AttribRelateContext | undefined { return this.tryGetRuleContext(0, AttribRelateContext); } public StringLiteral(): TerminalNode | undefined { return this.tryGetToken(LessParser.StringLiteral, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_attrib; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterAttrib) { listener.enterAttrib(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitAttrib) { listener.exitAttrib(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitAttrib) { return visitor.visitAttrib(this); } else { return visitor.visitChildren(this); } } } export class NegationContext extends ParserRuleContext { public COLON(): TerminalNode { return this.getToken(LessParser.COLON, 0); } public NOT(): TerminalNode { return this.getToken(LessParser.NOT, 0); } public LPAREN(): TerminalNode { return this.getToken(LessParser.LPAREN, 0); } public selectors(): SelectorsContext { return this.getRuleContext(0, SelectorsContext); } public RPAREN(): TerminalNode { return this.getToken(LessParser.RPAREN, 0); } public LBRACK(): TerminalNode | undefined { return this.tryGetToken(LessParser.LBRACK, 0); } public RBRACK(): TerminalNode | undefined { return this.tryGetToken(LessParser.RBRACK, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_negation; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterNegation) { listener.enterNegation(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitNegation) { listener.exitNegation(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitNegation) { return visitor.visitNegation(this); } else { return visitor.visitChildren(this); } } } export class PseudoContext extends ParserRuleContext { public Identifier(): TerminalNode { return this.getToken(LessParser.Identifier, 0); } public COLON(): TerminalNode | undefined { return this.tryGetToken(LessParser.COLON, 0); } public COLONCOLON(): TerminalNode | undefined { return this.tryGetToken(LessParser.COLONCOLON, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_pseudo; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterPseudo) { listener.enterPseudo(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitPseudo) { listener.exitPseudo(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitPseudo) { return visitor.visitPseudo(this); } else { return visitor.visitChildren(this); } } } export class ElementContext extends ParserRuleContext { public selectorPrefix(): SelectorPrefixContext | undefined { return this.tryGetRuleContext(0, SelectorPrefixContext); } public identifier(): IdentifierContext | undefined { return this.tryGetRuleContext(0, IdentifierContext); } public HASH(): TerminalNode | undefined { return this.tryGetToken(LessParser.HASH, 0); } public pseudo(): PseudoContext | undefined { return this.tryGetRuleContext(0, PseudoContext); } public negation(): NegationContext | undefined { return this.tryGetRuleContext(0, NegationContext); } public PARENTREF(): TerminalNode | undefined { return this.tryGetToken(LessParser.PARENTREF, 0); } public TIMES(): TerminalNode | undefined { return this.tryGetToken(LessParser.TIMES, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_element; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterElement) { listener.enterElement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitElement) { listener.exitElement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitElement) { return visitor.visitElement(this); } else { return visitor.visitChildren(this); } } } export class SelectorPrefixContext extends ParserRuleContext { public GT(): TerminalNode | undefined { return this.tryGetToken(LessParser.GT, 0); } public PLUS(): TerminalNode | undefined { return this.tryGetToken(LessParser.PLUS, 0); } public TIL(): TerminalNode | undefined { return this.tryGetToken(LessParser.TIL, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_selectorPrefix; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterSelectorPrefix) { listener.enterSelectorPrefix(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitSelectorPrefix) { listener.exitSelectorPrefix(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitSelectorPrefix) { return visitor.visitSelectorPrefix(this); } else { return visitor.visitChildren(this); } } } export class AttribRelateContext extends ParserRuleContext { public EQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.EQ, 0); } public TILD_EQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.TILD_EQ, 0); } public PIPE_EQ(): TerminalNode | undefined { return this.tryGetToken(LessParser.PIPE_EQ, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_attribRelate; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterAttribRelate) { listener.enterAttribRelate(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitAttribRelate) { listener.exitAttribRelate(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitAttribRelate) { return visitor.visitAttribRelate(this); } else { return visitor.visitChildren(this); } } } export class IdentifierContext extends ParserRuleContext { public Identifier(): TerminalNode | undefined { return this.tryGetToken(LessParser.Identifier, 0); } public identifierPart(): IdentifierPartContext[]; public identifierPart(i: number): IdentifierPartContext; public identifierPart(i?: number): IdentifierPartContext | IdentifierPartContext[] { if (i === undefined) { return this.getRuleContexts(IdentifierPartContext); } else { return this.getRuleContext(i, IdentifierPartContext); } } public InterpolationStart(): TerminalNode | undefined { return this.tryGetToken(LessParser.InterpolationStart, 0); } public identifierVariableName(): IdentifierVariableNameContext | undefined { return this.tryGetRuleContext(0, IdentifierVariableNameContext); } public BlockEnd(): TerminalNode | undefined { return this.tryGetToken(LessParser.BlockEnd, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_identifier; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterIdentifier) { listener.enterIdentifier(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitIdentifier) { listener.exitIdentifier(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitIdentifier) { return visitor.visitIdentifier(this); } else { return visitor.visitChildren(this); } } } export class IdentifierPartContext extends ParserRuleContext { public InterpolationStartAfter(): TerminalNode | undefined { return this.tryGetToken(LessParser.InterpolationStartAfter, 0); } public identifierVariableName(): IdentifierVariableNameContext | undefined { return this.tryGetRuleContext(0, IdentifierVariableNameContext); } public BlockEnd(): TerminalNode | undefined { return this.tryGetToken(LessParser.BlockEnd, 0); } public IdentifierAfter(): TerminalNode | undefined { return this.tryGetToken(LessParser.IdentifierAfter, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_identifierPart; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterIdentifierPart) { listener.enterIdentifierPart(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitIdentifierPart) { listener.exitIdentifierPart(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitIdentifierPart) { return visitor.visitIdentifierPart(this); } else { return visitor.visitChildren(this); } } } export class IdentifierVariableNameContext extends ParserRuleContext { public Identifier(): TerminalNode | undefined { return this.tryGetToken(LessParser.Identifier, 0); } public IdentifierAfter(): TerminalNode | undefined { return this.tryGetToken(LessParser.IdentifierAfter, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_identifierVariableName; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterIdentifierVariableName) { listener.enterIdentifierVariableName(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitIdentifierVariableName) { listener.exitIdentifierVariableName(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitIdentifierVariableName) { return visitor.visitIdentifierVariableName(this); } else { return visitor.visitChildren(this); } } } export class PropertyContext extends ParserRuleContext { public identifier(): IdentifierContext { return this.getRuleContext(0, IdentifierContext); } public COLON(): TerminalNode { return this.getToken(LessParser.COLON, 0); } public values(): ValuesContext { return this.getRuleContext(0, ValuesContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_property; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterProperty) { listener.enterProperty(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitProperty) { listener.exitProperty(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitProperty) { return visitor.visitProperty(this); } else { return visitor.visitChildren(this); } } } export class ValuesContext extends ParserRuleContext { public commandStatement(): CommandStatementContext[]; public commandStatement(i: number): CommandStatementContext; public commandStatement(i?: number): CommandStatementContext | CommandStatementContext[] { if (i === undefined) { return this.getRuleContexts(CommandStatementContext); } else { return this.getRuleContext(i, CommandStatementContext); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LessParser.COMMA); } else { return this.getToken(LessParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_values; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterValues) { listener.enterValues(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitValues) { listener.exitValues(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitValues) { return visitor.visitValues(this); } else { return visitor.visitChildren(this); } } } export class UrlContext extends ParserRuleContext { public UrlStart(): TerminalNode { return this.getToken(LessParser.UrlStart, 0); } public Url(): TerminalNode { return this.getToken(LessParser.Url, 0); } public UrlEnd(): TerminalNode { return this.getToken(LessParser.UrlEnd, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_url; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterUrl) { listener.enterUrl(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitUrl) { listener.exitUrl(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitUrl) { return visitor.visitUrl(this); } else { return visitor.visitChildren(this); } } } export class MeasurementContext extends ParserRuleContext { public Number(): TerminalNode { return this.getToken(LessParser.Number, 0); } public Unit(): TerminalNode | undefined { return this.tryGetToken(LessParser.Unit, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LessParser.RULE_measurement; } // @Override public enterRule(listener: LessParserListener): void { if (listener.enterMeasurement) { listener.enterMeasurement(this); } } // @Override public exitRule(listener: LessParserListener): void { if (listener.exitMeasurement) { listener.exitMeasurement(this); } } // @Override public accept<Result>(visitor: LessParserVisitor<Result>): Result { if (visitor.visitMeasurement) { return visitor.visitMeasurement(this); } else { return visitor.visitChildren(this); } } }
the_stack
import Cell from '../cell/Cell'; import CellArray from '../cell/CellArray'; import Rectangle from '../geometry/Rectangle'; import Dictionary from '../../util/Dictionary'; import RootChange from '../undoable_changes/RootChange'; import ChildChange from '../undoable_changes/ChildChange'; import { Graph } from '../Graph'; import { mixInto } from '../../util/Utils'; import GraphSelectionModel from '../GraphSelectionModel'; declare module '../Graph' { interface Graph { cells: CellArray; doneResource: string; updatingSelectionResource: string; singleSelection: boolean; selectionModel: any | null; getSelectionModel: () => GraphSelectionModel; setSelectionModel: (selectionModel: GraphSelectionModel) => void; isCellSelected: (cell: Cell) => boolean; isSelectionEmpty: () => boolean; clearSelection: () => void; getSelectionCount: () => number; getSelectionCell: () => Cell; getSelectionCells: () => CellArray; setSelectionCell: (cell: Cell | null) => void; setSelectionCells: (cells: CellArray) => void; addSelectionCell: (cell: Cell) => void; addSelectionCells: (cells: CellArray) => void; removeSelectionCell: (cell: Cell) => void; removeSelectionCells: (cells: CellArray) => void; selectRegion: (rect: Rectangle, evt: MouseEvent) => CellArray; selectNextCell: () => void; selectPreviousCell: () => void; selectParentCell: () => void; selectChildCell: () => void; selectCell: (isNext?: boolean, isParent?: boolean, isChild?: boolean) => void; selectAll: (parent?: Cell | null, descendants?: boolean) => void; selectVertices: (parent?: Cell | null, selectGroups?: boolean) => void; selectEdges: (parent?: Cell | null) => void; selectCells: ( vertices: boolean, edges: boolean, parent?: Cell | null, selectGroups?: boolean ) => void; selectCellForEvent: (cell: Cell, evt: MouseEvent) => void; selectCellsForEvent: (cells: CellArray, evt: MouseEvent) => void; isSiblingSelected: (cell: Cell) => boolean; getSelectionCellsForChanges: (changes: any[], ignoreFn?: Function | null) => CellArray; updateSelection: () => void; } } type PartialGraph = Pick< Graph, | 'getDataModel' | 'getView' | 'isCellSelectable' | 'fireEvent' | 'getDefaultParent' | 'getCurrentRoot' | 'getCells' | 'isToggleEvent' >; type PartialCells = Pick< Graph, | 'singleSelection' | 'selectionModel' | 'getSelectionModel' | 'setSelectionModel' | 'isCellSelected' | 'isSelectionEmpty' | 'clearSelection' | 'getSelectionCount' | 'getSelectionCell' | 'getSelectionCells' | 'setSelectionCell' | 'setSelectionCells' | 'addSelectionCell' | 'addSelectionCells' | 'removeSelectionCell' | 'removeSelectionCells' | 'selectRegion' | 'selectNextCell' | 'selectPreviousCell' | 'selectParentCell' | 'selectChildCell' | 'selectCell' | 'selectAll' | 'selectVertices' | 'selectEdges' | 'selectCells' | 'selectCellForEvent' | 'selectCellsForEvent' | 'isSiblingSelected' | 'getSelectionCellsForChanges' | 'updateSelection' >; type PartialType = PartialGraph & PartialCells; // @ts-expect-error The properties of PartialGraph are defined elsewhere. const SelectionMixin: PartialType = { selectionModel: null, /** * Returns the {@link mxGraphSelectionModel} that contains the selection. */ getSelectionModel() { return this.selectionModel; }, /** * Sets the {@link mxSelectionModel} that contains the selection. */ setSelectionModel(selectionModel) { this.selectionModel = selectionModel; }, /***************************************************************************** * Selection *****************************************************************************/ /** * Returns true if the given cell is selected. * * @param cell {@link mxCell} for which the selection state should be returned. */ isCellSelected(cell) { return this.selectionModel.isSelected(cell); }, /** * Returns true if the selection is empty. */ isSelectionEmpty() { return this.selectionModel.isEmpty(); }, /** * Clears the selection using {@link mxGraphSelectionModel.clear}. */ clearSelection() { this.selectionModel.clear(); }, /** * Returns the number of selected cells. */ getSelectionCount() { return this.selectionModel.cells.length; }, /** * Returns the first cell from the array of selected {@link Cell}. */ getSelectionCell() { return this.selectionModel.cells[0]; }, /** * Returns the array of selected {@link Cell}. */ getSelectionCells() { return this.selectionModel.cells.slice(); }, /** * Sets the selection cell. * * @param cell {@link mxCell} to be selected. */ setSelectionCell(cell) { this.selectionModel.setCell(cell); }, /** * Sets the selection cell. * * @param cells Array of {@link Cell} to be selected. */ setSelectionCells(cells) { this.selectionModel.setCells(cells); }, /** * Adds the given cell to the selection. * * @param cell {@link mxCell} to be add to the selection. */ addSelectionCell(cell) { this.selectionModel.addCell(cell); }, /** * Adds the given cells to the selection. * * @param cells Array of {@link Cell} to be added to the selection. */ addSelectionCells(cells) { this.selectionModel.addCells(cells); }, /** * Removes the given cell from the selection. * * @param cell {@link mxCell} to be removed from the selection. */ removeSelectionCell(cell) { this.selectionModel.removeCell(cell); }, /** * Removes the given cells from the selection. * * @param cells Array of {@link Cell} to be removed from the selection. */ removeSelectionCells(cells) { this.selectionModel.removeCells(cells); }, /** * Selects and returns the cells inside the given rectangle for the * specified event. * * @param rect {@link mxRectangle} that represents the region to be selected. * @param evt Mouseevent that triggered the selection. */ // selectRegion(rect: mxRectangle, evt: Event): mxCellArray; selectRegion(rect, evt) { const cells = this.getCells(rect.x, rect.y, rect.width, rect.height); this.selectCellsForEvent(cells, evt); return cells; }, /** * Selects the next cell. */ selectNextCell() { this.selectCell(true); }, /** * Selects the previous cell. */ selectPreviousCell() { this.selectCell(); }, /** * Selects the parent cell. */ selectParentCell() { this.selectCell(false, true); }, /** * Selects the first child cell. */ selectChildCell() { this.selectCell(false, false, true); }, /** * Selects the next, parent, first child or previous cell, if all arguments * are false. * * @param isNext Boolean indicating if the next cell should be selected. * @param isParent Boolean indicating if the parent cell should be selected. * @param isChild Boolean indicating if the first child cell should be selected. */ selectCell(isNext = false, isParent = false, isChild = false) { const cell = this.selectionModel.cells.length > 0 ? this.selectionModel.cells[0] : null; if (this.selectionModel.cells.length > 1) { this.selectionModel.clear(); } const parent = cell ? (cell.getParent() as Cell) : this.getDefaultParent(); const childCount = parent.getChildCount(); if (!cell && childCount > 0) { const child = parent.getChildAt(0); this.setSelectionCell(child); } else if ( parent && (!cell || isParent) && this.getView().getState(parent) && parent.getGeometry() ) { if (this.getCurrentRoot() !== parent) { this.setSelectionCell(parent); } } else if (cell && isChild) { const tmp = cell.getChildCount(); if (tmp > 0) { const child = cell.getChildAt(0); this.setSelectionCell(child); } } else if (childCount > 0) { let i = parent.getIndex(cell); if (isNext) { i++; const child = parent.getChildAt(i % childCount); this.setSelectionCell(child); } else { i--; const index = i < 0 ? childCount - 1 : i; const child = parent.getChildAt(index); this.setSelectionCell(child); } } }, /** * Selects all children of the given parent cell or the children of the * default parent if no parent is specified. To select leaf vertices and/or * edges use {@link selectCells}. * * @param parent Optional {@link Cell} whose children should be selected. * Default is {@link defaultParent}. * @param descendants Optional boolean specifying whether all descendants should be * selected. Default is `false`. */ selectAll(parent, descendants = false) { parent = parent ?? this.getDefaultParent(); const cells = descendants ? parent.filterDescendants((cell: Cell) => { return cell !== parent && !!this.getView().getState(cell); }) : parent.getChildren(); this.setSelectionCells(cells); }, /** * Select all vertices inside the given parent or the default parent. */ selectVertices(parent, selectGroups = false) { this.selectCells(true, false, parent, selectGroups); }, /** * Select all vertices inside the given parent or the default parent. */ selectEdges(parent) { this.selectCells(false, true, parent); }, /** * Selects all vertices and/or edges depending on the given boolean * arguments recursively, starting at the given parent or the default * parent if no parent is specified. Use {@link selectAll} to select all cells. * For vertices, only cells with no children are selected. * * @param vertices Boolean indicating if vertices should be selected. * @param edges Boolean indicating if edges should be selected. * @param parent Optional {@link Cell} that acts as the root of the recursion. * Default is {@link defaultParent}. * @param selectGroups Optional boolean that specifies if groups should be * selected. Default is `false`. */ selectCells(vertices = false, edges = false, parent, selectGroups = false) { parent = parent ?? this.getDefaultParent(); const filter = (cell: Cell) => { const p = cell.getParent(); return ( !!this.getView().getState(cell) && (((selectGroups || cell.getChildCount() === 0) && cell.isVertex() && vertices && p && !p.isEdge()) || (cell.isEdge() && edges)) ); }; const cells = parent.filterDescendants(filter); this.setSelectionCells(cells); }, /** * Selects the given cell by either adding it to the selection or * replacing the selection depending on whether the given mouse event is a * toggle event. * * @param cell {@link mxCell} to be selected. * @param evt Optional mouseevent that triggered the selection. */ selectCellForEvent(cell, evt) { const isSelected = this.isCellSelected(cell); if (this.isToggleEvent(evt)) { if (isSelected) { this.removeSelectionCell(cell); } else { this.addSelectionCell(cell); } } else if (!isSelected || this.getSelectionCount() !== 1) { this.setSelectionCell(cell); } }, /** * Selects the given cells by either adding them to the selection or * replacing the selection depending on whether the given mouse event is a * toggle event. * * @param cells Array of {@link Cell} to be selected. * @param evt Optional mouseevent that triggered the selection. */ selectCellsForEvent(cells, evt) { if (this.isToggleEvent(evt)) { this.addSelectionCells(cells); } else { this.setSelectionCells(cells); } }, /** * Returns true if any sibling of the given cell is selected. */ isSiblingSelected(cell) { const parent = cell.getParent() as Cell; const childCount = parent.getChildCount(); for (let i = 0; i < childCount; i += 1) { const child = parent.getChildAt(i); if (cell !== child && this.isCellSelected(child)) { return true; } } return false; }, /***************************************************************************** * Selection state *****************************************************************************/ /** * Returns the cells to be selected for the given array of changes. * * @param ignoreFn Optional function that takes a change and returns true if the * change should be ignored. */ getSelectionCellsForChanges(changes, ignoreFn = null) { const dict = new Dictionary(); const cells: CellArray = new CellArray(); const addCell = (cell: Cell) => { if (!dict.get(cell) && this.getDataModel().contains(cell)) { if (cell.isEdge() || cell.isVertex()) { dict.put(cell, true); cells.push(cell); } else { const childCount = cell.getChildCount(); for (let i = 0; i < childCount; i += 1) { addCell(cell.getChildAt(i)); } } } }; for (let i = 0; i < changes.length; i += 1) { const change = changes[i]; if (change.constructor !== RootChange && (!ignoreFn || !ignoreFn(change))) { let cell = null; if (change instanceof ChildChange) { cell = change.child; } else if (change.cell && change.cell instanceof Cell) { cell = change.cell; } if (cell) { addCell(cell); } } } return cells; }, /** * Removes selection cells that are not in the model from the selection. */ updateSelection() { const cells = this.getSelectionCells(); const removed = new CellArray(); for (const cell of cells) { if (!this.getDataModel().contains(cell) || !cell.isVisible()) { removed.push(cell); } else { let par = cell.getParent(); while (par && par !== this.getView().currentRoot) { if (par.isCollapsed() || !par.isVisible()) { removed.push(cell); break; } par = par.getParent(); } } } this.removeSelectionCells(removed); }, }; mixInto(Graph)(SelectionMixin);
the_stack
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; // <if expr="not chromeos and not lacros"> import './destination_dialog.js'; // </if> // <if expr="chromeos_ash or chromeos_lacros"> import './destination_dialog_cros.js'; // </if> // <if expr="not chromeos and not lacros"> import './destination_select.js'; // </if> // <if expr="chromeos_ash or chromeos_lacros"> import './destination_select_cros.js'; // </if> import './print_preview_shared_css.js'; import './print_preview_vars_css.js'; import './throbber_css.js'; import './settings_section.js'; import '../data/user_manager.js'; import '../strings.m.js'; import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {beforeNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {CloudPrintInterfaceImpl} from '../cloud_print_interface_impl.js'; import {CloudOrigins, createDestinationKey, createRecentDestinationKey, Destination, DestinationOrigin, GooglePromotedDestinationId, makeRecentDestination, RecentDestination} from '../data/destination.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {SAVE_TO_DRIVE_CROS_DESTINATION_KEY} from '../data/destination.js'; // </if> import {getPrinterTypeForDestination, PrinterType} from '../data/destination_match.js'; import {DestinationErrorType, DestinationStore, DestinationStoreEventType} from '../data/destination_store.js'; import {Error, State} from '../data/state.js'; // <if expr="not chromeos and not lacros"> import {PrintPreviewDestinationDialogElement} from './destination_dialog.js'; // </if> // <if expr="chromeos_ash or chromeos_lacros"> import {PrintPreviewDestinationDialogCrosElement} from './destination_dialog_cros.js'; // </if> // <if expr="not chromeos and not lacros"> import {PrintPreviewDestinationSelectElement} from './destination_select.js'; // </if> // <if expr="chromeos_ash or chromeos_lacros"> import {PrintPreviewDestinationSelectCrosElement} from './destination_select_cros.js'; // </if> import {SettingsMixin} from './settings_mixin.js'; export enum DestinationState { INIT = 0, SELECTED = 1, SET = 2, UPDATED = 3, ERROR = 4, } /** Number of recent destinations to save. */ // <if expr="not chromeos and not lacros"> export const NUM_PERSISTED_DESTINATIONS: number = 5; // </if> // <if expr="chromeos_ash or chromeos_lacros"> export const NUM_PERSISTED_DESTINATIONS: number = 10; // </if> /** * Number of unpinned recent destinations to display. * Pinned destinations include "Save as PDF" and "Save to Google Drive". */ const NUM_UNPINNED_DESTINATIONS: number = 3; export interface PrintPreviewDestinationSettingsElement { $: { // <if expr="not chromeos and not lacros"> destinationDialog: CrLazyRenderElement<PrintPreviewDestinationDialogElement>, destinationSelect: PrintPreviewDestinationSelectElement, // </if> // <if expr="chromeos_ash or chromeos_lacros"> destinationDialog: CrLazyRenderElement<PrintPreviewDestinationDialogCrosElement>, destinationSelect: PrintPreviewDestinationSelectCrosElement, // </if> }; } const PrintPreviewDestinationSettingsElementBase = I18nMixin(WebUIListenerMixin(SettingsMixin(PolymerElement))); export class PrintPreviewDestinationSettingsElement extends PrintPreviewDestinationSettingsElementBase { static get is() { return 'print-preview-destination-settings'; } static get template() { return html`{__html_template__}`; } static get properties() { return { dark: Boolean, destination: { type: Object, notify: true, value: null, }, destinationState: { type: Number, notify: true, value: DestinationState.INIT, observer: 'updateDestinationSelect_', }, disabled: Boolean, error: { type: Number, notify: true, observer: 'onErrorChanged_', }, firstLoad: Boolean, state: Number, activeUser_: { type: String, observer: 'onActiveUserChanged_', }, cloudPrintDisabled_: { type: Boolean, value: true, }, destinationStore_: { type: Object, value: null, }, displayedDestinations_: Array, // <if expr="chromeos_ash or chromeos_lacros"> driveDestinationKey_: { type: String, value: '', }, hasPinSetting_: { type: Boolean, computed: 'computeHasPinSetting_(settings.pin.available)', reflectToAttribute: true, }, // </if> isDialogOpen_: { type: Boolean, value: false, }, noDestinations_: { type: Boolean, value: false, }, pdfPrinterDisabled_: Boolean, loaded_: { type: Boolean, computed: 'computeLoaded_(destinationState, destination)', }, users_: Array, }; } dark: boolean; destination: Destination; destinationState: DestinationState; disabled: boolean; error: Error; firstLoad: boolean; state: State; private activeUser_: string; private cloudPrintDisabled_: boolean; private destinationStore_: DestinationStore|null; private displayedDestinations_: Destination[]; // <if expr="chromeos_ash or chromeos_lacros"> private driveDestinationKey_: string; private hasPinSetting_: boolean; // </if> private isDialogOpen_: boolean; private noDestinations_: boolean; private pdfPrinterDisabled_: boolean; private loaded_: boolean; private users_: string[]; private lastUser_: string = ''; private tracker_: EventTracker = new EventTracker(); connectedCallback() { super.connectedCallback(); this.destinationStore_ = new DestinationStore(this.addWebUIListener.bind(this)); this.tracker_.add( this.destinationStore_, DestinationStoreEventType.DESTINATION_SELECT, this.onDestinationSelect_.bind(this)); this.tracker_.add( this.destinationStore_, DestinationStoreEventType.SELECTED_DESTINATION_CAPABILITIES_READY, this.onDestinationCapabilitiesReady_.bind(this)); this.tracker_.add( this.destinationStore_, DestinationStoreEventType.ERROR, this.onDestinationError_.bind(this)); // Need to update the recent list when the destination store inserts // destinations, in case any recent destinations have been added to the // store. At startup, recent destinations can be in the sticky settings, // but they should not be displayed in the dropdown until they have been // fetched by the DestinationStore, to ensure that they still exist. this.tracker_.add( assert(this.destinationStore_), DestinationStoreEventType.DESTINATIONS_INSERTED, this.updateDropdownDestinations_.bind(this)); // <if expr="chromeos_ash or chromeos_lacros"> this.tracker_.add( this.destinationStore_, DestinationStoreEventType.DESTINATION_EULA_READY, this.updateDestinationEulaUrl_.bind(this)); // </if> } disconnectedCallback() { super.disconnectedCallback(); this.destinationStore_!.resetTracker(); this.tracker_.removeAll(); } private onActiveUserChanged_() { this.updateDropdownDestinations_(); if (!this.destination || this.destination.origin !== DestinationOrigin.COOKIES) { // Active user changing doesn't impact non-cookie based destinations. return; } if (this.destination.account === this.activeUser_) { // If the current destination belongs to the new account and the dialog // was waiting for sign in, update the state. if (this.destinationState === DestinationState.SELECTED) { this.destinationState = this.destination.capabilities ? DestinationState.UPDATED : DestinationState.SET; } return; } if (this.isDialogOpen_) { // Do not update the selected destination if the dialog is open, as this // will change the destination settings UI behind the dialog, and the // user may be selecting a new destination in the dialog anyway. Wait // for the user to select a destination or cancel. return; } // Destination belongs to a different account. Reset the destination to // the most recent destination associated with the new account, or the // default. const recent = this.displayedDestinations_.find(d => { return d.origin !== DestinationOrigin.COOKIES || d.account === this.activeUser_; }); if (recent) { this.destinationStore_!.selectDestination(recent); return; } this.destinationStore_!.selectDefaultDestination(); } /** * @param defaultPrinter The system default printer ID. * @param pdfPrinterDisabled Whether the PDF printer is disabled. * @param isDriveMounted Whether Google Drive is mounted. Only used on Chrome OS. * @param serializedDefaultDestinationRulesStr String with rules * for selecting a default destination. */ init( defaultPrinter: string, pdfPrinterDisabled: boolean, isDriveMounted: boolean, serializedDefaultDestinationRulesStr: string|null) { const cloudPrintInterface = CloudPrintInterfaceImpl.getInstance(); this.pdfPrinterDisabled_ = pdfPrinterDisabled; let recentDestinations = this.getSettingValue('recentDestinations') as RecentDestination[]; // <if expr="chromeos_ash or chromeos_lacros"> this.driveDestinationKey_ = isDriveMounted ? SAVE_TO_DRIVE_CROS_DESTINATION_KEY : ''; // </if> if (cloudPrintInterface.isConfigured()) { this.cloudPrintDisabled_ = false; this.destinationStore_!.setCloudPrintInterface(cloudPrintInterface); beforeNextRender(this, () => { this.shadowRoot!.querySelector( 'print-preview-user-manager')!.initUserAccounts(); recentDestinations = recentDestinations.slice( 0, this.getRecentDestinationsDisplayCount_(recentDestinations)); this.destinationStore_!.init( this.pdfPrinterDisabled_, isDriveMounted, defaultPrinter, serializedDefaultDestinationRulesStr, recentDestinations); }); return; } recentDestinations = recentDestinations.slice( 0, this.getRecentDestinationsDisplayCount_(recentDestinations)); this.destinationStore_!.init( this.pdfPrinterDisabled_, isDriveMounted, defaultPrinter, serializedDefaultDestinationRulesStr, recentDestinations); } /** * @param recentDestinations recent destinations. * @return Number of recent destinations to display. */ private getRecentDestinationsDisplayCount_(recentDestinations: RecentDestination[]): number { let numDestinationsToDisplay = NUM_UNPINNED_DESTINATIONS; for (let i = 0; i < recentDestinations.length; i++) { // Once all NUM_UNPINNED_DESTINATIONS unpinned destinations have been // found plus an extra unpinned destination, return the total number of // destinations found excluding the last extra unpinned destination. // // The extra unpinned destination ensures that pinned destinations // located directly after the last unpinned destination are included // in the display count. if (i > numDestinationsToDisplay) { return numDestinationsToDisplay; } // If a destination is pinned, increment numDestinationsToDisplay. if (this.destinationIsDriveOrPdf_(recentDestinations[i])) { numDestinationsToDisplay++; } } return Math.min(recentDestinations.length, numDestinationsToDisplay); } private onDestinationSelect_() { // If the user selected a destination in the dialog after changing the // active user, do the UI updates that were previously deferred. if (this.isDialogOpen_ && this.lastUser_ !== this.activeUser_) { this.updateDropdownDestinations_(); } if (this.state === State.FATAL_ERROR) { // Don't let anything reset if there is a fatal error. return; } const destination = this.destinationStore_!.selectedDestination!; if (!!this.activeUser_ || destination.origin !== DestinationOrigin.COOKIES) { this.destinationState = DestinationState.SET; } else { this.destinationState = DestinationState.SELECTED; } // Notify observers that the destination is set only after updating the // destinationState. this.destination = destination; this.updateRecentDestinations_(); } private onDestinationCapabilitiesReady_() { this.notifyPath('destination.capabilities'); this.updateRecentDestinations_(); if (this.destinationState === DestinationState.SET) { this.destinationState = DestinationState.UPDATED; } } private onDestinationError_(e: CustomEvent<DestinationErrorType>) { let errorType = Error.NONE; switch (e.detail) { case DestinationErrorType.INVALID: errorType = Error.INVALID_PRINTER; break; case DestinationErrorType.UNSUPPORTED: errorType = Error.UNSUPPORTED_PRINTER; break; case DestinationErrorType.NO_DESTINATIONS: errorType = Error.NO_DESTINATIONS; this.noDestinations_ = true; break; default: break; } this.error = errorType; } private onErrorChanged_() { if (this.error === Error.INVALID_PRINTER || this.error === Error.UNSUPPORTED_PRINTER || this.error === Error.NO_DESTINATIONS) { this.destinationState = DestinationState.ERROR; } } /** * @return Whether the destination is Save as PDF or Save to Drive. */ private destinationIsDriveOrPdf_(destination: RecentDestination): boolean { // <if expr="chromeos_ash or chromeos_lacros"> if (destination.id === GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS) { return true; } // </if> return destination.id === GooglePromotedDestinationId.SAVE_AS_PDF; } private updateRecentDestinations_() { if (!this.destination) { return; } // Determine if this destination is already in the recent destinations, // where in the array it is located, and whether or not it is visible. const newDestination = makeRecentDestination(assert(this.destination)); const recentDestinations = this.getSettingValue('recentDestinations') as RecentDestination[]; let indexFound = -1; // Note: isVisible should be only be used if the destination is unpinned. // Although pinned destinations are always visible, isVisible may not // necessarily be set to true in this case. let isVisible = false; let numUnpinnedChecked = 0; for (let index = 0; index < recentDestinations.length; index++) { const recent = recentDestinations[index]; if (recent.id === newDestination.id && recent.origin === newDestination.origin) { indexFound = index; // If we haven't seen the maximum unpinned destinations already, this // destination is visible in the dropdown. isVisible = numUnpinnedChecked < NUM_UNPINNED_DESTINATIONS; break; } if (!this.destinationIsDriveOrPdf_(recent)) { numUnpinnedChecked++; } } // No change if (indexFound === 0 && recentDestinations[0].capabilities === newDestination.capabilities) { return; } const isNew = indexFound === -1; // Shift the array so that the nth most recent destination is located at // index n. if (isNew && recentDestinations.length === NUM_PERSISTED_DESTINATIONS) { indexFound = NUM_PERSISTED_DESTINATIONS - 1; } if (indexFound !== -1) { this.setSettingSplice('recentDestinations', indexFound, 1, null); } // Add the most recent destination this.setSettingSplice('recentDestinations', 0, 0, newDestination); // The dropdown needs to be updated if a new printer or one not currently // visible in the dropdown has been added. if (!this.destinationIsDriveOrPdf_(newDestination) && (isNew || !isVisible)) { this.updateDropdownDestinations_(); } } private updateDropdownDestinations_() { const recentDestinations = this.getSettingValue('recentDestinations') as RecentDestination[]; const updatedDestinations: Destination[] = []; let numDestinationsChecked = 0; for (const recent of recentDestinations) { if (this.destinationIsDriveOrPdf_(recent)) { continue; } numDestinationsChecked++; const key = createRecentDestinationKey(recent); const destination = this.destinationStore_!.getDestinationByKey(key); if (destination && (!destination.account || destination.account === this.activeUser_)) { updatedDestinations.push(destination); } if (numDestinationsChecked === NUM_UNPINNED_DESTINATIONS) { break; } } this.displayedDestinations_ = updatedDestinations; } /** * @return Whether the destinations dropdown should be disabled. */ private shouldDisableDropdown_(): boolean { return this.state === State.FATAL_ERROR || (this.destinationState === DestinationState.UPDATED && this.disabled && this.state !== State.NOT_READY); } private computeLoaded_(): boolean { return this.destinationState === DestinationState.ERROR || this.destinationState === DestinationState.UPDATED || (this.destinationState === DestinationState.SET && !!this.destination && (!!this.destination.capabilities || getPrinterTypeForDestination(this.destination) === PrinterType.PDF_PRINTER)); } // <if expr="chromeos_ash or chromeos_lacros"> private computeHasPinSetting_(): boolean { return this.getSetting('pin').available; } // </if> /** * @param e Event containing the key of the recent destination that was * selected, or "seeMore". */ private onSelectedDestinationOptionChange_(e: CustomEvent<string>) { const value = e.detail; if (value === 'seeMore') { this.destinationStore_!.startLoadAllDestinations(); this.$.destinationDialog.get().show(); this.lastUser_ = this.activeUser_; this.isDialogOpen_ = true; } else { this.destinationStore_!.selectDestinationByKey(value); } } /** * @param e Event containing the new active user account. */ private onAccountChange_(e: CustomEvent<string>) { assert(!this.cloudPrintDisabled_); this.shadowRoot!.querySelector('print-preview-user-manager')! .updateActiveUser(e.detail); } private onDialogClose_() { if (this.lastUser_ !== this.activeUser_) { this.updateDropdownDestinations_(); } // Reset the select value if the user dismissed the dialog without // selecting a new destination. this.updateDestinationSelect_(); this.isDialogOpen_ = false; } private updateDestinationSelect_() { if (this.destinationState === DestinationState.ERROR && !this.destination) { return; } if (this.destinationState === DestinationState.INIT || this.destinationState === DestinationState.SELECTED) { return; } const shouldFocus = this.destinationState !== DestinationState.SET && !this.firstLoad; beforeNextRender(this.$.destinationSelect, () => { this.$.destinationSelect.updateDestination(); if (shouldFocus) { this.$.destinationSelect.focus(); } }); } getDestinationStoreForTest(): DestinationStore { return assert(this.destinationStore_!); } // <if expr="chromeos_ash or chromeos_lacros"> /** * @param e Event containing the current destination's EULA URL. */ private updateDestinationEulaUrl_(e: CustomEvent<string>) { if (!this.destination) { return; } this.destination.eulaUrl = e.detail; this.notifyPath('destination.eulaUrl'); } // </if> } declare global { interface HTMLElementTagNameMap { 'print-preview-destination-settings': PrintPreviewDestinationSettingsElement; } } customElements.define( PrintPreviewDestinationSettingsElement.is, PrintPreviewDestinationSettingsElement);
the_stack
import axios from "axios"; import { autobind, throttle } from "core-decorators"; import * as _ from "lodash"; import { action, computed, observable } from "mobx"; import { IPodcastContactFields } from "../components/admin/forms/PodcastContactForm"; import { IPodcastDesignFields } from "../components/admin/forms/PodcastDesignForm"; import { IEpisode, IImages, IPodcast, IUploadProgress, IUser } from "../lib/interfaces"; function clone(obj: object) { return JSON.parse(JSON.stringify(obj)); } export class RootState { @observable.ref public loadingCount: number = 0; @observable.ref public isAuthenticated: boolean = false; @observable.ref public podcast: IPodcast; @observable.ref public podcasts: IPodcast[]; @observable.ref public episodes: IEpisode[] = []; @observable.ref public currentEpisode: IEpisode = null; @observable.ref public uploadProgress: IUploadProgress = {}; @observable.ref public importProgress: object; @observable.ref public billingHistory: any[]; @observable.ref public me: IUser; @observable.ref public env: any; @observable.ref public images: IImages[]; @observable.ref public warningDismissed: boolean; @computed get publishedEpisodes() { return this.episodes.filter(e => { const publishedAt = (new Date(e.publishedAt)).getTime(); const now = (new Date()).getTime(); return (e.published && (publishedAt <= now)); }); } @computed get draftEpisodes() { return this.episodes.filter(e => !e.published); } @computed get scheduledEpisodes(): IEpisode[] { return this.episodes.filter(e => { const publishedAt = (new Date(e.publishedAt)).getTime(); const now = (new Date()).getTime(); return (e.published && (publishedAt > now)); }); } constructor() { this.checkIfAuthenticated(); window.onbeforeunload = () => { let isDirty = false; if (this.uploadProgress) { _.forIn(this.uploadProgress, (value: IUploadProgress, key) => { const progressEvent: any = value.progress; if (progressEvent && progressEvent.loaded && progressEvent.total) { // tslint:disable-next-line:one-line if (Math.ceil((+progressEvent.loaded / progressEvent.total) * 100) !== 100) { isDirty = true; } } }); } return isDirty ? "You have unfinished uploads!" : undefined; }; } @autobind @action public async checkIfAuthenticated() { this.loadingCount++; try { try { const config = await axios.get("/server-config"); this.env = config.data.env; } catch (err) { console.warn(err); } const response = await axios.get("/whoami"); if (response.data.user) { this.me = response.data.user; } this.isAuthenticated = true; } catch (e) { this.isAuthenticated = false; } finally { this.loadingCount--; } } @autobind @action public async signUpUser(firstName: string, lastName: string, email: string, password: string) { try { await axios.post("/sign_up", { firstName, lastName, email, password }); await this.checkIfAuthenticated(); } catch (e) { throw new Error((e.response && e.response.data) || "User registration failed"); } } @autobind @action public async subscribe(token: any, storageLimit: number) { try { const response = await axios.post("/subscribe", { stripeToken: token.id, // JSON.stringify(token), stripeEmail: token.email, storageLimit, }); this.podcast = response.data.podcast; const billingHistory = await axios.post("/billing-history", {}); if (billingHistory.data) { this.billingHistory = _.get(billingHistory, "data.charges.data", []); } return { status: "ok" }; } catch (e) { throw new Error((e.response && e.response.data) || "Payment failed"); } } @autobind @action public async cancelSubscription() { try { const response = await axios.post("/cancel-subscription"); this.podcast = response.data.podcast; } catch (e) { throw new Error((e.response && e.response.data) || "Subscription cancellation failed"); } } @autobind @action public async signInUser(email: string, password: string) { try { await axios.post("/login", { email, password }); await this.checkIfAuthenticated(); } catch (e) { throw new Error("Authentication failed."); } } @autobind @action public async logout() { this.isAuthenticated = false; this.podcast = null; this.episodes = []; this.currentEpisode = null; await axios.get("/logout"); } @autobind @action public async dismissWarning() { this.warningDismissed = true; } @autobind @action public async getPodcastWithEpisodes() { if (this.isAuthenticated && this.podcast) { return; } this.loadingCount++; try { // Core data const response: any = await axios.get("/podcast"); this.podcast = response.data.podcast; this.episodes = response.data.episodes; this.podcasts = response.data.podcasts; this.me = response.data.user; // Billing information const billingHistory: any = await axios.post("/billing-history"); this.billingHistory = _.get(billingHistory, "data.charges.data", []); // Uploaded image information const images = await axios.post("/images/find/podcast", { podcast: this.podcast._id }); this.images = images.data.images; this.loadingCount--; } catch (e) { this.loadingCount--; } } @autobind @action public async getEpisodeById(params: { episodeId: string }) { const { episodeId } = params; if (this.isAuthenticated && this.podcast && this.episodes.length) { const currentEpisode = this.episodes.find(e => e._id === episodeId); if (currentEpisode) { this.currentEpisode = currentEpisode; return; } } this.loadingCount++; try { await this.getPodcastWithEpisodes(); const response: any = await axios.get(`/episode/${episodeId}`); this.currentEpisode = response.data; this.loadingCount--; } catch (e) { this.loadingCount--; throw new Error("Episode not found."); } } @autobind @action public async unsetCurrentEpisode() { this.currentEpisode = null; } @autobind @action public async deleteEpisode(episode: IEpisode) { const { _id } = episode; if (_id && this.isAuthenticated && this.podcast && this.episodes.length) { this.loadingCount++; try { await this.getPodcastWithEpisodes(); const response = await axios.delete(`/episode/${_id}`); if (response.data.podcast) { this.podcast = response.data.podcast; } let episodeIndex = -1; let episodeFound = false; this.episodes.find((e, i) => { const found = e._id === episode._id; if (found) { episodeIndex = i; episodeFound = true; } return found; }); if (episodeFound) { this.episodes = this.episodes.slice(0, episodeIndex).concat(this.episodes.slice(episodeIndex + 1)); } this.currentEpisode = null; this.loadingCount--; } catch (e) { this.loadingCount--; throw new Error("An error ocurred while deleting an episode."); } } } @autobind @action public async updateOrCreatePodcast(podcast: IPodcast) { try { const response: any = await axios.post("/podcast", podcast); this.podcast = response.data; return response; } catch (e) { console.error(e); } } @autobind @action public async publishEpisode(episode: IEpisode) { try { if (!episode.published) { episode.published = true; } if (!episode.publishedAt) { episode.publishedAt = new Date(); } await this.updateOrCreateEpisode(episode); } catch (e) { throw new Error((e.response && e.response.data) || "Episode publish failed."); } } @autobind @action public async unpublishEpisode(episode: IEpisode) { try { episode.published = false; await this.updateOrCreateEpisode(episode); } catch (e) { throw new Error((e.response && e.response.data) || "Episode unpublish failed."); } } @autobind @action public async updateOrCreateEpisode(episode: IEpisode) { try { // If the file has not finished uploading and this is the first upload then we don't publish the episode const published = episode.published; if (!episode.audioUrl) { episode.published = false; } const response: any = await axios.post("/episode", episode); if (response.data.podcast) { this.podcast = response.data.podcast; } response.data.episode.published = published; if (this.episodes.length) { let episodeIndex = -1; let episodeFound = false; this.episodes.find((e, i) => { const found = e._id === episode._id; if (found) { episodeIndex = i; episodeFound = true; } return found; }); if (episodeFound) { this.episodes = this.episodes .slice(0, episodeIndex) // tslint:disable-next-line:prefer-object-spread .concat([response.data.episode]) .concat(this.episodes.slice(episodeIndex + 1)); } else { this.episodes = [response.data.episode, ...this.episodes]; } } else { this.episodes = [response.data.episode]; } this.currentEpisode = response.data.episode; } catch (e) { throw new Error((e.response && e.response.data) || "Episode create or update failed."); } } @autobind @action public async uploadRssFeed(url: string, publish: boolean) { try { const response: any = await axios.post("/import-rss", { url, publish }); if (response.status === 200) { const statusInterval = setInterval(async () => { const res: any = await axios.get("/podcast"); this.podcast = res.data.podcast; this.episodes = res.data.episodes; this.importProgress = res.data.podcast.importProgress; if ((this.importProgress as any).done) { clearInterval(statusInterval); } }, 1000); } return response; } catch (e) { throw new Error((e.response && e.response.data) || "Failed to import RSS feed"); } } @autobind @action public async resetImport() { const response: any = await axios.post("/reset-import"); this.importProgress = response.data.importProgress; } @autobind @action public async updatePodcastContactInformation(contact: IPodcastContactFields) { try { const response: any = await axios.post("/contact", contact); this.podcast = response.data; } catch (e) { throw new Error((e.response && e.response.data) || "Podcast contact page update failed."); } } @autobind @action public async previewPodcastContactInformation(contact: IPodcastContactFields) { try { const contact_preview = { preview: { ...contact }, }; const response: any = await axios.post("/contact", contact_preview); } catch (e) { throw new Error((e.response && e.response.data) || "Podcast contact page preview update failed."); } } @autobind @action public async previewPodcastInformation(data: IPodcast) { try { const podcast_preview = { ...this.podcast, preview: { ...data }, }; const response: any = await axios.post("/podcast", podcast_preview); } catch (e) { throw new Error((e.response && e.response.data) || "Podcast contact page preview update failed."); } } @autobind @action public async updateOrCreateEpisodePreview(episode: IEpisode) { try { // We create an episode preview episode.published = false; episode.preview = true; const response: any = await axios.post("/episode", episode); } catch (e) { throw new Error((e.response && e.response.data) || "Episode create or update failed."); } } @autobind @action public async getUploadPolicy(file: File): Promise<{ uploadUrl: string, publicFileUrl: string }> { try { const response: any = await axios.get("/upload_policy", { params: { filename: file.name, type: file.type }, }); if (!response.data || !response.data.uploadUrl || !response.data.publicFileUrl) { throw new Error("Failed to get upload_policy."); } return response.data; } catch (e) { throw new Error((e.response && e.response.data) || "Failed to get upload_policy."); } } @autobind @action public async uploadFileToCloudStorage(file: File, policyUrl: string, publicFileUrl?: string) { try { const uploadConfig: any = { headers: { "content-type": file.type }, }; uploadConfig.onUploadProgress = (progress: { loaded: number, total: number }) => { const progressEvent = progress; // tslint:disable-next-line:prefer-object-spread this.uploadProgress = Object.assign({}, this.uploadProgress, { [publicFileUrl]: { publicFileUrl, progress, }, }); let currentProgress = 0; if (publicFileUrl && progressEvent && progressEvent.loaded && progressEvent.total) { currentProgress = Math.ceil((+progressEvent.loaded / progressEvent.total) * 100); // If the download is finished we make a request to reflect the changes if (currentProgress === 100) { if (this.isAuthenticated && this.podcast && this.episodes.length) { const currentEpisode = this.episodes.find(e => e.uploadUrl === publicFileUrl); if (currentEpisode) { currentEpisode.audioUrl = publicFileUrl; this.updateOrCreateEpisode(currentEpisode); } } } } }; const uploadResponse: any = await axios.put(policyUrl, file, uploadConfig); // if (publicFileUrl) { // const response = await axios.post("/add_storage_usage", { url: publicFileUrl }); // this.podcast = response.data.podcast; // } return uploadResponse; } catch (e) { // tslint:disable-next-line:prefer-object-spread this.uploadProgress = Object.assign({}, this.uploadProgress, { [publicFileUrl]: { publicFileUrl, error: "File upload failed! " + e, }, }); throw new Error((e.response && e.response.data) || "Failed to get upload_policy."); } } @autobind @action public async addImageEntry(url, episode, podcast) { try { const response = await axios.post("/images/add", { url, episode, podcast }); if (response.data.images) { this.images = response.data.images; } return { status: "ok", }; } catch (e) { return { status: "error", }; } } @autobind @action public async deleteImage(id) { try { const response = await axios.post("/images/delete/" + id, {}); const images = await axios.post("/images/find/podcast", { podcast: this.podcast._id }); this.images = images.data.images; return { status: "ok", }; } catch (e) { return { status: "error", }; } } @autobind @action public async sendInviteForCollab(email: string) { try { const response = await axios.post("/invite-collaborator", { email }); return { message: "An invitation was sent to user " + email, error: "", }; } catch (e) { return { message: "An invitation could not be sent to user " + email, error: "", }; } } @autobind @action public async submitPodcast() { try { const response = await axios.post("/submit-podcast", { podcastId: this.podcast._id, podcastTitle: this.podcast.title, podcastEmail: this.podcast.email, rssFeed: "/p/" + this.podcast.slug + "/rss.xml"}); return { message: "You will receive an email when your podcast is published.", error: "", status: 200, }; } catch (e) { return { message: "Your podcast could not be submitted for publication.", error: "", status: 200, }; } } @autobind @action public async removeCollaborators(collaborators: any[]) { try { const response = await axios.post("/remove-collaborators", { collaborators }); this.podcast = response.data.podcast; return { message: "Collaborators removed sccessfully", error: "", }; } catch (e) { return { message: "Failed to remove collaborators", error: "", }; } } @autobind @action public async switchPodcast(podcastId: string) { try { const res = await axios.post("/switch-podcast", { podcastId }); try { const response: any = await axios.get("/podcast"); this.podcast = response.data.podcast; this.episodes = response.data.episodes; this.podcasts = response.data.podcasts; const billingHistory: any = await axios.post("/billing-history"); this.billingHistory = _.get(billingHistory, "data.charges.data", []); } catch (e) { throw new Error((e.response && e.response.data) || "Failed to load podcast."); } } catch (e) { throw new Error((e.response && e.response.data) || "Failed to load podcast."); } } } export default new RootState();
the_stack
import { EditorState, TextSelection, Transaction, Plugin, } from "prosemirror-state"; import { createMenuPlugin, makeMenuIcon, makeMenuLinkEntry, makeMenuSpacerEntry, addIf, MenuCommand, } from "../shared/menu"; import { EditorView } from "prosemirror-view"; import { imageUploaderEnabled, showImageUploader, } from "../shared/prosemirror-plugins/image-upload"; import type { CommonViewOptions } from "../shared/view"; import { Schema } from "prosemirror-model"; import { undo, redo } from "prosemirror-history"; /** * Shortcut binding that takes in a formatting string and returns a matching setBlockType command * @param formattingText */ export const setBlockTypeCommand = (formattingText: string): MenuCommand => <MenuCommand>setBlockType.bind(null, formattingText); /** * Shortcut binding that takes in a formatting string and returns a matching wrapIn command * @param formattingText */ export const wrapInCommand = (formattingText: string): MenuCommand => <MenuCommand>toggleWrapIn.bind(null, formattingText); export const blockWrapInCommand = (formattingText: string): MenuCommand => <MenuCommand>toggleBlockWrap.bind(null, formattingText); export const insertRawTextCommand = ( text: string, selectFrom?: number, selectTo?: number ): MenuCommand => <MenuCommand>insertRawText.bind(null, text, selectFrom, selectTo); const newTextNode = (schema: Schema, content: string) => schema.text(content); /** * Toggles wrapping selected text in the formatting string; adds newly wrapped text if nothing is selected * @param formattingText The text to wrap the currently selected text in * @param state The current editor state * @param dispatch The dispatch function used to trigger the transaction, set to "null" if you don't want to dispatch */ function toggleWrapIn( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // check if we're unwrapping first if (unwrapIn(formattingText, state, dispatch)) { return true; } return wrapIn(formattingText, state, dispatch); } /** * Wraps the currently selected text with the passed text, creating new text if nothing is selected * @param formattingText The text to wrap the currently selected text in * @param state The current editor state * @param dispatch The dispatch function used to trigger the transaction, set to "null" if you don't want to dispatch */ function wrapIn( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { const textToInsertOnEmptySelection = "your text"; const { from, to } = state.selection; const tr = state.tr.insertText(formattingText, to); if (state.selection.empty) { tr.insertText(textToInsertOnEmptySelection, to); } tr.insertText(formattingText, from).scrollIntoView(); if (dispatch) { let selectionStart = from; // add the format length twice to adjust for the characters added before *and* after the text let selectionEnd = to + formattingText.length * 2; // if the selection was empty, just select the newly added text // and *not* the formatting so the user can start typing over it immediately if (state.selection.empty) { selectionStart = from + formattingText.length; selectionEnd = selectionStart + textToInsertOnEmptySelection.length; } // set the selection to include our newly added characters tr.setSelection( TextSelection.create( state.apply(tr).doc, selectionStart, selectionEnd ) ); dispatch(tr); } return true; } /** * Unwraps the currently selected text if it is already wrapped in the passed text * @param formattingText The text to wrap the currently selected text in * @param state The current editor state * @param dispatch The dispatch function used to trigger the transaction, set to "null" if you don't want to dispatch */ function unwrapIn( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // if the selection is empty, then there is nothing to unwrap if (state.selection.empty) { return false; } const { from, to } = state.selection; const selectedText = state.doc.textBetween(from, to); const precedingString = selectedText.slice(0, formattingText.length); const postcedingString = selectedText.slice(formattingText.length * -1); if ( precedingString !== formattingText || postcedingString !== formattingText ) { return false; } if (dispatch) { const tr = state.tr; // unwrap the text and set into the document const unwrappedText = selectedText.slice( formattingText.length, formattingText.length * -1 ); tr.replaceSelectionWith(newTextNode(tr.doc.type.schema, unwrappedText)); // set the selected text to the unwrapped text tr.setSelection( TextSelection.create( state.apply(tr).doc, from, to - formattingText.length * 2 ) ); dispatch(tr); } return true; } /** * Sets/unsets the block type of either selected (set for just the selection) or unselected (set at the beginning of the line) text * @param formattingText The text to prepend to the currently selected block * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function setBlockType( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // check first if we are toggling this entire block or toggling just the selected content if (setMultilineSelectedBlockType(formattingText, state, dispatch)) { return true; } return setSingleLineBlockType(formattingText, state, dispatch); } /** * Returns any block formatting characters (plus trailing space) at the very start of the passed text * @param text The text to check for leading block characters */ function matchLeadingBlockCharacters(text: string) { // TODO this might be too aggressive... remove based on a whitelist instead? // TODO HACK assumes all block types are non-letter characters followed by a single space return /^[^a-zA-Z]+\s{1}(?=[a-zA-Z_*[!]|$)/.exec(text)?.[0] || ""; } /** * Places/removes the passed text at the very beginning of the text block the selection exists in, * potentially removing other block text to do so * @param formattingText The text to prepend to the currently selected block * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function setSingleLineBlockType( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // get the "from" position of the cursor/selection only const { from } = state.selection as TextSelection; // get all text from the start of the doc to our cursor const textToCursor = state.doc.cut(0, from).textContent; // doc position is index differently (0 vs 1 indexed), so offset const stateOffset = 1; // look backwards for the most recent newline char const prevNewlineIndex = textToCursor.lastIndexOf("\n"); // store where we're inserting our text; this will be our working point from now on let textInsertPos: number; // if there is no newline, set to beginning of doc if (prevNewlineIndex === -1) { textInsertPos = stateOffset; } else { // otherwise, set based on the index textInsertPos = prevNewlineIndex + stateOffset + "\n".length; } // always trail the formatting text with an empty space const trailingText = " "; // get all text starting from our insert point to check if we're toggling on/off const textFromInsert = state.doc.cut(textInsertPos).textContent; // check if *any* block type is already set const leadingBlockChars = matchLeadingBlockCharacters(textFromInsert); let tr = state.tr; if (leadingBlockChars.length) { // remove all leading block chars tr = tr.delete(textInsertPos, textInsertPos + leadingBlockChars.length); } let isTogglingOff = false; // check if the text at that index is already set to our formatting text if (leadingBlockChars === formattingText + trailingText) { isTogglingOff = true; } if (!isTogglingOff) { // add the formatting text tr = tr.insertText(formattingText + trailingText, textInsertPos); } if (dispatch) { tr = tr.scrollIntoView(); dispatch(tr); } return true; } /** * Places/removes the passed text at the very beginning of each selected text line, creating a preceding newline if necessary * @param formattingText The text to prepend to the currently selected block * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function setMultilineSelectedBlockType( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // if the selection is empty, then this command is not valid if (state.selection.empty) { return false; } let { from } = state.selection; const selectedText = state.doc.cut(from, state.selection.to).textContent; // if there are no line breaks inside this text, then treat it as if we're editing the whole block if (!selectedText.includes("\n")) { return false; } // always trail the formatting text with a space const trailingText = " "; let tr = state.tr; // check the very first character on each line // if even a single line is missing, toggle all missing ON, else toggle all OFF const lines = selectedText.split("\n"); const isTogglingOn = lines.some( (text) => !text.startsWith(formattingText + trailingText) ); // doc position is index differently (0 vs 1 indexed), so offset const stateOffset = 1; let rangeFrom = from; lines.forEach((l) => { let formattedLine: string; const leadingBlockChars = matchLeadingBlockCharacters(l); const beginsWithText = leadingBlockChars === formattingText + trailingText; if (isTogglingOn && beginsWithText) { // toggling on and already begins with text... leave it formattedLine = l; } else if (isTogglingOn && leadingBlockChars.length) { // toggling on and another block is there... replace formattedLine = formattingText + trailingText + l.slice(leadingBlockChars.length); } else if (isTogglingOn) { // toggling on and nothing is there... just add formattedLine = formattingText + trailingText + l; } else { // toggling off... remove whatever leading block chars are there formattedLine = l.slice(leadingBlockChars.length); } const rangeTo = rangeFrom + l.length; // we can't set an empty text node, so if the line is empty, just delete the text instead if (formattedLine.length) { tr = tr.replaceRangeWith( rangeFrom, rangeTo, newTextNode(tr.doc.type.schema, formattedLine) ); } else { tr = tr.deleteRange(rangeFrom, rangeTo); } // set the start of the next line to the altered line's length + 1 character for the removed (by .split) newline char rangeFrom += formattedLine.length + "\n".length; }); // if the character immediately preceding the selection isn't a newline, add one if ( from > stateOffset && state.doc.textBetween(from - stateOffset, from) !== "\n" ) { tr = tr.insertText("\n", from, from); from += "\n".length; rangeFrom += "\n".length; } if (dispatch) { // the end of the selection is the calculated "rangeFrom", which includes all our added/removed chars // subtract a single \n's length from the end that is overadjusted in the calculation (for splitting on \n) const selectionEnd = rangeFrom - "\n".length; tr.setSelection( TextSelection.create(state.apply(tr).doc, from, selectionEnd) ); tr.scrollIntoView(); dispatch(tr); } return true; } //TODO document function toggleBlockWrap( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // check if we're unwrapping first if (blockUnwrapIn(formattingText, state, dispatch)) { return true; } return blockWrapIn(formattingText, state, dispatch); } /** * Wraps/unwraps a multiline block in the given formatting text, adding newlines before and after the selection if necessary * @param formattingText The text to wrap/unwrap the currently selected block in * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function blockWrapIn( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // empty selection, not valid if (state.selection.empty) { const placeholderText = "type here"; const insertedBlock = `\n${formattingText}\n${placeholderText}\n${formattingText}\n`; const newlineOffset = 2; // account for two inserted newlines return insertRawText( insertedBlock, formattingText.length + newlineOffset, formattingText.length + placeholderText.length + newlineOffset, state, dispatch ); } let { from, to } = state.selection; // check if we need to unwrap if (blockUnwrapIn(formattingText, state, dispatch)) { return true; } // wrap the selected block in code fences, prepending/appending newlines if necessary let tr = state.tr; // if the character immediately preceding the selection isn't a newline, add one if (from > 0 && state.doc.textBetween(from - 1, from) !== "\n") { tr = tr.insertText("\n", from, from); from += 1; to += 1; } // if the character immediately postceding the selection isn't a newline, add one if ( to + 1 < state.doc.content.size && state.doc.textBetween(to, to + 1) !== "\n" ) { tr = tr.insertText("\n", to + 1, to + 1); to += 1; } // add this char before and after the selection along with the formatting text const surroundingChar = "\n"; // insert the code fences from the end first so we don't mess up our from index tr.insertText(surroundingChar + formattingText, to); tr.insertText(formattingText + surroundingChar, from); if (dispatch) { // adjust our new text selection based on how many characters we added const addedTextModifier = surroundingChar.length + formattingText.length; tr.setSelection( TextSelection.create( state.apply(tr).doc, from, // add modifier twice, once for added leading text, once for added trailing text to + addedTextModifier * 2 ) ); tr.scrollIntoView(); dispatch(tr); } return true; } /** * Unwraps a multiline block in the given formatting text if able * @param formattingText The text to unwrap from currently selected block * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function blockUnwrapIn( formattingText: string, state: EditorState, dispatch: (tr: Transaction) => void ) { // no selection, not valid if (state.selection.empty) { return false; } const { from, to } = state.selection; const selectedText = state.doc.textBetween(from, to); const surroundingChar = "\n"; const totalFormattedLength = formattingText.length + surroundingChar.length; const precedingString = selectedText.slice(0, totalFormattedLength); const postcedingString = selectedText.slice(totalFormattedLength * -1); if ( precedingString !== formattingText + surroundingChar || postcedingString !== surroundingChar + formattingText ) { return false; } let tr = state.tr; // remove our wrapping chars, starting with the trailing text so we don't disturb the from index tr = tr.delete(to - totalFormattedLength, to); tr = tr.delete(from, from + totalFormattedLength); if (dispatch) { tr.setSelection( TextSelection.create( state.apply(tr).doc, from, // add modifier twice, once for added leading text, once for added trailing text to - totalFormattedLength * 2 ) ); tr.scrollIntoView(); dispatch(tr); } return true; } /** * Inserts the given text at the cursor, replacing selected text if applicable * @param text The text to insert * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ function insertRawText( text: string, selectFrom: number, selectTo: number, state: EditorState, dispatch: (tr: Transaction) => void ) { let tr = state.tr; const { from } = state.selection; if (state.selection.empty) { tr = tr.insertText(text, from); } else { tr = tr.replaceSelectionWith(newTextNode(tr.doc.type.schema, text)); } if (dispatch) { // if the select range is declared, select the specified range in the added text if ( typeof selectFrom !== "undefined" && typeof selectTo !== "undefined" ) { tr = tr.setSelection( TextSelection.create( state.apply(tr).doc, from + selectFrom, from + selectTo ) ); } else { // if the range is NOT declared, set the cursor to before the inserted text tr = tr.setSelection( TextSelection.create(state.apply(tr).doc, from) ); } tr = tr.scrollIntoView(); dispatch(tr); } return true; } /** * Inserts a link at the cursor, optionally placing it around the currenly selected text if able * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ export function insertLinkCommand( state: EditorState, dispatch: (tr: Transaction) => void ): boolean { // TODO what dummy link to use? const dummyLink = "https://www.stackoverflow.com/"; // TODO what should we select - text or link? if (state.selection.empty) { return insertRawText( "[text](" + dummyLink + ")", 1, 5, state, dispatch ); } const { from, to } = state.selection; const selectedText = state.doc.textBetween(from, to); const insertedText = `[${selectedText}](${dummyLink})`; //TODO magic numbers! const selectFrom = 3 + selectedText.length; const selectTo = selectFrom + dummyLink.length; // insert the link with the link selected for easy typeover return insertRawText(insertedText, selectFrom, selectTo, state, dispatch); } /** * Inserts a basic table at the cursor * @param state The current editor state * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch */ export function insertTableCommand( state: EditorState, dispatch: (tr: Transaction) => void ): boolean { const tableMarkdown = ` | Column A | Column B | | -------- | -------- | | Cell 1 | Cell 2 | | Cell 3 | Cell 4 | `; if (state.selection.empty) { return insertRawText(tableMarkdown, 1, 1, state, dispatch); } } //TODO function indentBlockCommand(): boolean { return false; } //TODO function unIndentBlockCommand(): boolean { return false; } export const boldCommand = wrapInCommand("**"); export const emphasisCommand = wrapInCommand("*"); export const inlineCodeCommand = wrapInCommand("`"); export const indentCommand = indentBlockCommand; export const unindentBlock = unIndentBlockCommand; export const headerCommand = setBlockTypeCommand("#"); export const strikethroughCommand = wrapInCommand("~~"); export const blockquoteCommand = setBlockTypeCommand(">"); export const orderedListCommand = setBlockTypeCommand("1."); export const unorderedListCommand = setBlockTypeCommand("-"); export const insertHorizontalRuleCommand = insertRawTextCommand("\n---\n"); export const insertCodeblockCommand = blockWrapInCommand("```"); export function insertImageCommand( state: EditorState, dispatch: (tr: Transaction) => void, view: EditorView ): boolean { if (!imageUploaderEnabled(view)) { return false; } if (!dispatch) return true; showImageUploader(view); return true; } export const createMenu = (options: CommonViewOptions): Plugin => createMenuPlugin( [ { key: "toggleHeading", command: headerCommand, dom: makeMenuIcon("Header", "Heading", "heading-btn"), }, { key: "togglBold", command: boldCommand, dom: makeMenuIcon("Bold", "Bold", "bold-btn"), }, { key: "toggleEmphasis", command: emphasisCommand, dom: makeMenuIcon("Italic", "Italic", "italic-btn"), }, { key: "toggleCode", command: inlineCodeCommand, dom: makeMenuIcon("Code", "Inline code", "code-btn"), }, addIf( { key: "toggleStrikethrough", command: strikethroughCommand, dom: makeMenuIcon( "Strikethrough", "Strikethrough", "strike-btn" ), }, options.parserFeatures.extraEmphasis ), makeMenuSpacerEntry(), { key: "toggleLink", command: insertLinkCommand, dom: makeMenuIcon("Link", "Insert link", "insert-link-btn"), }, { key: "toggleBlockquote", command: blockquoteCommand, dom: makeMenuIcon("Quote", "Blockquote", "blockquote-btn"), }, { key: "insertCodeblock", command: insertCodeblockCommand, dom: makeMenuIcon( "Codeblock", "Insert code block", "code-block-btn" ), }, addIf( { key: "insertImage", command: insertImageCommand, dom: makeMenuIcon( "Image", "Insert image", "insert-image-btn" ), }, !!options.imageUpload?.handler ), addIf( { key: "insertTable", command: insertTableCommand, dom: makeMenuIcon( "Table", "Insert table", "insert-table-btn" ), }, options.parserFeatures.tables ), makeMenuSpacerEntry(), { key: "toggleOrderedList", command: orderedListCommand, dom: makeMenuIcon( "OrderedList", "Numbered list", "numbered-list-btn" ), }, { key: "toggleUnorderedList", command: unorderedListCommand, dom: makeMenuIcon( "UnorderedList", "Bulleted list", "bullet-list-btn" ), }, { key: "insertRule", command: insertHorizontalRuleCommand, dom: makeMenuIcon( "HorizontalRule", "Insert Horizontal rule", "horizontal-rule-btn" ), }, makeMenuSpacerEntry(() => false, ["sm:d-inline-block"]), { key: "undo", command: undo, dom: makeMenuIcon("Undo", "Undo", "undo-btn", [ "sm:d-inline-block", ]), visible: () => false, }, { key: "redo", command: redo, dom: makeMenuIcon("Refresh", "Redo", "redo-btn", [ "sm:d-inline-block", ]), visible: () => false, }, makeMenuSpacerEntry(), //TODO eventually this will mimic the "help" dropdown in the prod editor makeMenuLinkEntry("Help", "Help", options.editorHelpLink), ], options.menuParentContainer );
the_stack
export function polyfill(w: Window = window, d = document) { // return if scroll behavior is supported and polyfill is not forced if ( 'scrollBehavior' in d.documentElement.style && w.__forceSmoothScrollPolyfill__ !== true ) { return; } // globals var Element = w.HTMLElement || w.Element; var SCROLL_TIME = 468; // object gathering original scroll methods var original = { scroll: w.scroll || w.scrollTo, scrollBy: w.scrollBy, elementScroll: Element.prototype.scroll || scrollElement, scrollIntoView: Element.prototype.scrollIntoView, }; // define timing method var now = w.performance && w.performance.now ? w.performance.now.bind(w.performance) : Date.now; /** * indicates if a the current browser is made by Microsoft * @method isMicrosoftBrowser * @param {String} userAgent * @returns {Boolean} */ function isMicrosoftBrowser(userAgent) { var userAgentPatterns = ['MSIE ', 'Trident/', 'Edge/']; return new RegExp(userAgentPatterns.join('|')).test(userAgent); } /* * IE has rounding bug rounding down clientHeight and clientWidth and * rounding up scrollHeight and scrollWidth causing false positives * on hasScrollableSpace */ var ROUNDING_TOLERANCE = isMicrosoftBrowser(w.navigator.userAgent) ? 1 : 0; /** * changes scroll position inside an element * @method scrollElement * @param {Number} x * @param {Number} y * @returns {undefined} */ function scrollElement(x, y) { this.scrollLeft = x; this.scrollTop = y; } /** * returns result of applying ease math function to a number * @method ease * @param {Number} k * @returns {Number} */ function ease(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); } /** * indicates if a smooth behavior should be applied * @method shouldBailOut * @param {Number|Object} firstArg * @returns {Boolean} */ function shouldBailOut(firstArg) { if ( firstArg === null || typeof firstArg !== 'object' || firstArg.behavior === undefined || firstArg.behavior === 'auto' || firstArg.behavior === 'instant' ) { // first argument is not an object/null // or behavior is auto, instant or undefined return true; } if (typeof firstArg === 'object' && firstArg.behavior === 'smooth') { // first argument is an object and behavior is smooth return false; } // throw error when behavior is not supported throw new TypeError( 'behavior member of ScrollOptions ' + firstArg.behavior + ' is not a valid value for enumeration ScrollBehavior.', ); } /** * indicates if an element has scrollable space in the provided axis * @method hasScrollableSpace * @param {Node} el * @param {String} axis * @returns {Boolean} */ function hasScrollableSpace(el, axis) { if (axis === 'Y') { return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight; } if (axis === 'X') { return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth; } } /** * indicates if an element has a scrollable overflow property in the axis * @method canOverflow * @param {Node} el * @param {String} axis * @returns {Boolean} */ function canOverflow(el, axis) { var overflowValue = w.getComputedStyle(el, null)['overflow' + axis]; return overflowValue === 'auto' || overflowValue === 'scroll'; } /** * indicates if an element can be scrolled in either axis * @method isScrollable * @param {Node} el * @param {String} axis * @returns {Boolean} */ function isScrollable(el) { var isScrollableY = hasScrollableSpace(el, 'Y') && canOverflow(el, 'Y'); var isScrollableX = hasScrollableSpace(el, 'X') && canOverflow(el, 'X'); return isScrollableY || isScrollableX; } /** * finds scrollable parent of an element * @method findScrollableParent * @param {Node} el * @returns {Node} el */ function findScrollableParent(el) { while (el !== d.body && isScrollable(el) === false) { el = el.parentNode || el.host; } return el; } /** * self invoked function that, given a context, steps through scrolling * @method step * @param {Object} context * @returns {undefined} */ function step(context) { var time = now(); var value; var currentX; var currentY; var elapsed = (time - context.startTime) / SCROLL_TIME; // avoid elapsed times higher than one elapsed = elapsed > 1 ? 1 : elapsed; // apply easing to elapsed time value = ease(elapsed); currentX = context.startX + (context.x - context.startX) * value; currentY = context.startY + (context.y - context.startY) * value; context.method.call(context.scrollable, currentX, currentY); // scroll more if we have not reached our destination if (currentX !== context.x || currentY !== context.y) { w.requestAnimationFrame(step.bind(w, context)); } } /** * scrolls window or element with a smooth behavior * @method smoothScroll * @param {Object|Node} el * @param {Number} x * @param {Number} y * @returns {undefined} */ function smoothScroll(el, x, y) { var scrollable; var startX; var startY; var method; var startTime = now(); // define scroll context if (el === d.body) { scrollable = w; startX = w.scrollX || w.pageXOffset; startY = w.scrollY || w.pageYOffset; method = original.scroll; } else { scrollable = el; startX = el.scrollLeft; startY = el.scrollTop; method = scrollElement; } // scroll looping over a frame step({ scrollable: scrollable, method: method, startTime: startTime, startX: startX, startY: startY, x: x, y: y, }); } // ORIGINAL METHODS OVERRIDES // w.scroll and w.scrollTo w.scroll = w.scrollTo = function () { // avoid action when no arguments are passed if (arguments[0] === undefined) { return; } // avoid smooth behavior if not required if (shouldBailOut(arguments[0]) === true) { original.scroll.call( w, arguments[0].left !== undefined ? arguments[0].left : typeof arguments[0] !== 'object' ? arguments[0] : w.scrollX || w.pageXOffset, // use top prop, second argument if present or fallback to scrollY arguments[0].top !== undefined ? arguments[0].top : arguments[1] !== undefined ? arguments[1] : w.scrollY || w.pageYOffset, ); return; } // LET THE SMOOTHNESS BEGIN! smoothScroll.call( w, d.body, arguments[0].left !== undefined ? ~~arguments[0].left : w.scrollX || w.pageXOffset, arguments[0].top !== undefined ? ~~arguments[0].top : w.scrollY || w.pageYOffset, ); }; // w.scrollBy w.scrollBy = function () { // avoid action when no arguments are passed if (arguments[0] === undefined) { return; } // avoid smooth behavior if not required if (shouldBailOut(arguments[0])) { original.scrollBy.call( w, arguments[0].left !== undefined ? arguments[0].left : typeof arguments[0] !== 'object' ? arguments[0] : 0, arguments[0].top !== undefined ? arguments[0].top : arguments[1] !== undefined ? arguments[1] : 0, ); return; } // LET THE SMOOTHNESS BEGIN! smoothScroll.call( w, d.body, ~~arguments[0].left + (w.scrollX || w.pageXOffset), ~~arguments[0].top + (w.scrollY || w.pageYOffset), ); }; // Element.prototype.scroll and Element.prototype.scrollTo Element.prototype.scroll = Element.prototype.scrollTo = function () { // avoid action when no arguments are passed if (arguments[0] === undefined) { return; } // avoid smooth behavior if not required if (shouldBailOut(arguments[0]) === true) { // if one number is passed, throw error to match Firefox implementation if (typeof arguments[0] === 'number' && arguments[1] === undefined) { throw new SyntaxError('Value could not be converted'); } original.elementScroll.call( this, // use left prop, first number argument or fallback to scrollLeft arguments[0].left !== undefined ? ~~arguments[0].left : typeof arguments[0] !== 'object' ? ~~arguments[0] : this.scrollLeft, // use top prop, second argument or fallback to scrollTop arguments[0].top !== undefined ? ~~arguments[0].top : arguments[1] !== undefined ? ~~arguments[1] : this.scrollTop, ); return; } var left = arguments[0].left; var top = arguments[0].top; // LET THE SMOOTHNESS BEGIN! smoothScroll.call( this, this, typeof left === 'undefined' ? this.scrollLeft : ~~left, typeof top === 'undefined' ? this.scrollTop : ~~top, ); }; // Element.prototype.scrollBy Element.prototype.scrollBy = function () { // avoid action when no arguments are passed if (arguments[0] === undefined) { return; } // avoid smooth behavior if not required if (shouldBailOut(arguments[0]) === true) { original.elementScroll.call( this, arguments[0].left !== undefined ? ~~arguments[0].left + this.scrollLeft : ~~arguments[0] + this.scrollLeft, arguments[0].top !== undefined ? ~~arguments[0].top + this.scrollTop : ~~arguments[1] + this.scrollTop, ); return; } this.scroll({ left: ~~arguments[0].left + this.scrollLeft, top: ~~arguments[0].top + this.scrollTop, behavior: arguments[0].behavior, }); }; // Element.prototype.scrollIntoView Element.prototype.scrollIntoView = function () { // avoid smooth behavior if not required if (shouldBailOut(arguments[0]) === true) { original.scrollIntoView.call( this, arguments[0] === undefined ? true : arguments[0], ); return; } // LET THE SMOOTHNESS BEGIN! var scrollableParent = findScrollableParent(this); var parentRects = scrollableParent.getBoundingClientRect(); var clientRects = this.getBoundingClientRect(); if (scrollableParent !== d.body) { // reveal element inside parent smoothScroll.call( this, scrollableParent, scrollableParent.scrollLeft + clientRects.left - parentRects.left, scrollableParent.scrollTop + clientRects.top - parentRects.top, ); // reveal parent in viewport unless is fixed if (w.getComputedStyle(scrollableParent).position !== 'fixed') { w.scrollBy({ left: parentRects.left, top: parentRects.top, behavior: 'smooth', }); } } else { // reveal element in viewport w.scrollBy({ left: clientRects.left, top: clientRects.top, behavior: 'smooth', }); } }; }
the_stack
import { CommonOffset } from "@akashic/pdi-types"; /** * 変換行列を表すインターフェース。 * 通常ゲーム開発者が本インターフェースを直接利用する事はない。 */ export interface Matrix { /** * 変更フラグ。 * 本フラグが立っていても特に何も処理はされない。 * 本フラグの操作、本フラグを参照して値を再計算することは、いずれも利用する側で適切に処理をする必要がある。 * @private */ _modified: boolean; /** * 変換本体。 * CanvasRenderingContext2D#transformの値と等しい。 * ``` * a c e * [ b d f ] * 0 0 1 * ``` * 配列の添え字では、 a(m11): 0, b(m12): 1, c(m21): 2, d(m22): 3, e(dx): 4, f(dy): 5 となる。 * 参考: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/transform * @private */ // TODO: (GAMEDEV-844) Matrix#_matrix と二重名称になっているのでRendererと合わせて再検討 _matrix: [number, number, number, number, number, number]; /** * この変換行列に別の変換行列を右側から掛け合わせる。 * @param matrix 掛け合わせる変換行列 */ multiply(matrix: Matrix): void; /** * この変換行列に別の変換行列を左側から掛け合わせる。 * @param matrix 掛け合わせる変換行列 */ multiplyLeft(matrix: Matrix): void; /** * この変換行列に別の変換行列を掛け合わせた新しい変換行列を返す。 * @param matrix 掛け合わせる変換行列 */ multiplyNew(matrix: Matrix): Matrix; /** * 2D object利用の一般的な値を基に変換行列の値を再計算する。 * @param width 対象の横幅 * @param heigth 対象の縦幅 * @param scaleX 対象の横方向への拡大率 * @param scaleY 対象の縦方向への拡大率 * @param angle 角度。単位は `degree` であり `radian` ではない * @param x x座標 * @param y y座標 * @param anchorX アンカーの横位置。単位は相対値(左端が 0、中央が 0.5、右端が 1.0)である。 * @param anchorY アンカーの縦位置。単位は相対値(上端が 0、中央が 0.5、下端が 1.0)である。 */ update( width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number, anchorX: number | null, anchorY: number | null ): void; /** * `update()` によって得られる行列の逆変換になるよう変換行列の値を再計算する。 * @param width 対象の横幅 * @param heigth 対象の縦幅 * @param scaleX 対象の横方向への拡大率 * @param scaleY 対象の縦方向への拡大率 * @param angle 角度。単位は `degree` であり `radian` ではない * @param x x座標 * @param y y座標 * @param anchorX アンカーの横位置。単位は相対値(左端が 0、中央が 0.5、右端が 1.0)である。 * @param anchorY アンカーの縦位置。単位は相対値(上端が 0、中央が 0.5、下端が 1.0)である。 */ updateByInverse( width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number, anchorX: number | null, anchorY: number | null ): void; /** * 値を単位行列にリセットする。x/yの座標情報を初期値に反映させることも出来る。 * @param x x座標。省略時は0として処理される * @param y y座標。省略時は0として処理される */ reset(x?: number, y?: number): void; /** * この変換行列と同じ値を持つ変換行列を新しく作って返す。 */ clone(): Matrix; /** * 拡縮を変換行列に反映させる。 * @param x X方向の拡縮律 * @param y y方向の拡縮律 */ scale(x: number, y: number): void; /** * この変換行列を逆行列に変換した結果を引数の座標系に適用した座標値を返す。 * この変換行列の値自体や、引数の値は変更されない。 * @param point 逆行列を適用する座標 */ multiplyInverseForPoint(point: CommonOffset): CommonOffset; /** * この変換行列と引数の座標系が表す行列の積を返す。 * @param point この変換行列との積を求める座標 */ multiplyPoint(point: CommonOffset): CommonOffset; } /** * 変換行列を一般的なJavaScriptのみで表したクラス。 * 通常ゲーム開発者が本クラスを直接利用する事はない。 * 各フィールド、メソッドの詳細は `Matrix` インターフェースの説明を参照。 */ export class PlainMatrix { /** * @private */ _modified: boolean; /** * @private */ _matrix: [number, number, number, number, number, number]; /** * 無変換の変換行列を表す `PlainMatrix` のインスタンスを作成する。 */ constructor(); /** * 2Dオブジェクト利用の一般的な値を元に変換行列を表す `PlainMatrix` のインスタンスを生成する。 * @param width 対象の横幅 * @param height 対象の縦幅 * @param scaleX 対象の横方向への拡大率 * @param scaleY 対象の縦方向への拡大率 * @param angle 角度。単位は `degree` であり `radian` ではない * @param anchorX アンカーの横位置。単位は相対値(左端が 0、中央が 0.5、右端が 1.0)である。 * @param anchorY アンカーの縦位置。単位は相対値(上端が 0、中央が 0.5、下端が 1.0)である。 */ constructor(width: number, height: number, scaleX: number, scaleY: number, angle: number, anchorX: number, anchorY: number); /** * 指定の `Matrix` と同じ変換行列を表す `PlainMatrix` のインスタンスを生成する。 */ constructor(src: Matrix); constructor( widthOrSrc?: number | Matrix, height?: number, scaleX?: number, scaleY?: number, angle?: number, anchorX?: number, anchorY?: number ) { // TODO: (GAMEDEV-845) Float32Arrayの方が速いらしいので、polyfillして使うかどうか検討 if (widthOrSrc === undefined) { this._modified = false; this._matrix = [1, 0, 0, 1, 0, 0]; } else if (typeof widthOrSrc === "number") { this._modified = false; this._matrix = new Array<number>(6) as [number, number, number, number, number, number]; // @ts-ignore this.update(widthOrSrc, height, scaleX, scaleY, angle, 0, 0, anchorX, anchorY); } else { this._modified = widthOrSrc._modified; this._matrix = [ widthOrSrc._matrix[0], widthOrSrc._matrix[1], widthOrSrc._matrix[2], widthOrSrc._matrix[3], widthOrSrc._matrix[4], widthOrSrc._matrix[5] ]; } } update( width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number, anchorX: number | null, anchorY: number | null ): void { if (anchorX == null || anchorY == null) { this._updateWithoutAnchor(width, height, scaleX, scaleY, angle, x, y); return; } // ここで求める変換行列Mは、引数で指定された変形を、拡大・回転・平行移動の順に適用するものである。 // 変形の原点は (anchorX * width, anchorY * height) である。従って // M = A^-1 T R S A // である。ただしここでA, S, R, Tは、それぞれ以下を表す変換行列である: // A: アンカーを原点に移す(平行移動する)変換 // S: X軸方向にscaleX倍、Y軸方向にscaleY倍する変換 // R: angle度だけ回転する変換 // T: x, yの値だけ平行移動する変換 // それらは次のように表せる: // 1 0 -w sx 0 0 c -s 0 1 0 x // A = [ 0 1 -h] S = [ 0 sy 0] R = [ s c 0] T = [ 0 1 y] // 0 0 1 0 0 1 0 0 1 0 0 1 // ここで sx, sy は scaleX, scaleY であり、c, s は cos(theta), sin(theta) // (ただし theta = angle * PI / 180)、w = anchorX * width, h = anchorY * height である。 // 以下の実装は、M の各要素をそれぞれ計算して直接求めている。 const r = (angle * Math.PI) / 180; const _cos = Math.cos(r); const _sin = Math.sin(r); const a = _cos * scaleX; const b = _sin * scaleX; const c = _sin * scaleY; const d = _cos * scaleY; const w = anchorX * width; const h = anchorY * height; this._matrix[0] = a; this._matrix[1] = b; this._matrix[2] = -c; this._matrix[3] = d; this._matrix[4] = -a * w + c * h + x; this._matrix[5] = -b * w - d * h + y; } /** * このメソッドは anchorX, anchorY が存在しなかった当時との互換性のため存在する。将来この互換性を破棄する時に削除する予定である。 * @private */ _updateWithoutAnchor(width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number): void { // ここで求める変換行列Mは、引数で指定された変形を、拡大・回転・平行移動の順に適用するものである。 // 変形の原点は引数で指定された矩形の中心、すなわち (width/2, height/2) の位置である。従って // M = A^-1 T R S A // である。ただしここでA, S, R, Tは、それぞれ以下を表す変換行列である: // A: 矩形の中心を原点に移す(平行移動する)変換 // S: X軸方向にscaleX倍、Y軸方向にscaleY倍する変換 // R: angle度だけ回転する変換 // T: x, yの値だけ平行移動する変換 // それらは次のように表せる: // 1 0 -w sx 0 0 c -s 0 1 0 x // A = [ 0 1 -h] S = [ 0 sy 0] R = [ s c 0] T = [ 0 1 y] // 0 0 1 0 0 1 0 0 1 0 0 1 // ここで sx, sy は scaleX, scaleY であり、c, s は cos(theta), sin(theta) // (ただし theta = angle * PI / 180)、w = (width / 2), h = (height / 2) である。 // 以下の実装は、M の各要素をそれぞれ計算して直接求めている。 const r = (angle * Math.PI) / 180; const _cos = Math.cos(r); const _sin = Math.sin(r); const a = _cos * scaleX; const b = _sin * scaleX; const c = _sin * scaleY; const d = _cos * scaleY; const w = width / 2; const h = height / 2; this._matrix[0] = a; this._matrix[1] = b; this._matrix[2] = -c; this._matrix[3] = d; this._matrix[4] = -a * w + c * h + w + x; this._matrix[5] = -b * w - d * h + h + y; } updateByInverse( width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number, anchorX: number | null, anchorY: number | null ): void { if (anchorX == null || anchorY == null) { this._updateByInverseWithoutAnchor(width, height, scaleX, scaleY, angle, x, y); return; } // ここで求める変換行列は、update() の求める行列Mの逆行列、M^-1である。update() のコメントに記述のとおり、 // M = A^-1 T R S A // であるから、 // M^-1 = A^-1 S^-1 R^-1 T^-1 A // それぞれは次のように表せる: // 1 0 w 1/sx 0 0 c s 0 1 0 -x+w // A^-1 = [ 0 1 h] S^-1 = [ 0 1/sy 0] R^-1 = [ -s c 0] T^-1 = [ 0 1 -y+h] // 0 0 1 0 0 1 0 0 1 0 0 1 // ここで各変数は update() のコメントのものと同様である。 // 以下の実装は、M^-1 の各要素をそれぞれ計算して直接求めている。 const r = (angle * Math.PI) / 180; const _cos = Math.cos(r); const _sin = Math.sin(r); const a = _cos / scaleX; const b = _sin / scaleY; const c = _sin / scaleX; const d = _cos / scaleY; const w = anchorX * width; const h = anchorY * height; this._matrix[0] = a; this._matrix[1] = -b; this._matrix[2] = c; this._matrix[3] = d; this._matrix[4] = -a * x - c * y + w; this._matrix[5] = b * x - d * y + h; } /** * このメソッドは anchorX, anchorY が存在しなかった当時との互換性のため存在する。将来この互換性を破棄する時に削除する予定である。 * @private */ _updateByInverseWithoutAnchor( width: number, height: number, scaleX: number, scaleY: number, angle: number, x: number, y: number ): void { // ここで求める変換行列は、update() の求める行列Mの逆行列、M^-1である。update() のコメントに記述のとおり、 // M = A^-1 T R S A // であるから、 // M^-1 = A^-1 S^-1 R^-1 T^-1 A // それぞれは次のように表せる: // 1 0 w 1/sx 0 0 c s 0 1 0 -x // A^-1 = [ 0 1 h] S^-1 = [ 0 1/sy 0] R^-1 = [ -s c 0] T^-1 = [ 0 1 -y] // 0 0 1 0 0 1 0 0 1 0 0 1 // ここで各変数は update() のコメントのものと同様である。 // 以下の実装は、M^-1 の各要素をそれぞれ計算して直接求めている。 const r = (angle * Math.PI) / 180; const _cos = Math.cos(r); const _sin = Math.sin(r); const a = _cos / scaleX; const b = _sin / scaleY; const c = _sin / scaleX; const d = _cos / scaleY; const w = width / 2; const h = height / 2; this._matrix[0] = a; this._matrix[1] = -b; this._matrix[2] = c; this._matrix[3] = d; this._matrix[4] = -a * (w + x) - c * (h + y) + w; this._matrix[5] = b * (w + x) - d * (h + y) + h; } multiply(matrix: Matrix): void { var m1 = this._matrix; var m2 = matrix._matrix; var m10 = m1[0]; var m11 = m1[1]; var m12 = m1[2]; var m13 = m1[3]; m1[0] = m10 * m2[0] + m12 * m2[1]; m1[1] = m11 * m2[0] + m13 * m2[1]; m1[2] = m10 * m2[2] + m12 * m2[3]; m1[3] = m11 * m2[2] + m13 * m2[3]; m1[4] = m10 * m2[4] + m12 * m2[5] + m1[4]; m1[5] = m11 * m2[4] + m13 * m2[5] + m1[5]; } multiplyLeft(matrix: Matrix): void { var m1 = matrix._matrix; var m2 = this._matrix; var m20 = m2[0]; var m22 = m2[2]; var m24 = m2[4]; m2[0] = m1[0] * m20 + m1[2] * m2[1]; m2[1] = m1[1] * m20 + m1[3] * m2[1]; m2[2] = m1[0] * m22 + m1[2] * m2[3]; m2[3] = m1[1] * m22 + m1[3] * m2[3]; m2[4] = m1[0] * m24 + m1[2] * m2[5] + m1[4]; m2[5] = m1[1] * m24 + m1[3] * m2[5] + m1[5]; } multiplyNew(matrix: Matrix): Matrix { var ret = this.clone(); ret.multiply(matrix); return ret; } reset(x?: number, y?: number): void { this._matrix[0] = 1; this._matrix[1] = 0; this._matrix[2] = 0; this._matrix[3] = 1; this._matrix[4] = x || 0; this._matrix[5] = y || 0; } clone(): Matrix { return new PlainMatrix(this); } multiplyInverseForPoint(point: CommonOffset): CommonOffset { var m = this._matrix; // id = inverse of the determinant var _id = 1 / (m[0] * m[3] + m[2] * -m[1]); return { x: m[3] * _id * point.x + -m[2] * _id * point.y + (m[5] * m[2] - m[4] * m[3]) * _id, y: m[0] * _id * point.y + -m[1] * _id * point.x + (-m[5] * m[0] + m[4] * m[1]) * _id }; } scale(x: number, y: number): void { var m = this._matrix; m[0] *= x; m[1] *= y; m[2] *= x; m[3] *= y; m[4] *= x; m[5] *= y; } multiplyPoint(point: CommonOffset): CommonOffset { var m = this._matrix; var x = m[0] * point.x + m[2] * point.y + m[4]; var y = m[1] * point.x + m[3] * point.y + m[5]; return { x: x, y: y }; } }
the_stack
export default { sum__num: [ { group: ['Christopher'], values: [ { x: -157766400000.0, y: null, }, { x: -126230400000.0, y: null, }, { x: -94694400000.0, y: null, }, { x: -63158400000.0, y: null, }, { x: -31536000000.0, y: null, }, { x: 0.0, y: null, }, { x: 31536000000.0, y: null, }, { x: 63072000000.0, y: null, }, { x: 94694400000.0, y: null, }, { x: 126230400000.0, y: null, }, { x: 157766400000.0, y: null, }, { x: 189302400000.0, y: null, }, { x: 220924800000.0, y: null, }, { x: 252460800000.0, y: null, }, { x: 283996800000.0, y: null, }, { x: 315532800000.0, y: null, }, { x: 347155200000.0, y: null, }, { x: 378691200000.0, y: 59055.0, }, { x: 410227200000.0, y: 59188.0, }, { x: 441763200000.0, y: 59859.0, }, { x: 473385600000.0, y: 59516.0, }, { x: 504921600000.0, y: null, }, { x: 536457600000.0, y: null, }, { x: 567993600000.0, y: null, }, { x: 599616000000.0, y: null, }, { x: 631152000000.0, y: null, }, { x: 662688000000.0, y: null, }, ], }, { group: ['David'], values: [ { x: -157766400000.0, y: 67646.0, }, { x: -126230400000.0, y: 66207.0, }, { x: -94694400000.0, y: 66581.0, }, { x: -63158400000.0, y: 63531.0, }, { x: -31536000000.0, y: 63502.0, }, { x: 0.0, y: 61570.0, }, { x: 31536000000.0, y: null, }, { x: 63072000000.0, y: null, }, { x: 94694400000.0, y: null, }, { x: 126230400000.0, y: null, }, { x: 157766400000.0, y: null, }, { x: 189302400000.0, y: null, }, { x: 220924800000.0, y: null, }, { x: 252460800000.0, y: null, }, { x: 283996800000.0, y: null, }, { x: 315532800000.0, y: null, }, { x: 347155200000.0, y: null, }, { x: 378691200000.0, y: null, }, { x: 410227200000.0, y: null, }, { x: 441763200000.0, y: null, }, { x: 473385600000.0, y: null, }, { x: 504921600000.0, y: null, }, { x: 536457600000.0, y: null, }, { x: 567993600000.0, y: null, }, { x: 599616000000.0, y: null, }, { x: 631152000000.0, y: null, }, { x: 662688000000.0, y: null, }, ], }, { group: ['James'], values: [ { x: -157766400000.0, y: 67506.0, }, { x: -126230400000.0, y: 65036.0, }, { x: -94694400000.0, y: 61554.0, }, { x: -63158400000.0, y: 60584.0, }, { x: -31536000000.0, y: 59824.0, }, { x: 0.0, y: 61597.0, }, { x: 31536000000.0, y: null, }, { x: 63072000000.0, y: null, }, { x: 94694400000.0, y: null, }, { x: 126230400000.0, y: null, }, { x: 157766400000.0, y: null, }, { x: 189302400000.0, y: null, }, { x: 220924800000.0, y: null, }, { x: 252460800000.0, y: null, }, { x: 283996800000.0, y: null, }, { x: 315532800000.0, y: null, }, { x: 347155200000.0, y: null, }, { x: 378691200000.0, y: null, }, { x: 410227200000.0, y: null, }, { x: 441763200000.0, y: null, }, { x: 473385600000.0, y: null, }, { x: 504921600000.0, y: null, }, { x: 536457600000.0, y: null, }, { x: 567993600000.0, y: null, }, { x: 599616000000.0, y: null, }, { x: 631152000000.0, y: null, }, { x: 662688000000.0, y: null, }, ], }, { group: ['John'], values: [ { x: -157766400000.0, y: 71390.0, }, { x: -126230400000.0, y: 64858.0, }, { x: -94694400000.0, y: 61480.0, }, { x: -63158400000.0, y: 60754.0, }, { x: -31536000000.0, y: 58644.0, }, { x: 0.0, y: null, }, { x: 31536000000.0, y: null, }, { x: 63072000000.0, y: null, }, { x: 94694400000.0, y: null, }, { x: 126230400000.0, y: null, }, { x: 157766400000.0, y: null, }, { x: 189302400000.0, y: null, }, { x: 220924800000.0, y: null, }, { x: 252460800000.0, y: null, }, { x: 283996800000.0, y: null, }, { x: 315532800000.0, y: null, }, { x: 347155200000.0, y: null, }, { x: 378691200000.0, y: null, }, { x: 410227200000.0, y: null, }, { x: 441763200000.0, y: null, }, { x: 473385600000.0, y: null, }, { x: 504921600000.0, y: null, }, { x: 536457600000.0, y: null, }, { x: 567993600000.0, y: null, }, { x: 599616000000.0, y: null, }, { x: 631152000000.0, y: null, }, { x: 662688000000.0, y: null, }, ], }, { group: ['Michael'], values: [ { x: -157766400000.0, y: 80812.0, }, { x: -126230400000.0, y: 79709.0, }, { x: -94694400000.0, y: 82204.0, }, { x: -63158400000.0, y: 81785.0, }, { x: -31536000000.0, y: 84893.0, }, { x: 0.0, y: 85015.0, }, { x: 31536000000.0, y: 77321.0, }, { x: 63072000000.0, y: 71197.0, }, { x: 94694400000.0, y: 67598.0, }, { x: 126230400000.0, y: 67304.0, }, { x: 157766400000.0, y: 68149.0, }, { x: 189302400000.0, y: 66686.0, }, { x: 220924800000.0, y: 67344.0, }, { x: 252460800000.0, y: 66875.0, }, { x: 283996800000.0, y: 67473.0, }, { x: 315532800000.0, y: 68375.0, }, { x: 347155200000.0, y: 68467.0, }, { x: 378691200000.0, y: 67904.0, }, { x: 410227200000.0, y: 67708.0, }, { x: 441763200000.0, y: 67457.0, }, { x: 473385600000.0, y: 64667.0, }, { x: 504921600000.0, y: 63959.0, }, { x: 536457600000.0, y: 63442.0, }, { x: 567993600000.0, y: 63924.0, }, { x: 599616000000.0, y: 65233.0, }, { x: 631152000000.0, y: 65138.0, }, { x: 662688000000.0, y: 60646.0, }, ], }, { group: ['Robert'], values: [ { x: -157766400000.0, y: 62973.0, }, { x: -126230400000.0, y: 59162.0, }, { x: -94694400000.0, y: null, }, { x: -63158400000.0, y: null, }, { x: -31536000000.0, y: null, }, { x: 0.0, y: null, }, { x: 31536000000.0, y: null, }, { x: 63072000000.0, y: null, }, { x: 94694400000.0, y: null, }, { x: 126230400000.0, y: null, }, { x: 157766400000.0, y: null, }, { x: 189302400000.0, y: null, }, { x: 220924800000.0, y: null, }, { x: 252460800000.0, y: null, }, { x: 283996800000.0, y: null, }, { x: 315532800000.0, y: null, }, { x: 347155200000.0, y: null, }, { x: 378691200000.0, y: null, }, { x: 410227200000.0, y: null, }, { x: 441763200000.0, y: null, }, { x: 473385600000.0, y: null, }, { x: 504921600000.0, y: null, }, { x: 536457600000.0, y: null, }, { x: 567993600000.0, y: null, }, { x: 599616000000.0, y: null, }, { x: 631152000000.0, y: null, }, { x: 662688000000.0, y: null, }, ], }, ], };
the_stack
import { ActionSummary, TableDelta } from 'app/common/ActionSummary'; import { delay } from 'app/common/delay'; import { fromTableDataAction, RowRecord, TableColValues, TableDataAction } from 'app/common/DocActions'; import { StringUnion } from 'app/common/StringUnion'; import { MetaRowRecord } from 'app/common/TableData'; import { CellDelta } from 'app/common/TabularDiff'; import { ActiveDoc } from 'app/server/lib/ActiveDoc'; import { makeExceptionalDocSession } from 'app/server/lib/DocSession'; import * as log from 'app/server/lib/log'; import { promisifyAll } from 'bluebird'; import * as _ from 'lodash'; import * as LRUCache from 'lru-cache'; import fetch from 'node-fetch'; import { createClient, RedisClient } from 'redis'; promisifyAll(RedisClient.prototype); // Only owners can manage triggers, but any user's activity can trigger them // and the corresponding actions get the full values const docSession = makeExceptionalDocSession('system'); // Describes the change in existence to a record, which determines the event type interface RecordDelta { existedBefore: boolean; existedAfter: boolean; } type RecordDeltas = Map<number, RecordDelta>; // Union discriminated by type type TriggerAction = WebhookAction | PythonAction; export interface WebhookAction { type: "webhook"; id: string; } // Just hypothetical interface PythonAction { type: "python"; code: string; } interface WebHookEvent { payload: RowRecord; id: string; } export const allowedEventTypes = StringUnion("add", "update"); type EventType = typeof allowedEventTypes.type; type Trigger = MetaRowRecord<"_grist_Triggers">; export interface WebHookSecret { url: string; unsubscribeKey: string; } // Work to do after fetching values from the document interface Task { tableId: string; tableDelta: TableDelta; triggers: any; tableDataAction: Promise<TableDataAction>; recordDeltas: RecordDeltas; } // Processes triggers for records changed as described in ActionSummary objects, // initiating webhooks and automations. export class DocTriggers { // Converts a column ref to colId by looking it up in _grist_Tables_column private _getColId: (rowId: number) => string|undefined; // Events that need to be sent to webhooks in FIFO order. private _webHookEventQueue: WebHookEvent[] = []; // DB cache for webhook secrets private _webhookCache = new LRUCache<string, WebHookSecret>({max: 1000}); private _shuttingDown: boolean = false; private _sending: boolean = false; private _redisClient: RedisClient | undefined; constructor(private _activeDoc: ActiveDoc) { const redisUrl = process.env.REDIS_URL; if (redisUrl) { this._redisClient = createClient(redisUrl); // TODO check for existing events on redis queue } } public shutdown() { this._shuttingDown = true; if (!this._sending) { this._redisClient?.quitAsync(); } } public async handle(summary: ActionSummary) { const docData = this._activeDoc.docData; if (!docData) { return; } // Happens on doc creation while processing InitNewDoc action. const triggersTable = docData.getMetaTable("_grist_Triggers"); const getTableId = docData.getMetaTable("_grist_Tables").getMetaRowPropFunc("tableId"); this._getColId = docData.getMetaTable("_grist_Tables_column").getMetaRowPropFunc("colId"); const triggersByTableRef = _.groupBy(triggersTable.getRecords(), "tableRef"); const tasks: Task[] = []; for (const tableRef of Object.keys(triggersByTableRef).sort()) { const triggers = triggersByTableRef[tableRef]; const tableId = getTableId(Number(tableRef))!; // groupBy makes tableRef a string const tableDelta = summary.tableDeltas[tableId]; if (tableDelta) { const recordDeltas = this._getRecordDeltas(tableDelta); const filters = {id: [...recordDeltas.keys()]}; // Fetch the modified records in full so they can be sent in webhooks // They will also be used to check if the record is ready const tableDataAction = this._activeDoc.fetchQuery(docSession, {tableId, filters}); tasks.push({tableId, tableDelta, triggers, tableDataAction, recordDeltas}); } } // Fetch values from document DB in parallel await Promise.all(tasks.map(t => t.tableDataAction)); const events: WebHookEvent[] = []; for (const task of tasks) { events.push(...this._handleTask(task, await task.tableDataAction)); } this._webHookEventQueue.push(...events); if (!this._sending && events.length) { this._sending = true; const startSendLoop = () => { this._sendLoop().catch((e) => { log.error(`_sendLoop failed: ${e}`); startSendLoop(); }); }; startSendLoop(); } // TODO also push to redis queue } private _getRecordDeltas(tableDelta: TableDelta): RecordDeltas { const recordDeltas = new Map<number, RecordDelta>(); tableDelta.updateRows.forEach(id => recordDeltas.set(id, {existedBefore: true, existedAfter: true})); // A row ID can appear in both updateRows and addRows, although it probably shouldn't // Added row IDs override updated rows because they didn't exist before tableDelta.addRows.forEach(id => recordDeltas.set(id, {existedBefore: false, existedAfter: true})); // If we allow subscribing to deletion in the future // delta.removeRows.forEach(id => // recordDeltas.set(id, {existedBefore: true, existedAfter: false})); return recordDeltas; } private _handleTask( {tableDelta, tableId, triggers, recordDeltas}: Task, tableDataAction: TableDataAction, ) { const bulkColValues = fromTableDataAction(tableDataAction); log.info(`Processing ${triggers.length} triggers for ${bulkColValues.id.length} records of ${tableId}`); const makePayload = _.memoize((rowIndex: number) => _.mapValues(bulkColValues, col => col[rowIndex]) as RowRecord ); const result: WebHookEvent[] = []; for (const trigger of triggers) { const actions = JSON.parse(trigger.actions) as TriggerAction[]; const webhookActions = actions.filter(act => act.type === "webhook") as WebhookAction[]; if (!webhookActions.length) { continue; } const rowIndexesToSend: number[] = _.range(bulkColValues.id.length).filter(rowIndex => { const rowId = bulkColValues.id[rowIndex]; return this._shouldTriggerActions( trigger, bulkColValues, rowIndex, rowId, recordDeltas.get(rowId)!, tableDelta, ); } ); for (const action of webhookActions) { for (const rowIndex of rowIndexesToSend) { const event = {id: action.id, payload: makePayload(rowIndex)}; result.push(event); } } } return result; } /** * Determines if actions should be triggered for a single record and trigger. */ private _shouldTriggerActions( trigger: Trigger, bulkColValues: TableColValues, rowIndex: number, rowId: number, recordDelta: RecordDelta, tableDelta: TableDelta, ): boolean { let readyBefore: boolean; if (!trigger.isReadyColRef) { // User hasn't configured a column, so all records are considered ready immediately readyBefore = recordDelta.existedBefore; } else { const isReadyColId = this._getColId(trigger.isReadyColRef)!; // Must be the actual boolean `true`, not just anything truthy const isReady = bulkColValues[isReadyColId][rowIndex] === true; if (!isReady) { return false; } const cellDelta: CellDelta | undefined = tableDelta.columnDeltas[isReadyColId]?.[rowId]; if (!recordDelta.existedBefore) { readyBefore = false; } else if (!cellDelta ) { // Cell wasn't changed, and the record is ready now, so it was ready before. // This assumes that the ActionSummary contains all changes to the isReady column. // TODO ensure ActionSummary actually contains all changes, right now bulk changes are truncated. readyBefore = true; } else { const deltaBefore = cellDelta[0]; if (deltaBefore === null) { // The record didn't exist before, so it definitely wasn't ready // (although we probably shouldn't reach this since we already checked recordDelta.existedBefore) readyBefore = false; } else if (deltaBefore === "?") { // The ActionSummary shouldn't contain this kind of delta at all // since it comes from a single action bundle, not a combination of summaries. log.warn('Unexpected deltaBefore === "?"', {trigger, isReadyColId, rowId, docId: this._activeDoc.docName}); readyBefore = true; } else { // Only remaining case is that deltaBefore is a single-element array containing the previous value. const [valueBefore] = deltaBefore; // Must be the actual boolean `true`, not just anything truthy readyBefore = valueBefore === true; } } } let eventType: EventType; if (readyBefore) { eventType = "update"; // If we allow subscribing to deletion in the future // if (recordDelta.existedAfter) { // eventType = "update"; // } else { // eventType = "remove"; // } } else { eventType = "add"; } return trigger.eventTypes!.includes(eventType); } private async _getWebHookUrl(id: string): Promise<string | undefined> { let webhook = this._webhookCache.get(id); if (!webhook) { const secret = await this._activeDoc.getHomeDbManager()?.getSecret(id, this._activeDoc.docName); if (!secret) { return; } webhook = JSON.parse(secret); this._webhookCache.set(id, webhook!); } const url = webhook!.url; if (!isUrlAllowed(url)) { log.warn(`Webhook not sent to forbidden URL: ${url}`); return; } return url; } private async _sendLoop() { log.info("Starting _sendLoop"); // TODO delay/prevent shutting down while queue isn't empty? while (!this._shuttingDown) { if (!this._webHookEventQueue.length) { await delay(1000); continue; } const id = this._webHookEventQueue[0].id; const batch = _.takeWhile(this._webHookEventQueue.slice(0, 100), {id}); const body = JSON.stringify(batch.map(e => e.payload)); const url = await this._getWebHookUrl(id); let success: boolean; if (!url) { success = true; } else { success = await this._sendWebhookWithRetries(url, body); } if (success) { this._webHookEventQueue.splice(0, batch.length); // TODO also remove on redis } else if (!this._shuttingDown) { // TODO reorder queue on failure } } log.info("Ended _sendLoop"); this._redisClient?.quitAsync().catch(e => // Catch error to prevent sendLoop being restarted log.warn("Error quitting redis: " + e) ); } private async _sendWebhookWithRetries(url: string, body: string) { const maxAttempts = 20; const maxWait = 64; let wait = 1; for (let attempt = 0; attempt < maxAttempts; attempt++) { if (this._shuttingDown) { return false; } try { const response = await fetch(url, { method: 'POST', body, headers: { 'Content-Type': 'application/json', }, }); if (response.status === 200) { return true; } log.warn(`Webhook responded with status ${response.status}`); } catch (e) { log.warn(`Webhook error: ${e}`); } // Don't wait any more if this is the last attempt. if (attempt >= maxAttempts - 1) { return false; } // Wait `wait` seconds, checking this._shuttingDown every second. for (let waitIndex = 0; waitIndex < wait; waitIndex++) { if (this._shuttingDown) { return false; } await delay(1000); } if (wait < maxWait) { wait *= 2; } } return false; } } export function isUrlAllowed(urlString: string) { let url: URL; try { url = new URL(urlString); } catch (e) { return false; } // http (no s) is only allowed for localhost for testing. // localhost still needs to be explicitly permitted, and it shouldn't be outside dev if (url.protocol !== "https:" && url.hostname !== "localhost") { return false; } return (process.env.ALLOWED_WEBHOOK_DOMAINS || "").split(",").some(domain => domain && url.host.endsWith(domain) ); }
the_stack