text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Items, TradeOffer, ItemsDict } from '@tf2autobot/tradeoffer-manager';
import SKU from '@tf2autobot/tf2-sku';
import Currencies from '@tf2autobot/tf2-currencies';
import pluralize from 'pluralize';
import dayjs from 'dayjs';
import PriceCheckQueue from './requestPriceCheck';
import Bot from '../../../Bot';
import { EntryData } from '../../../Pricelist';
import { Attributes } from '../../../TF2GC';
import log from '../../../../lib/logger';
import { sendAlert } from '../../../../lib/DiscordWebhook/export';
import { PaintedNames } from '../../../Options';
import { testSKU } from '../../../../lib/tools/export';
let itemsFromPreviousTrades: string[] = [];
const removeDuplicate = (skus: string[]): string[] => {
const fix = new Set(skus);
return [...fix];
};
let craftWeapons: string[] = [];
export default function updateListings(
offer: TradeOffer,
bot: Bot,
highValue: { isDisableSKU: string[]; theirItems: string[]; items: Items }
): void {
const opt = bot.options;
const diff = offer.getDiff() || {};
const dict = offer.data('dict') as ItemsDict;
const weapons = opt.miscSettings.weaponsAsCurrency.enable
? opt.miscSettings.weaponsAsCurrency.withUncraft
? bot.craftWeapons.concat(bot.uncraftWeapons)
: bot.craftWeapons
: [];
craftWeapons = weapons;
const alwaysRemoveCustomTexture = opt.miscSettings.alwaysRemoveItemAttributes.customTexture.enable;
const skus: string[] = [];
const inventory = bot.inventoryManager.getInventory;
const hv = highValue.items;
const normalizePainted = opt.normalize.painted;
const dwEnabled = opt.discordWebhook.sendAlert.enable && opt.discordWebhook.sendAlert.url !== '';
const pure = ['5000;6', '5001;6', '5002;6'];
const pureWithWeapons = pure.concat(weapons);
const isAdmin = bot.isAdmin(offer.partner);
for (const sku in diff) {
if (!Object.prototype.hasOwnProperty.call(diff, sku)) {
continue;
}
if (!testSKU(sku)) {
continue;
}
const item = SKU.fromString(sku);
const name = bot.schema.getName(item, false);
const isNotPure = !pure.includes(sku);
const isNotPureOrWeapons = !pureWithWeapons.includes(sku);
const inPrice = bot.pricelist.getPrice(sku, false);
const existInPricelist = inPrice !== null;
const amount = inventory.getAmount(sku, false, true);
const itemNoPaint = SKU.fromString(sku);
itemNoPaint.paint = null;
const skuNoPaint = SKU.fromObject(itemNoPaint);
const inPrice2 = bot.pricelist.getPrice(skuNoPaint, false);
const isDisabledHV = highValue.isDisableSKU.includes(sku);
const isNotSkinsOrWarPaint = item.wear === null;
// if item is unusual and autoAddInvalidUnusual is set to true then we allow addInvalidUnusual.
// If the item is not an unusual sku, we "allow" still (no-op)
const addInvalidUnusual = item.quality === 5 ? opt.pricelist.autoAddInvalidUnusual.enable : true;
const isAutoaddPainted = /;[p][0-9]+/.test(sku)
? false // sku must NOT include any painted partial sku
: opt.pricelist.autoAddPaintedItems.enable && // autoAddPaintedItems must enabled
normalizePainted.our === false && // must meet this setting
normalizePainted.their === true && // must meet this setting
hv && // this must be defined
hv[sku]?.p && // painted must be defined
hv[sku]?.s === undefined && // make sure spelled is undefined
inPrice !== null && // base items must already in pricelist
bot.pricelist.getPrice(`${sku};${Object.keys(hv[sku].p)[0]}`, false) === null && // painted items must not in pricelist
inventory.getAmount(`${sku};${Object.keys(hv[sku].p)[0]}`, false, true) > 0;
const isAutoAddPaintedFromAdmin = !isAdmin
? false
: normalizePainted.our === false && // must meet this setting
normalizePainted.their === true && // must meet this setting
/;[p][0-9]+/.test(sku) && // sku must include any painted partial sku
hv && // this must be defined
hv[sku]?.p && // painted must be defined
hv[sku]?.s === undefined && // make sure spelled is undefined
inPrice === null && // painted items must not in pricelist
inPrice2 !== null && // base items must already in pricelist
amount > 0;
const isAutoaddInvalidItems =
!existInPricelist &&
isNotPureOrWeapons &&
sku !== '5021;6' && // not Mann Co. Supply Crate Key
isNotSkinsOrWarPaint && // exclude War Paint (could be skins)
addInvalidUnusual &&
!isDisabledHV &&
!isAdmin &&
opt.pricelist.autoAddInvalidItems.enable;
const receivedHighValueNotInPricelist =
!existInPricelist &&
isNotPureOrWeapons &&
isNotSkinsOrWarPaint && // exclude War Paint (could be skins)
isDisabledHV && // This is the only difference
!isAdmin;
const receivedUnusualNotInPricelist =
!existInPricelist &&
isNotPureOrWeapons &&
isNotSkinsOrWarPaint &&
item.quality === 5 &&
opt.pricelist.autoAddInvalidUnusual.enable === false &&
!isAdmin;
const isAutoDisableHighValueItems =
existInPricelist && isDisabledHV && isNotPureOrWeapons && opt.highValue.enableHold;
const isAutoRemoveIntentSell =
opt.pricelist.autoRemoveIntentSell.enable &&
existInPricelist &&
inPrice.intent === 1 &&
(opt.autokeys.enable ? sku !== '5021;6' : true) && // not Mann Co. Supply Crate Key if Autokeys enabled
amount < 1 && // current stock
isNotPureOrWeapons;
const isUpdatePartialPricedItem =
inPrice !== null &&
inPrice.autoprice &&
inPrice.isPartialPriced &&
amount < 1 && // current stock
isNotPureOrWeapons;
//
if (isAutoaddPainted) {
const pSKU = Object.keys(hv[sku].p)[0];
const paintedSKU = `${sku};${pSKU}`;
const priceFromOptions =
opt.detailsExtra.painted[
bot.schema.getPaintNameByDecimal(parseInt(pSKU.replace('p', ''), 10)) as PaintedNames
].price;
const keyPriceInRef = bot.pricelist.getKeyPrice.metal;
const keyPriceInScrap = Currencies.toScrap(keyPriceInRef);
let sellingKeyPrice = inPrice.sell.keys + priceFromOptions.keys;
let sellingMetalPriceInRef = inPrice.sell.metal + priceFromOptions.metal;
const sellingMetalPriceInScrap = Currencies.toScrap(sellingMetalPriceInRef);
if (sellingMetalPriceInScrap >= keyPriceInScrap) {
const truncValue = Math.trunc(sellingMetalPriceInRef / keyPriceInRef);
sellingKeyPrice =
sellingKeyPrice - truncValue <= 0 ? sellingKeyPrice + 1 : sellingKeyPrice + truncValue;
sellingMetalPriceInRef = Currencies.toRefined(sellingMetalPriceInScrap - truncValue * keyPriceInScrap);
}
const entry = {
sku: paintedSKU,
enabled: true,
autoprice: false,
buy: {
keys: 0,
metal: 1 // always set like this for buying price
},
sell: {
keys: sellingKeyPrice,
metal: sellingMetalPriceInRef
},
min: 0,
max: 1,
intent: 1,
group: 'painted'
} as EntryData;
const isCustomPricer = bot.pricelist.isUseCustomPricer;
bot.pricelist
.addPrice(entry, true)
.then(data => {
const msg =
`✅ Automatically added ${bot.schema.getName(SKU.fromString(paintedSKU), false)}` +
` (${paintedSKU}) to sell.` +
`\nBase price: ${inPrice.buy.toString()}/${inPrice.sell.toString()}` +
`\nSelling for: ${data.sell.toString()} ` +
`(+ ${priceFromOptions.keys > 0 ? `${pluralize('key', priceFromOptions.keys, true)}, ` : ''}${
priceFromOptions.metal
} ref)` +
(isCustomPricer
? '\n - Base selling price was fetched from custom auto-pricer'
: `\nhttps://www.prices.tf/items/${sku}`);
log.debug(msg);
if (opt.sendAlert.enable && opt.sendAlert.autoAddPaintedItems) {
if (dwEnabled) {
sendAlert('autoAddPaintedItems', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(paintedSKU, isNotPure, existInPricelist);
})
.catch(err => {
const msg =
`❌ Failed to add ${bot.schema.getName(SKU.fromString(paintedSKU), false)}` +
` (${paintedSKU}) to sell automatically: ${(err as Error).message}`;
log.warn(`Failed to add ${paintedSKU} to sell automatically:`, err);
if (opt.sendAlert.enable && opt.sendAlert.autoAddPaintedItems) {
if (dwEnabled) {
sendAlert('autoAddPaintedItemsFailed', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(paintedSKU, isNotPure, existInPricelist);
});
//
} else if (isAutoAddPaintedFromAdmin) {
const priceFromOptions =
opt.detailsExtra.painted[bot.schema.getPaintNameByDecimal(item.paint) as PaintedNames].price;
const keyPriceInRef = bot.pricelist.getKeyPrice.metal;
const keyPriceInScrap = Currencies.toScrap(keyPriceInRef);
let sellingKeyPrice = inPrice2.sell.keys + priceFromOptions.keys;
let sellingMetalPriceInRef = inPrice2.sell.metal + priceFromOptions.metal;
const sellingMetalPriceInScrap = Currencies.toScrap(sellingMetalPriceInRef);
if (sellingMetalPriceInScrap >= keyPriceInScrap) {
const truncValue = Math.trunc(sellingMetalPriceInRef / keyPriceInRef);
sellingKeyPrice =
sellingKeyPrice - truncValue <= 0 ? sellingKeyPrice + 1 : sellingKeyPrice + truncValue;
sellingMetalPriceInRef = Currencies.toRefined(sellingMetalPriceInScrap - truncValue * keyPriceInScrap);
}
const entry = {
sku: sku,
enabled: true,
autoprice: false,
buy: {
keys: 0,
metal: 1 // always set like this for buying price
},
sell: {
keys: sellingKeyPrice,
metal: sellingMetalPriceInRef
},
min: 0,
max: 1,
intent: 1,
group: 'painted'
} as EntryData;
const isCustomPricer = bot.pricelist.isUseCustomPricer;
bot.pricelist
.addPrice(entry, true)
.then(data => {
const msg =
`✅ Automatically added ${name} (${sku}) to sell.` +
`\nBase price: ${inPrice2.buy.toString()}/${inPrice2.sell.toString()}` +
`\nSelling for: ${data.sell.toString()} ` +
`(+ ${priceFromOptions.keys > 0 ? `${pluralize('key', priceFromOptions.keys, true)}, ` : ''}${
priceFromOptions.metal
} ref)` +
(isCustomPricer
? '\n - Base selling price was fetched from custom auto-pricer'
: `\nhttps://www.prices.tf/items/${skuNoPaint}`);
log.debug(msg);
if (opt.sendAlert.enable && opt.sendAlert.autoAddPaintedItems) {
if (dwEnabled) {
sendAlert('autoAddPaintedItems', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
})
.catch(err => {
const msg = `❌ Failed to add ${name} (${sku}) to sell automatically: ${(err as Error).message}`;
log.warn(`Failed to add ${sku} to sell automatically:`, err);
if (opt.sendAlert.enable && opt.sendAlert.autoAddPaintedItems) {
if (dwEnabled) {
sendAlert('autoAddPaintedItemsFailed', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
});
//
} else if (isAutoaddInvalidItems) {
// if the item sku is not in pricelist, not craftweapons or pure or skins or highValue items, and not
// from ADMINS, then add INVALID_ITEMS to the pricelist.
const entry = {
sku: sku,
enabled: true,
autoprice: true,
min: 0,
max: 1,
intent: 1,
group: 'invalidItem'
} as EntryData;
bot.pricelist
.addPrice(entry, true)
.then(() => {
log.debug(`✅ Automatically added ${name} (${sku}) to sell.`);
addToQueu(sku, isNotPure, existInPricelist);
})
.catch(err => {
log.warn(`❌ Failed to add ${name} (${sku}) to sell automatically: ${(err as Error).message}`);
addToQueu(sku, isNotPure, existInPricelist);
});
//
} else if (receivedHighValueNotInPricelist) {
// if the item sku is not in pricelist, not craftweapons or pure or skins AND it's a highValue items, and not
// from ADMINS, then notify admin.
let msg =
'I have received a high-valued items which is not in my pricelist.' + '\n\nItem information:\n\n- ';
const theirCount = highValue.theirItems.length;
for (let i = 0; i < theirCount; i++) {
if (highValue.theirItems[i].includes(name)) {
msg += `${highValue.isDisableSKU[i]}: ` + highValue.theirItems[i];
}
}
if (opt.sendAlert.enable && opt.sendAlert.highValue.receivedNotInPricelist) {
if (dwEnabled) {
sendAlert('highValuedInvalidItems', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
} else if (receivedUnusualNotInPricelist) {
// if the item sku is not in pricelist, not craftweapons or pure or skins AND it's a Unusual (bought with Generic Unusual), and not
// from ADMINS, and opt.pricelist.autoAddInvalidUnusual is false, then notify admin.
const msg =
'I have received an Unusual bought with Generic Unusual feature\n\nItem info: ' +
(dwEnabled ? `[${name}](https://www.prices.tf/items/${sku}) (${sku})` : `${name} (${sku})`);
if (opt.sendAlert.enable && opt.sendAlert.receivedUnusualNotInPricelist) {
if (dwEnabled) {
sendAlert('unusualInvalidItems', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
} else if (isAutoDisableHighValueItems) {
// If item received is high value, temporarily disable that item so it will not be sellable.
const oldGroup = inPrice.group;
const entry: EntryData = {
sku: sku, // required
enabled: false, // required
autoprice: inPrice.autoprice, // required
min: inPrice.min, // required
max: inPrice.max, // required
intent: inPrice.intent, // required
group: 'highValue'
};
if (!inPrice.autoprice) {
// if not autopriced, then explicitly set the buy/sell prices
// with the current buy/sell prices
entry.buy = {
keys: inPrice.buy.keys,
metal: inPrice.buy.metal
};
entry.sell = {
keys: inPrice.sell.keys,
metal: inPrice.sell.metal
};
}
bot.pricelist
.updatePrice(entry, true)
.then(() => {
log.debug(`✅ Automatically disabled ${sku}, which is a high value item.`);
let msg =
`I have temporarily disabled ${name} (${sku}) because it contains some high value spells/parts.` +
`\nYou can manually price it with "!update sku=${sku}&enabled=true&<buy and sell price>"` +
` or just re-enable it with "!update sku=${sku}&enabled=true&group=${oldGroup}".` +
'\n\nItem information:\n\n- ';
const theirCount = highValue.theirItems.length;
for (let i = 0; i < theirCount; i++) {
if (highValue.theirItems[i].includes(name)) msg += highValue.theirItems[i];
}
if (opt.sendAlert.enable && opt.sendAlert.highValue.gotDisabled) {
if (dwEnabled) {
sendAlert('highValuedDisabled', bot, msg.replace(/"/g, '`'));
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
})
.catch(err => {
log.warn(`❌ Failed to disable high value ${sku}: `, err);
addToQueu(sku, isNotPure, existInPricelist);
});
//
} else if (isAutoRemoveIntentSell) {
// If "automatic remove items with intent=sell" enabled and it's in the pricelist and no more stock,
// then remove the item entry from pricelist.
bot.pricelist
.removePrice(sku, true)
.then(() => {
log.debug(`✅ Automatically removed ${name} (${sku}) from pricelist.`);
addToQueu(sku, isNotPure, existInPricelist);
})
.catch(err => {
const msg = `❌ Failed to automatically remove ${name} (${sku}) from pricelist: ${
(err as Error).message
}`;
log.warn(`❌ Failed to automatically remove ${sku}`, err);
if (opt.sendAlert.enable && opt.sendAlert.autoRemoveIntentSellFailed) {
if (dwEnabled) {
sendAlert('autoRemoveIntentSellFailed', bot, msg);
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
});
} else if (isUpdatePartialPricedItem) {
// If item exist in pricelist with "isPartialPriced" set to true and we no longer have that in stock,
// then update entry with the latest prices.
const oldPrice = {
buy: new Currencies(inPrice.buy),
sell: new Currencies(inPrice.sell)
};
const oldTime = inPrice.time;
const entry = {
sku: sku,
enabled: inPrice.enabled,
autoprice: true,
min: inPrice.min,
max: inPrice.max,
intent: inPrice.intent,
group: inPrice.group,
isPartialPriced: false
} as EntryData;
bot.pricelist
.updatePrice(entry, true)
.then(data => {
const msg =
`${dwEnabled ? `[${name}](https://www.prices.tf/items/${sku})` : name} (${sku})\n▸ ` +
[
`old: ${oldPrice.buy.toString()}/${oldPrice.sell.toString()}`,
`new: ${data.buy.toString()}/${data.sell.toString()}`
].join('\n▸ ') +
`\n - Partial priced since ${dayjs.unix(oldTime).fromNow()}` +
`\n - Current prices last update: ${dayjs.unix(data.time).fromNow()}`;
log.debug(msg);
if (opt.sendAlert.enable && opt.sendAlert.partialPrice.onSuccessUpdatePartialPriced) {
if (dwEnabled) {
sendAlert('autoUpdatePartialPriceSuccess', bot, msg);
} else {
bot.messageAdmins('✅ Automatically update partially priced item - ' + msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
})
.catch(err => {
const msg = `❌ Failed to automatically update prices for ${name} (${sku}): ${
(err as Error).message
}`;
log.error(`❌ Failed to automatically update prices for ${sku}`, err);
if (opt.sendAlert.enable && opt.sendAlert.partialPrice.onFailedUpdatePartialPriced) {
if (dwEnabled) {
sendAlert('autoUpdatePartialPriceFailed', bot, msg);
} else {
bot.messageAdmins(msg, []);
}
}
addToQueu(sku, isNotPure, existInPricelist);
});
} else {
addToQueu(sku, isNotPure, existInPricelist);
}
if (
[474, 619, 623, 625].includes(item.defindex) &&
alwaysRemoveCustomTexture &&
dict.their[sku] !== undefined
) {
const amountTraded = dict.their[sku];
const assetids = inventory.findBySKU(sku, true).sort((a, b) => parseInt(b) - parseInt(a)); // descending order
const assetidsTraded = assetids.slice(0).splice(0, amountTraded);
log.debug(`Adding ${sku} (${assetidsTraded.join(', ')}) to the queue to remove custom texture...`);
assetidsTraded.forEach(assetid => {
bot.tf2gc.removeAttributes(sku, assetid, Attributes.CustomTexture, err => {
if (err) log.debug(`Error remove custom texture for ${sku} (${assetid})`, err);
});
});
// if (opt.miscSettings.alwaysRemoveItemAttributes.giftedByTag.enable) {
// assetidsTraded.forEach(assetid => {
// bot.tf2gc.removeAttributes(sku, assetid, Attributes.GiftedBy, err => {
// if (err) log.debug(`Error remove giftedBy tag for ${sku} (${assetid})`, err);
// });
// });
// }
}
}
if (skus.length > 0) {
const itemsToCheck = removeDuplicate(skus.concat(itemsFromPreviousTrades));
checkPrevious(itemsToCheck);
itemsFromPreviousTrades = skus.slice(0);
}
}
function addToQueu(sku: string, isNotPure: boolean, isExistInPricelist: boolean): void {
/**
* Request priceheck on each sku involved in the trade, except craft weapons (if weaponsAsCurrency enabled) and pure.
*/
if (isNotPure) {
if (craftWeapons.includes(sku)) {
if (isExistInPricelist) {
// Only includes sku of weapons that are in the pricelist (enabled)
PriceCheckQueue.enqueue(sku);
}
} else {
PriceCheckQueue.enqueue(sku);
}
}
}
function checkPrevious(skus: string[]): void {
skus.forEach(sku => {
PriceCheckQueue.enqueue(sku);
});
} | the_stack |
namespace wordBreakers {
export namespace data {
// Automatically generated file. DO NOT MODIFY.
/**
* Valid values for a word break property.
*/
export const enum WordBreakProperty {
Other,
LF,
Newline,
CR,
WSegSpace,
Double_Quote,
Single_Quote,
MidNum,
MidNumLet,
Numeric,
MidLetter,
ALetter,
ExtendNumLet,
Format,
Extend,
Hebrew_Letter,
ZWJ,
Katakana,
Regional_Indicator,
sot,
eot
};
/**
* Constants for indexing values in WORD_BREAK_PROPERTY.
*/
export const enum I {
Start = 0,
Value = 1
}
export const WORD_BREAK_PROPERTY: [number, WordBreakProperty][] = [
[/*start*/ 0x0, WordBreakProperty.Other],
[/*start*/ 0xA, WordBreakProperty.LF],
[/*start*/ 0xB, WordBreakProperty.Newline],
[/*start*/ 0xD, WordBreakProperty.CR],
[/*start*/ 0xE, WordBreakProperty.Other],
[/*start*/ 0x20, WordBreakProperty.WSegSpace],
[/*start*/ 0x21, WordBreakProperty.Other],
[/*start*/ 0x22, WordBreakProperty.Double_Quote],
[/*start*/ 0x23, WordBreakProperty.Other],
[/*start*/ 0x27, WordBreakProperty.Single_Quote],
[/*start*/ 0x28, WordBreakProperty.Other],
[/*start*/ 0x2C, WordBreakProperty.MidNum],
[/*start*/ 0x2D, WordBreakProperty.Other],
[/*start*/ 0x2E, WordBreakProperty.MidNumLet],
[/*start*/ 0x2F, WordBreakProperty.Other],
[/*start*/ 0x30, WordBreakProperty.Numeric],
[/*start*/ 0x3A, WordBreakProperty.MidLetter],
[/*start*/ 0x3B, WordBreakProperty.MidNum],
[/*start*/ 0x3C, WordBreakProperty.Other],
[/*start*/ 0x41, WordBreakProperty.ALetter],
[/*start*/ 0x5B, WordBreakProperty.Other],
[/*start*/ 0x5F, WordBreakProperty.ExtendNumLet],
[/*start*/ 0x60, WordBreakProperty.Other],
[/*start*/ 0x61, WordBreakProperty.ALetter],
[/*start*/ 0x7B, WordBreakProperty.Other],
[/*start*/ 0x85, WordBreakProperty.Newline],
[/*start*/ 0x86, WordBreakProperty.Other],
[/*start*/ 0xAA, WordBreakProperty.ALetter],
[/*start*/ 0xAB, WordBreakProperty.Other],
[/*start*/ 0xAD, WordBreakProperty.Format],
[/*start*/ 0xAE, WordBreakProperty.Other],
[/*start*/ 0xB5, WordBreakProperty.ALetter],
[/*start*/ 0xB6, WordBreakProperty.Other],
[/*start*/ 0xB7, WordBreakProperty.MidLetter],
[/*start*/ 0xB8, WordBreakProperty.Other],
[/*start*/ 0xBA, WordBreakProperty.ALetter],
[/*start*/ 0xBB, WordBreakProperty.Other],
[/*start*/ 0xC0, WordBreakProperty.ALetter],
[/*start*/ 0xD7, WordBreakProperty.Other],
[/*start*/ 0xD8, WordBreakProperty.ALetter],
[/*start*/ 0xF7, WordBreakProperty.Other],
[/*start*/ 0xF8, WordBreakProperty.ALetter],
[/*start*/ 0x2D8, WordBreakProperty.Other],
[/*start*/ 0x2DE, WordBreakProperty.ALetter],
[/*start*/ 0x300, WordBreakProperty.Extend],
[/*start*/ 0x370, WordBreakProperty.ALetter],
[/*start*/ 0x375, WordBreakProperty.Other],
[/*start*/ 0x376, WordBreakProperty.ALetter],
[/*start*/ 0x378, WordBreakProperty.Other],
[/*start*/ 0x37A, WordBreakProperty.ALetter],
[/*start*/ 0x37E, WordBreakProperty.MidNum],
[/*start*/ 0x37F, WordBreakProperty.ALetter],
[/*start*/ 0x380, WordBreakProperty.Other],
[/*start*/ 0x386, WordBreakProperty.ALetter],
[/*start*/ 0x387, WordBreakProperty.MidLetter],
[/*start*/ 0x388, WordBreakProperty.ALetter],
[/*start*/ 0x38B, WordBreakProperty.Other],
[/*start*/ 0x38C, WordBreakProperty.ALetter],
[/*start*/ 0x38D, WordBreakProperty.Other],
[/*start*/ 0x38E, WordBreakProperty.ALetter],
[/*start*/ 0x3A2, WordBreakProperty.Other],
[/*start*/ 0x3A3, WordBreakProperty.ALetter],
[/*start*/ 0x3F6, WordBreakProperty.Other],
[/*start*/ 0x3F7, WordBreakProperty.ALetter],
[/*start*/ 0x482, WordBreakProperty.Other],
[/*start*/ 0x483, WordBreakProperty.Extend],
[/*start*/ 0x48A, WordBreakProperty.ALetter],
[/*start*/ 0x530, WordBreakProperty.Other],
[/*start*/ 0x531, WordBreakProperty.ALetter],
[/*start*/ 0x557, WordBreakProperty.Other],
[/*start*/ 0x559, WordBreakProperty.ALetter],
[/*start*/ 0x55D, WordBreakProperty.Other],
[/*start*/ 0x55E, WordBreakProperty.ALetter],
[/*start*/ 0x55F, WordBreakProperty.MidLetter],
[/*start*/ 0x560, WordBreakProperty.ALetter],
[/*start*/ 0x589, WordBreakProperty.MidNum],
[/*start*/ 0x58A, WordBreakProperty.ALetter],
[/*start*/ 0x58B, WordBreakProperty.Other],
[/*start*/ 0x591, WordBreakProperty.Extend],
[/*start*/ 0x5BE, WordBreakProperty.Other],
[/*start*/ 0x5BF, WordBreakProperty.Extend],
[/*start*/ 0x5C0, WordBreakProperty.Other],
[/*start*/ 0x5C1, WordBreakProperty.Extend],
[/*start*/ 0x5C3, WordBreakProperty.Other],
[/*start*/ 0x5C4, WordBreakProperty.Extend],
[/*start*/ 0x5C6, WordBreakProperty.Other],
[/*start*/ 0x5C7, WordBreakProperty.Extend],
[/*start*/ 0x5C8, WordBreakProperty.Other],
[/*start*/ 0x5D0, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0x5EB, WordBreakProperty.Other],
[/*start*/ 0x5EF, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0x5F3, WordBreakProperty.ALetter],
[/*start*/ 0x5F4, WordBreakProperty.MidLetter],
[/*start*/ 0x5F5, WordBreakProperty.Other],
[/*start*/ 0x600, WordBreakProperty.Format],
[/*start*/ 0x606, WordBreakProperty.Other],
[/*start*/ 0x60C, WordBreakProperty.MidNum],
[/*start*/ 0x60E, WordBreakProperty.Other],
[/*start*/ 0x610, WordBreakProperty.Extend],
[/*start*/ 0x61B, WordBreakProperty.Other],
[/*start*/ 0x61C, WordBreakProperty.Format],
[/*start*/ 0x61D, WordBreakProperty.Other],
[/*start*/ 0x620, WordBreakProperty.ALetter],
[/*start*/ 0x64B, WordBreakProperty.Extend],
[/*start*/ 0x660, WordBreakProperty.Numeric],
[/*start*/ 0x66A, WordBreakProperty.Other],
[/*start*/ 0x66B, WordBreakProperty.Numeric],
[/*start*/ 0x66C, WordBreakProperty.MidNum],
[/*start*/ 0x66D, WordBreakProperty.Other],
[/*start*/ 0x66E, WordBreakProperty.ALetter],
[/*start*/ 0x670, WordBreakProperty.Extend],
[/*start*/ 0x671, WordBreakProperty.ALetter],
[/*start*/ 0x6D4, WordBreakProperty.Other],
[/*start*/ 0x6D5, WordBreakProperty.ALetter],
[/*start*/ 0x6D6, WordBreakProperty.Extend],
[/*start*/ 0x6DD, WordBreakProperty.Format],
[/*start*/ 0x6DE, WordBreakProperty.Other],
[/*start*/ 0x6DF, WordBreakProperty.Extend],
[/*start*/ 0x6E5, WordBreakProperty.ALetter],
[/*start*/ 0x6E7, WordBreakProperty.Extend],
[/*start*/ 0x6E9, WordBreakProperty.Other],
[/*start*/ 0x6EA, WordBreakProperty.Extend],
[/*start*/ 0x6EE, WordBreakProperty.ALetter],
[/*start*/ 0x6F0, WordBreakProperty.Numeric],
[/*start*/ 0x6FA, WordBreakProperty.ALetter],
[/*start*/ 0x6FD, WordBreakProperty.Other],
[/*start*/ 0x6FF, WordBreakProperty.ALetter],
[/*start*/ 0x700, WordBreakProperty.Other],
[/*start*/ 0x70F, WordBreakProperty.Format],
[/*start*/ 0x710, WordBreakProperty.ALetter],
[/*start*/ 0x711, WordBreakProperty.Extend],
[/*start*/ 0x712, WordBreakProperty.ALetter],
[/*start*/ 0x730, WordBreakProperty.Extend],
[/*start*/ 0x74B, WordBreakProperty.Other],
[/*start*/ 0x74D, WordBreakProperty.ALetter],
[/*start*/ 0x7A6, WordBreakProperty.Extend],
[/*start*/ 0x7B1, WordBreakProperty.ALetter],
[/*start*/ 0x7B2, WordBreakProperty.Other],
[/*start*/ 0x7C0, WordBreakProperty.Numeric],
[/*start*/ 0x7CA, WordBreakProperty.ALetter],
[/*start*/ 0x7EB, WordBreakProperty.Extend],
[/*start*/ 0x7F4, WordBreakProperty.ALetter],
[/*start*/ 0x7F6, WordBreakProperty.Other],
[/*start*/ 0x7F8, WordBreakProperty.MidNum],
[/*start*/ 0x7F9, WordBreakProperty.Other],
[/*start*/ 0x7FA, WordBreakProperty.ALetter],
[/*start*/ 0x7FB, WordBreakProperty.Other],
[/*start*/ 0x7FD, WordBreakProperty.Extend],
[/*start*/ 0x7FE, WordBreakProperty.Other],
[/*start*/ 0x800, WordBreakProperty.ALetter],
[/*start*/ 0x816, WordBreakProperty.Extend],
[/*start*/ 0x81A, WordBreakProperty.ALetter],
[/*start*/ 0x81B, WordBreakProperty.Extend],
[/*start*/ 0x824, WordBreakProperty.ALetter],
[/*start*/ 0x825, WordBreakProperty.Extend],
[/*start*/ 0x828, WordBreakProperty.ALetter],
[/*start*/ 0x829, WordBreakProperty.Extend],
[/*start*/ 0x82E, WordBreakProperty.Other],
[/*start*/ 0x840, WordBreakProperty.ALetter],
[/*start*/ 0x859, WordBreakProperty.Extend],
[/*start*/ 0x85C, WordBreakProperty.Other],
[/*start*/ 0x860, WordBreakProperty.ALetter],
[/*start*/ 0x86B, WordBreakProperty.Other],
[/*start*/ 0x8A0, WordBreakProperty.ALetter],
[/*start*/ 0x8B5, WordBreakProperty.Other],
[/*start*/ 0x8B6, WordBreakProperty.ALetter],
[/*start*/ 0x8C8, WordBreakProperty.Other],
[/*start*/ 0x8D3, WordBreakProperty.Extend],
[/*start*/ 0x8E2, WordBreakProperty.Format],
[/*start*/ 0x8E3, WordBreakProperty.Extend],
[/*start*/ 0x904, WordBreakProperty.ALetter],
[/*start*/ 0x93A, WordBreakProperty.Extend],
[/*start*/ 0x93D, WordBreakProperty.ALetter],
[/*start*/ 0x93E, WordBreakProperty.Extend],
[/*start*/ 0x950, WordBreakProperty.ALetter],
[/*start*/ 0x951, WordBreakProperty.Extend],
[/*start*/ 0x958, WordBreakProperty.ALetter],
[/*start*/ 0x962, WordBreakProperty.Extend],
[/*start*/ 0x964, WordBreakProperty.Other],
[/*start*/ 0x966, WordBreakProperty.Numeric],
[/*start*/ 0x970, WordBreakProperty.Other],
[/*start*/ 0x971, WordBreakProperty.ALetter],
[/*start*/ 0x981, WordBreakProperty.Extend],
[/*start*/ 0x984, WordBreakProperty.Other],
[/*start*/ 0x985, WordBreakProperty.ALetter],
[/*start*/ 0x98D, WordBreakProperty.Other],
[/*start*/ 0x98F, WordBreakProperty.ALetter],
[/*start*/ 0x991, WordBreakProperty.Other],
[/*start*/ 0x993, WordBreakProperty.ALetter],
[/*start*/ 0x9A9, WordBreakProperty.Other],
[/*start*/ 0x9AA, WordBreakProperty.ALetter],
[/*start*/ 0x9B1, WordBreakProperty.Other],
[/*start*/ 0x9B2, WordBreakProperty.ALetter],
[/*start*/ 0x9B3, WordBreakProperty.Other],
[/*start*/ 0x9B6, WordBreakProperty.ALetter],
[/*start*/ 0x9BA, WordBreakProperty.Other],
[/*start*/ 0x9BC, WordBreakProperty.Extend],
[/*start*/ 0x9BD, WordBreakProperty.ALetter],
[/*start*/ 0x9BE, WordBreakProperty.Extend],
[/*start*/ 0x9C5, WordBreakProperty.Other],
[/*start*/ 0x9C7, WordBreakProperty.Extend],
[/*start*/ 0x9C9, WordBreakProperty.Other],
[/*start*/ 0x9CB, WordBreakProperty.Extend],
[/*start*/ 0x9CE, WordBreakProperty.ALetter],
[/*start*/ 0x9CF, WordBreakProperty.Other],
[/*start*/ 0x9D7, WordBreakProperty.Extend],
[/*start*/ 0x9D8, WordBreakProperty.Other],
[/*start*/ 0x9DC, WordBreakProperty.ALetter],
[/*start*/ 0x9DE, WordBreakProperty.Other],
[/*start*/ 0x9DF, WordBreakProperty.ALetter],
[/*start*/ 0x9E2, WordBreakProperty.Extend],
[/*start*/ 0x9E4, WordBreakProperty.Other],
[/*start*/ 0x9E6, WordBreakProperty.Numeric],
[/*start*/ 0x9F0, WordBreakProperty.ALetter],
[/*start*/ 0x9F2, WordBreakProperty.Other],
[/*start*/ 0x9FC, WordBreakProperty.ALetter],
[/*start*/ 0x9FD, WordBreakProperty.Other],
[/*start*/ 0x9FE, WordBreakProperty.Extend],
[/*start*/ 0x9FF, WordBreakProperty.Other],
[/*start*/ 0xA01, WordBreakProperty.Extend],
[/*start*/ 0xA04, WordBreakProperty.Other],
[/*start*/ 0xA05, WordBreakProperty.ALetter],
[/*start*/ 0xA0B, WordBreakProperty.Other],
[/*start*/ 0xA0F, WordBreakProperty.ALetter],
[/*start*/ 0xA11, WordBreakProperty.Other],
[/*start*/ 0xA13, WordBreakProperty.ALetter],
[/*start*/ 0xA29, WordBreakProperty.Other],
[/*start*/ 0xA2A, WordBreakProperty.ALetter],
[/*start*/ 0xA31, WordBreakProperty.Other],
[/*start*/ 0xA32, WordBreakProperty.ALetter],
[/*start*/ 0xA34, WordBreakProperty.Other],
[/*start*/ 0xA35, WordBreakProperty.ALetter],
[/*start*/ 0xA37, WordBreakProperty.Other],
[/*start*/ 0xA38, WordBreakProperty.ALetter],
[/*start*/ 0xA3A, WordBreakProperty.Other],
[/*start*/ 0xA3C, WordBreakProperty.Extend],
[/*start*/ 0xA3D, WordBreakProperty.Other],
[/*start*/ 0xA3E, WordBreakProperty.Extend],
[/*start*/ 0xA43, WordBreakProperty.Other],
[/*start*/ 0xA47, WordBreakProperty.Extend],
[/*start*/ 0xA49, WordBreakProperty.Other],
[/*start*/ 0xA4B, WordBreakProperty.Extend],
[/*start*/ 0xA4E, WordBreakProperty.Other],
[/*start*/ 0xA51, WordBreakProperty.Extend],
[/*start*/ 0xA52, WordBreakProperty.Other],
[/*start*/ 0xA59, WordBreakProperty.ALetter],
[/*start*/ 0xA5D, WordBreakProperty.Other],
[/*start*/ 0xA5E, WordBreakProperty.ALetter],
[/*start*/ 0xA5F, WordBreakProperty.Other],
[/*start*/ 0xA66, WordBreakProperty.Numeric],
[/*start*/ 0xA70, WordBreakProperty.Extend],
[/*start*/ 0xA72, WordBreakProperty.ALetter],
[/*start*/ 0xA75, WordBreakProperty.Extend],
[/*start*/ 0xA76, WordBreakProperty.Other],
[/*start*/ 0xA81, WordBreakProperty.Extend],
[/*start*/ 0xA84, WordBreakProperty.Other],
[/*start*/ 0xA85, WordBreakProperty.ALetter],
[/*start*/ 0xA8E, WordBreakProperty.Other],
[/*start*/ 0xA8F, WordBreakProperty.ALetter],
[/*start*/ 0xA92, WordBreakProperty.Other],
[/*start*/ 0xA93, WordBreakProperty.ALetter],
[/*start*/ 0xAA9, WordBreakProperty.Other],
[/*start*/ 0xAAA, WordBreakProperty.ALetter],
[/*start*/ 0xAB1, WordBreakProperty.Other],
[/*start*/ 0xAB2, WordBreakProperty.ALetter],
[/*start*/ 0xAB4, WordBreakProperty.Other],
[/*start*/ 0xAB5, WordBreakProperty.ALetter],
[/*start*/ 0xABA, WordBreakProperty.Other],
[/*start*/ 0xABC, WordBreakProperty.Extend],
[/*start*/ 0xABD, WordBreakProperty.ALetter],
[/*start*/ 0xABE, WordBreakProperty.Extend],
[/*start*/ 0xAC6, WordBreakProperty.Other],
[/*start*/ 0xAC7, WordBreakProperty.Extend],
[/*start*/ 0xACA, WordBreakProperty.Other],
[/*start*/ 0xACB, WordBreakProperty.Extend],
[/*start*/ 0xACE, WordBreakProperty.Other],
[/*start*/ 0xAD0, WordBreakProperty.ALetter],
[/*start*/ 0xAD1, WordBreakProperty.Other],
[/*start*/ 0xAE0, WordBreakProperty.ALetter],
[/*start*/ 0xAE2, WordBreakProperty.Extend],
[/*start*/ 0xAE4, WordBreakProperty.Other],
[/*start*/ 0xAE6, WordBreakProperty.Numeric],
[/*start*/ 0xAF0, WordBreakProperty.Other],
[/*start*/ 0xAF9, WordBreakProperty.ALetter],
[/*start*/ 0xAFA, WordBreakProperty.Extend],
[/*start*/ 0xB00, WordBreakProperty.Other],
[/*start*/ 0xB01, WordBreakProperty.Extend],
[/*start*/ 0xB04, WordBreakProperty.Other],
[/*start*/ 0xB05, WordBreakProperty.ALetter],
[/*start*/ 0xB0D, WordBreakProperty.Other],
[/*start*/ 0xB0F, WordBreakProperty.ALetter],
[/*start*/ 0xB11, WordBreakProperty.Other],
[/*start*/ 0xB13, WordBreakProperty.ALetter],
[/*start*/ 0xB29, WordBreakProperty.Other],
[/*start*/ 0xB2A, WordBreakProperty.ALetter],
[/*start*/ 0xB31, WordBreakProperty.Other],
[/*start*/ 0xB32, WordBreakProperty.ALetter],
[/*start*/ 0xB34, WordBreakProperty.Other],
[/*start*/ 0xB35, WordBreakProperty.ALetter],
[/*start*/ 0xB3A, WordBreakProperty.Other],
[/*start*/ 0xB3C, WordBreakProperty.Extend],
[/*start*/ 0xB3D, WordBreakProperty.ALetter],
[/*start*/ 0xB3E, WordBreakProperty.Extend],
[/*start*/ 0xB45, WordBreakProperty.Other],
[/*start*/ 0xB47, WordBreakProperty.Extend],
[/*start*/ 0xB49, WordBreakProperty.Other],
[/*start*/ 0xB4B, WordBreakProperty.Extend],
[/*start*/ 0xB4E, WordBreakProperty.Other],
[/*start*/ 0xB55, WordBreakProperty.Extend],
[/*start*/ 0xB58, WordBreakProperty.Other],
[/*start*/ 0xB5C, WordBreakProperty.ALetter],
[/*start*/ 0xB5E, WordBreakProperty.Other],
[/*start*/ 0xB5F, WordBreakProperty.ALetter],
[/*start*/ 0xB62, WordBreakProperty.Extend],
[/*start*/ 0xB64, WordBreakProperty.Other],
[/*start*/ 0xB66, WordBreakProperty.Numeric],
[/*start*/ 0xB70, WordBreakProperty.Other],
[/*start*/ 0xB71, WordBreakProperty.ALetter],
[/*start*/ 0xB72, WordBreakProperty.Other],
[/*start*/ 0xB82, WordBreakProperty.Extend],
[/*start*/ 0xB83, WordBreakProperty.ALetter],
[/*start*/ 0xB84, WordBreakProperty.Other],
[/*start*/ 0xB85, WordBreakProperty.ALetter],
[/*start*/ 0xB8B, WordBreakProperty.Other],
[/*start*/ 0xB8E, WordBreakProperty.ALetter],
[/*start*/ 0xB91, WordBreakProperty.Other],
[/*start*/ 0xB92, WordBreakProperty.ALetter],
[/*start*/ 0xB96, WordBreakProperty.Other],
[/*start*/ 0xB99, WordBreakProperty.ALetter],
[/*start*/ 0xB9B, WordBreakProperty.Other],
[/*start*/ 0xB9C, WordBreakProperty.ALetter],
[/*start*/ 0xB9D, WordBreakProperty.Other],
[/*start*/ 0xB9E, WordBreakProperty.ALetter],
[/*start*/ 0xBA0, WordBreakProperty.Other],
[/*start*/ 0xBA3, WordBreakProperty.ALetter],
[/*start*/ 0xBA5, WordBreakProperty.Other],
[/*start*/ 0xBA8, WordBreakProperty.ALetter],
[/*start*/ 0xBAB, WordBreakProperty.Other],
[/*start*/ 0xBAE, WordBreakProperty.ALetter],
[/*start*/ 0xBBA, WordBreakProperty.Other],
[/*start*/ 0xBBE, WordBreakProperty.Extend],
[/*start*/ 0xBC3, WordBreakProperty.Other],
[/*start*/ 0xBC6, WordBreakProperty.Extend],
[/*start*/ 0xBC9, WordBreakProperty.Other],
[/*start*/ 0xBCA, WordBreakProperty.Extend],
[/*start*/ 0xBCE, WordBreakProperty.Other],
[/*start*/ 0xBD0, WordBreakProperty.ALetter],
[/*start*/ 0xBD1, WordBreakProperty.Other],
[/*start*/ 0xBD7, WordBreakProperty.Extend],
[/*start*/ 0xBD8, WordBreakProperty.Other],
[/*start*/ 0xBE6, WordBreakProperty.Numeric],
[/*start*/ 0xBF0, WordBreakProperty.Other],
[/*start*/ 0xC00, WordBreakProperty.Extend],
[/*start*/ 0xC05, WordBreakProperty.ALetter],
[/*start*/ 0xC0D, WordBreakProperty.Other],
[/*start*/ 0xC0E, WordBreakProperty.ALetter],
[/*start*/ 0xC11, WordBreakProperty.Other],
[/*start*/ 0xC12, WordBreakProperty.ALetter],
[/*start*/ 0xC29, WordBreakProperty.Other],
[/*start*/ 0xC2A, WordBreakProperty.ALetter],
[/*start*/ 0xC3A, WordBreakProperty.Other],
[/*start*/ 0xC3D, WordBreakProperty.ALetter],
[/*start*/ 0xC3E, WordBreakProperty.Extend],
[/*start*/ 0xC45, WordBreakProperty.Other],
[/*start*/ 0xC46, WordBreakProperty.Extend],
[/*start*/ 0xC49, WordBreakProperty.Other],
[/*start*/ 0xC4A, WordBreakProperty.Extend],
[/*start*/ 0xC4E, WordBreakProperty.Other],
[/*start*/ 0xC55, WordBreakProperty.Extend],
[/*start*/ 0xC57, WordBreakProperty.Other],
[/*start*/ 0xC58, WordBreakProperty.ALetter],
[/*start*/ 0xC5B, WordBreakProperty.Other],
[/*start*/ 0xC60, WordBreakProperty.ALetter],
[/*start*/ 0xC62, WordBreakProperty.Extend],
[/*start*/ 0xC64, WordBreakProperty.Other],
[/*start*/ 0xC66, WordBreakProperty.Numeric],
[/*start*/ 0xC70, WordBreakProperty.Other],
[/*start*/ 0xC80, WordBreakProperty.ALetter],
[/*start*/ 0xC81, WordBreakProperty.Extend],
[/*start*/ 0xC84, WordBreakProperty.Other],
[/*start*/ 0xC85, WordBreakProperty.ALetter],
[/*start*/ 0xC8D, WordBreakProperty.Other],
[/*start*/ 0xC8E, WordBreakProperty.ALetter],
[/*start*/ 0xC91, WordBreakProperty.Other],
[/*start*/ 0xC92, WordBreakProperty.ALetter],
[/*start*/ 0xCA9, WordBreakProperty.Other],
[/*start*/ 0xCAA, WordBreakProperty.ALetter],
[/*start*/ 0xCB4, WordBreakProperty.Other],
[/*start*/ 0xCB5, WordBreakProperty.ALetter],
[/*start*/ 0xCBA, WordBreakProperty.Other],
[/*start*/ 0xCBC, WordBreakProperty.Extend],
[/*start*/ 0xCBD, WordBreakProperty.ALetter],
[/*start*/ 0xCBE, WordBreakProperty.Extend],
[/*start*/ 0xCC5, WordBreakProperty.Other],
[/*start*/ 0xCC6, WordBreakProperty.Extend],
[/*start*/ 0xCC9, WordBreakProperty.Other],
[/*start*/ 0xCCA, WordBreakProperty.Extend],
[/*start*/ 0xCCE, WordBreakProperty.Other],
[/*start*/ 0xCD5, WordBreakProperty.Extend],
[/*start*/ 0xCD7, WordBreakProperty.Other],
[/*start*/ 0xCDE, WordBreakProperty.ALetter],
[/*start*/ 0xCDF, WordBreakProperty.Other],
[/*start*/ 0xCE0, WordBreakProperty.ALetter],
[/*start*/ 0xCE2, WordBreakProperty.Extend],
[/*start*/ 0xCE4, WordBreakProperty.Other],
[/*start*/ 0xCE6, WordBreakProperty.Numeric],
[/*start*/ 0xCF0, WordBreakProperty.Other],
[/*start*/ 0xCF1, WordBreakProperty.ALetter],
[/*start*/ 0xCF3, WordBreakProperty.Other],
[/*start*/ 0xD00, WordBreakProperty.Extend],
[/*start*/ 0xD04, WordBreakProperty.ALetter],
[/*start*/ 0xD0D, WordBreakProperty.Other],
[/*start*/ 0xD0E, WordBreakProperty.ALetter],
[/*start*/ 0xD11, WordBreakProperty.Other],
[/*start*/ 0xD12, WordBreakProperty.ALetter],
[/*start*/ 0xD3B, WordBreakProperty.Extend],
[/*start*/ 0xD3D, WordBreakProperty.ALetter],
[/*start*/ 0xD3E, WordBreakProperty.Extend],
[/*start*/ 0xD45, WordBreakProperty.Other],
[/*start*/ 0xD46, WordBreakProperty.Extend],
[/*start*/ 0xD49, WordBreakProperty.Other],
[/*start*/ 0xD4A, WordBreakProperty.Extend],
[/*start*/ 0xD4E, WordBreakProperty.ALetter],
[/*start*/ 0xD4F, WordBreakProperty.Other],
[/*start*/ 0xD54, WordBreakProperty.ALetter],
[/*start*/ 0xD57, WordBreakProperty.Extend],
[/*start*/ 0xD58, WordBreakProperty.Other],
[/*start*/ 0xD5F, WordBreakProperty.ALetter],
[/*start*/ 0xD62, WordBreakProperty.Extend],
[/*start*/ 0xD64, WordBreakProperty.Other],
[/*start*/ 0xD66, WordBreakProperty.Numeric],
[/*start*/ 0xD70, WordBreakProperty.Other],
[/*start*/ 0xD7A, WordBreakProperty.ALetter],
[/*start*/ 0xD80, WordBreakProperty.Other],
[/*start*/ 0xD81, WordBreakProperty.Extend],
[/*start*/ 0xD84, WordBreakProperty.Other],
[/*start*/ 0xD85, WordBreakProperty.ALetter],
[/*start*/ 0xD97, WordBreakProperty.Other],
[/*start*/ 0xD9A, WordBreakProperty.ALetter],
[/*start*/ 0xDB2, WordBreakProperty.Other],
[/*start*/ 0xDB3, WordBreakProperty.ALetter],
[/*start*/ 0xDBC, WordBreakProperty.Other],
[/*start*/ 0xDBD, WordBreakProperty.ALetter],
[/*start*/ 0xDBE, WordBreakProperty.Other],
[/*start*/ 0xDC0, WordBreakProperty.ALetter],
[/*start*/ 0xDC7, WordBreakProperty.Other],
[/*start*/ 0xDCA, WordBreakProperty.Extend],
[/*start*/ 0xDCB, WordBreakProperty.Other],
[/*start*/ 0xDCF, WordBreakProperty.Extend],
[/*start*/ 0xDD5, WordBreakProperty.Other],
[/*start*/ 0xDD6, WordBreakProperty.Extend],
[/*start*/ 0xDD7, WordBreakProperty.Other],
[/*start*/ 0xDD8, WordBreakProperty.Extend],
[/*start*/ 0xDE0, WordBreakProperty.Other],
[/*start*/ 0xDE6, WordBreakProperty.Numeric],
[/*start*/ 0xDF0, WordBreakProperty.Other],
[/*start*/ 0xDF2, WordBreakProperty.Extend],
[/*start*/ 0xDF4, WordBreakProperty.Other],
[/*start*/ 0xE31, WordBreakProperty.Extend],
[/*start*/ 0xE32, WordBreakProperty.Other],
[/*start*/ 0xE34, WordBreakProperty.Extend],
[/*start*/ 0xE3B, WordBreakProperty.Other],
[/*start*/ 0xE47, WordBreakProperty.Extend],
[/*start*/ 0xE4F, WordBreakProperty.Other],
[/*start*/ 0xE50, WordBreakProperty.Numeric],
[/*start*/ 0xE5A, WordBreakProperty.Other],
[/*start*/ 0xEB1, WordBreakProperty.Extend],
[/*start*/ 0xEB2, WordBreakProperty.Other],
[/*start*/ 0xEB4, WordBreakProperty.Extend],
[/*start*/ 0xEBD, WordBreakProperty.Other],
[/*start*/ 0xEC8, WordBreakProperty.Extend],
[/*start*/ 0xECE, WordBreakProperty.Other],
[/*start*/ 0xED0, WordBreakProperty.Numeric],
[/*start*/ 0xEDA, WordBreakProperty.Other],
[/*start*/ 0xF00, WordBreakProperty.ALetter],
[/*start*/ 0xF01, WordBreakProperty.Other],
[/*start*/ 0xF18, WordBreakProperty.Extend],
[/*start*/ 0xF1A, WordBreakProperty.Other],
[/*start*/ 0xF20, WordBreakProperty.Numeric],
[/*start*/ 0xF2A, WordBreakProperty.Other],
[/*start*/ 0xF35, WordBreakProperty.Extend],
[/*start*/ 0xF36, WordBreakProperty.Other],
[/*start*/ 0xF37, WordBreakProperty.Extend],
[/*start*/ 0xF38, WordBreakProperty.Other],
[/*start*/ 0xF39, WordBreakProperty.Extend],
[/*start*/ 0xF3A, WordBreakProperty.Other],
[/*start*/ 0xF3E, WordBreakProperty.Extend],
[/*start*/ 0xF40, WordBreakProperty.ALetter],
[/*start*/ 0xF48, WordBreakProperty.Other],
[/*start*/ 0xF49, WordBreakProperty.ALetter],
[/*start*/ 0xF6D, WordBreakProperty.Other],
[/*start*/ 0xF71, WordBreakProperty.Extend],
[/*start*/ 0xF85, WordBreakProperty.Other],
[/*start*/ 0xF86, WordBreakProperty.Extend],
[/*start*/ 0xF88, WordBreakProperty.ALetter],
[/*start*/ 0xF8D, WordBreakProperty.Extend],
[/*start*/ 0xF98, WordBreakProperty.Other],
[/*start*/ 0xF99, WordBreakProperty.Extend],
[/*start*/ 0xFBD, WordBreakProperty.Other],
[/*start*/ 0xFC6, WordBreakProperty.Extend],
[/*start*/ 0xFC7, WordBreakProperty.Other],
[/*start*/ 0x102B, WordBreakProperty.Extend],
[/*start*/ 0x103F, WordBreakProperty.Other],
[/*start*/ 0x1040, WordBreakProperty.Numeric],
[/*start*/ 0x104A, WordBreakProperty.Other],
[/*start*/ 0x1056, WordBreakProperty.Extend],
[/*start*/ 0x105A, WordBreakProperty.Other],
[/*start*/ 0x105E, WordBreakProperty.Extend],
[/*start*/ 0x1061, WordBreakProperty.Other],
[/*start*/ 0x1062, WordBreakProperty.Extend],
[/*start*/ 0x1065, WordBreakProperty.Other],
[/*start*/ 0x1067, WordBreakProperty.Extend],
[/*start*/ 0x106E, WordBreakProperty.Other],
[/*start*/ 0x1071, WordBreakProperty.Extend],
[/*start*/ 0x1075, WordBreakProperty.Other],
[/*start*/ 0x1082, WordBreakProperty.Extend],
[/*start*/ 0x108E, WordBreakProperty.Other],
[/*start*/ 0x108F, WordBreakProperty.Extend],
[/*start*/ 0x1090, WordBreakProperty.Numeric],
[/*start*/ 0x109A, WordBreakProperty.Extend],
[/*start*/ 0x109E, WordBreakProperty.Other],
[/*start*/ 0x10A0, WordBreakProperty.ALetter],
[/*start*/ 0x10C6, WordBreakProperty.Other],
[/*start*/ 0x10C7, WordBreakProperty.ALetter],
[/*start*/ 0x10C8, WordBreakProperty.Other],
[/*start*/ 0x10CD, WordBreakProperty.ALetter],
[/*start*/ 0x10CE, WordBreakProperty.Other],
[/*start*/ 0x10D0, WordBreakProperty.ALetter],
[/*start*/ 0x10FB, WordBreakProperty.Other],
[/*start*/ 0x10FC, WordBreakProperty.ALetter],
[/*start*/ 0x1249, WordBreakProperty.Other],
[/*start*/ 0x124A, WordBreakProperty.ALetter],
[/*start*/ 0x124E, WordBreakProperty.Other],
[/*start*/ 0x1250, WordBreakProperty.ALetter],
[/*start*/ 0x1257, WordBreakProperty.Other],
[/*start*/ 0x1258, WordBreakProperty.ALetter],
[/*start*/ 0x1259, WordBreakProperty.Other],
[/*start*/ 0x125A, WordBreakProperty.ALetter],
[/*start*/ 0x125E, WordBreakProperty.Other],
[/*start*/ 0x1260, WordBreakProperty.ALetter],
[/*start*/ 0x1289, WordBreakProperty.Other],
[/*start*/ 0x128A, WordBreakProperty.ALetter],
[/*start*/ 0x128E, WordBreakProperty.Other],
[/*start*/ 0x1290, WordBreakProperty.ALetter],
[/*start*/ 0x12B1, WordBreakProperty.Other],
[/*start*/ 0x12B2, WordBreakProperty.ALetter],
[/*start*/ 0x12B6, WordBreakProperty.Other],
[/*start*/ 0x12B8, WordBreakProperty.ALetter],
[/*start*/ 0x12BF, WordBreakProperty.Other],
[/*start*/ 0x12C0, WordBreakProperty.ALetter],
[/*start*/ 0x12C1, WordBreakProperty.Other],
[/*start*/ 0x12C2, WordBreakProperty.ALetter],
[/*start*/ 0x12C6, WordBreakProperty.Other],
[/*start*/ 0x12C8, WordBreakProperty.ALetter],
[/*start*/ 0x12D7, WordBreakProperty.Other],
[/*start*/ 0x12D8, WordBreakProperty.ALetter],
[/*start*/ 0x1311, WordBreakProperty.Other],
[/*start*/ 0x1312, WordBreakProperty.ALetter],
[/*start*/ 0x1316, WordBreakProperty.Other],
[/*start*/ 0x1318, WordBreakProperty.ALetter],
[/*start*/ 0x135B, WordBreakProperty.Other],
[/*start*/ 0x135D, WordBreakProperty.Extend],
[/*start*/ 0x1360, WordBreakProperty.Other],
[/*start*/ 0x1380, WordBreakProperty.ALetter],
[/*start*/ 0x1390, WordBreakProperty.Other],
[/*start*/ 0x13A0, WordBreakProperty.ALetter],
[/*start*/ 0x13F6, WordBreakProperty.Other],
[/*start*/ 0x13F8, WordBreakProperty.ALetter],
[/*start*/ 0x13FE, WordBreakProperty.Other],
[/*start*/ 0x1401, WordBreakProperty.ALetter],
[/*start*/ 0x166D, WordBreakProperty.Other],
[/*start*/ 0x166F, WordBreakProperty.ALetter],
[/*start*/ 0x1680, WordBreakProperty.WSegSpace],
[/*start*/ 0x1681, WordBreakProperty.ALetter],
[/*start*/ 0x169B, WordBreakProperty.Other],
[/*start*/ 0x16A0, WordBreakProperty.ALetter],
[/*start*/ 0x16EB, WordBreakProperty.Other],
[/*start*/ 0x16EE, WordBreakProperty.ALetter],
[/*start*/ 0x16F9, WordBreakProperty.Other],
[/*start*/ 0x1700, WordBreakProperty.ALetter],
[/*start*/ 0x170D, WordBreakProperty.Other],
[/*start*/ 0x170E, WordBreakProperty.ALetter],
[/*start*/ 0x1712, WordBreakProperty.Extend],
[/*start*/ 0x1715, WordBreakProperty.Other],
[/*start*/ 0x1720, WordBreakProperty.ALetter],
[/*start*/ 0x1732, WordBreakProperty.Extend],
[/*start*/ 0x1735, WordBreakProperty.Other],
[/*start*/ 0x1740, WordBreakProperty.ALetter],
[/*start*/ 0x1752, WordBreakProperty.Extend],
[/*start*/ 0x1754, WordBreakProperty.Other],
[/*start*/ 0x1760, WordBreakProperty.ALetter],
[/*start*/ 0x176D, WordBreakProperty.Other],
[/*start*/ 0x176E, WordBreakProperty.ALetter],
[/*start*/ 0x1771, WordBreakProperty.Other],
[/*start*/ 0x1772, WordBreakProperty.Extend],
[/*start*/ 0x1774, WordBreakProperty.Other],
[/*start*/ 0x17B4, WordBreakProperty.Extend],
[/*start*/ 0x17D4, WordBreakProperty.Other],
[/*start*/ 0x17DD, WordBreakProperty.Extend],
[/*start*/ 0x17DE, WordBreakProperty.Other],
[/*start*/ 0x17E0, WordBreakProperty.Numeric],
[/*start*/ 0x17EA, WordBreakProperty.Other],
[/*start*/ 0x180B, WordBreakProperty.Extend],
[/*start*/ 0x180E, WordBreakProperty.Format],
[/*start*/ 0x180F, WordBreakProperty.Other],
[/*start*/ 0x1810, WordBreakProperty.Numeric],
[/*start*/ 0x181A, WordBreakProperty.Other],
[/*start*/ 0x1820, WordBreakProperty.ALetter],
[/*start*/ 0x1879, WordBreakProperty.Other],
[/*start*/ 0x1880, WordBreakProperty.ALetter],
[/*start*/ 0x1885, WordBreakProperty.Extend],
[/*start*/ 0x1887, WordBreakProperty.ALetter],
[/*start*/ 0x18A9, WordBreakProperty.Extend],
[/*start*/ 0x18AA, WordBreakProperty.ALetter],
[/*start*/ 0x18AB, WordBreakProperty.Other],
[/*start*/ 0x18B0, WordBreakProperty.ALetter],
[/*start*/ 0x18F6, WordBreakProperty.Other],
[/*start*/ 0x1900, WordBreakProperty.ALetter],
[/*start*/ 0x191F, WordBreakProperty.Other],
[/*start*/ 0x1920, WordBreakProperty.Extend],
[/*start*/ 0x192C, WordBreakProperty.Other],
[/*start*/ 0x1930, WordBreakProperty.Extend],
[/*start*/ 0x193C, WordBreakProperty.Other],
[/*start*/ 0x1946, WordBreakProperty.Numeric],
[/*start*/ 0x1950, WordBreakProperty.Other],
[/*start*/ 0x19D0, WordBreakProperty.Numeric],
[/*start*/ 0x19DA, WordBreakProperty.Other],
[/*start*/ 0x1A00, WordBreakProperty.ALetter],
[/*start*/ 0x1A17, WordBreakProperty.Extend],
[/*start*/ 0x1A1C, WordBreakProperty.Other],
[/*start*/ 0x1A55, WordBreakProperty.Extend],
[/*start*/ 0x1A5F, WordBreakProperty.Other],
[/*start*/ 0x1A60, WordBreakProperty.Extend],
[/*start*/ 0x1A7D, WordBreakProperty.Other],
[/*start*/ 0x1A7F, WordBreakProperty.Extend],
[/*start*/ 0x1A80, WordBreakProperty.Numeric],
[/*start*/ 0x1A8A, WordBreakProperty.Other],
[/*start*/ 0x1A90, WordBreakProperty.Numeric],
[/*start*/ 0x1A9A, WordBreakProperty.Other],
[/*start*/ 0x1AB0, WordBreakProperty.Extend],
[/*start*/ 0x1AC1, WordBreakProperty.Other],
[/*start*/ 0x1B00, WordBreakProperty.Extend],
[/*start*/ 0x1B05, WordBreakProperty.ALetter],
[/*start*/ 0x1B34, WordBreakProperty.Extend],
[/*start*/ 0x1B45, WordBreakProperty.ALetter],
[/*start*/ 0x1B4C, WordBreakProperty.Other],
[/*start*/ 0x1B50, WordBreakProperty.Numeric],
[/*start*/ 0x1B5A, WordBreakProperty.Other],
[/*start*/ 0x1B6B, WordBreakProperty.Extend],
[/*start*/ 0x1B74, WordBreakProperty.Other],
[/*start*/ 0x1B80, WordBreakProperty.Extend],
[/*start*/ 0x1B83, WordBreakProperty.ALetter],
[/*start*/ 0x1BA1, WordBreakProperty.Extend],
[/*start*/ 0x1BAE, WordBreakProperty.ALetter],
[/*start*/ 0x1BB0, WordBreakProperty.Numeric],
[/*start*/ 0x1BBA, WordBreakProperty.ALetter],
[/*start*/ 0x1BE6, WordBreakProperty.Extend],
[/*start*/ 0x1BF4, WordBreakProperty.Other],
[/*start*/ 0x1C00, WordBreakProperty.ALetter],
[/*start*/ 0x1C24, WordBreakProperty.Extend],
[/*start*/ 0x1C38, WordBreakProperty.Other],
[/*start*/ 0x1C40, WordBreakProperty.Numeric],
[/*start*/ 0x1C4A, WordBreakProperty.Other],
[/*start*/ 0x1C4D, WordBreakProperty.ALetter],
[/*start*/ 0x1C50, WordBreakProperty.Numeric],
[/*start*/ 0x1C5A, WordBreakProperty.ALetter],
[/*start*/ 0x1C7E, WordBreakProperty.Other],
[/*start*/ 0x1C80, WordBreakProperty.ALetter],
[/*start*/ 0x1C89, WordBreakProperty.Other],
[/*start*/ 0x1C90, WordBreakProperty.ALetter],
[/*start*/ 0x1CBB, WordBreakProperty.Other],
[/*start*/ 0x1CBD, WordBreakProperty.ALetter],
[/*start*/ 0x1CC0, WordBreakProperty.Other],
[/*start*/ 0x1CD0, WordBreakProperty.Extend],
[/*start*/ 0x1CD3, WordBreakProperty.Other],
[/*start*/ 0x1CD4, WordBreakProperty.Extend],
[/*start*/ 0x1CE9, WordBreakProperty.ALetter],
[/*start*/ 0x1CED, WordBreakProperty.Extend],
[/*start*/ 0x1CEE, WordBreakProperty.ALetter],
[/*start*/ 0x1CF4, WordBreakProperty.Extend],
[/*start*/ 0x1CF5, WordBreakProperty.ALetter],
[/*start*/ 0x1CF7, WordBreakProperty.Extend],
[/*start*/ 0x1CFA, WordBreakProperty.ALetter],
[/*start*/ 0x1CFB, WordBreakProperty.Other],
[/*start*/ 0x1D00, WordBreakProperty.ALetter],
[/*start*/ 0x1DC0, WordBreakProperty.Extend],
[/*start*/ 0x1DFA, WordBreakProperty.Other],
[/*start*/ 0x1DFB, WordBreakProperty.Extend],
[/*start*/ 0x1E00, WordBreakProperty.ALetter],
[/*start*/ 0x1F16, WordBreakProperty.Other],
[/*start*/ 0x1F18, WordBreakProperty.ALetter],
[/*start*/ 0x1F1E, WordBreakProperty.Other],
[/*start*/ 0x1F20, WordBreakProperty.ALetter],
[/*start*/ 0x1F46, WordBreakProperty.Other],
[/*start*/ 0x1F48, WordBreakProperty.ALetter],
[/*start*/ 0x1F4E, WordBreakProperty.Other],
[/*start*/ 0x1F50, WordBreakProperty.ALetter],
[/*start*/ 0x1F58, WordBreakProperty.Other],
[/*start*/ 0x1F59, WordBreakProperty.ALetter],
[/*start*/ 0x1F5A, WordBreakProperty.Other],
[/*start*/ 0x1F5B, WordBreakProperty.ALetter],
[/*start*/ 0x1F5C, WordBreakProperty.Other],
[/*start*/ 0x1F5D, WordBreakProperty.ALetter],
[/*start*/ 0x1F5E, WordBreakProperty.Other],
[/*start*/ 0x1F5F, WordBreakProperty.ALetter],
[/*start*/ 0x1F7E, WordBreakProperty.Other],
[/*start*/ 0x1F80, WordBreakProperty.ALetter],
[/*start*/ 0x1FB5, WordBreakProperty.Other],
[/*start*/ 0x1FB6, WordBreakProperty.ALetter],
[/*start*/ 0x1FBD, WordBreakProperty.Other],
[/*start*/ 0x1FBE, WordBreakProperty.ALetter],
[/*start*/ 0x1FBF, WordBreakProperty.Other],
[/*start*/ 0x1FC2, WordBreakProperty.ALetter],
[/*start*/ 0x1FC5, WordBreakProperty.Other],
[/*start*/ 0x1FC6, WordBreakProperty.ALetter],
[/*start*/ 0x1FCD, WordBreakProperty.Other],
[/*start*/ 0x1FD0, WordBreakProperty.ALetter],
[/*start*/ 0x1FD4, WordBreakProperty.Other],
[/*start*/ 0x1FD6, WordBreakProperty.ALetter],
[/*start*/ 0x1FDC, WordBreakProperty.Other],
[/*start*/ 0x1FE0, WordBreakProperty.ALetter],
[/*start*/ 0x1FED, WordBreakProperty.Other],
[/*start*/ 0x1FF2, WordBreakProperty.ALetter],
[/*start*/ 0x1FF5, WordBreakProperty.Other],
[/*start*/ 0x1FF6, WordBreakProperty.ALetter],
[/*start*/ 0x1FFD, WordBreakProperty.Other],
[/*start*/ 0x2000, WordBreakProperty.WSegSpace],
[/*start*/ 0x2007, WordBreakProperty.Other],
[/*start*/ 0x2008, WordBreakProperty.WSegSpace],
[/*start*/ 0x200B, WordBreakProperty.Other],
[/*start*/ 0x200C, WordBreakProperty.Extend],
[/*start*/ 0x200D, WordBreakProperty.ZWJ],
[/*start*/ 0x200E, WordBreakProperty.Format],
[/*start*/ 0x2010, WordBreakProperty.Other],
[/*start*/ 0x2018, WordBreakProperty.MidNumLet],
[/*start*/ 0x201A, WordBreakProperty.Other],
[/*start*/ 0x2024, WordBreakProperty.MidNumLet],
[/*start*/ 0x2025, WordBreakProperty.Other],
[/*start*/ 0x2027, WordBreakProperty.MidLetter],
[/*start*/ 0x2028, WordBreakProperty.Newline],
[/*start*/ 0x202A, WordBreakProperty.Format],
[/*start*/ 0x202F, WordBreakProperty.ExtendNumLet],
[/*start*/ 0x2030, WordBreakProperty.Other],
[/*start*/ 0x203F, WordBreakProperty.ExtendNumLet],
[/*start*/ 0x2041, WordBreakProperty.Other],
[/*start*/ 0x2044, WordBreakProperty.MidNum],
[/*start*/ 0x2045, WordBreakProperty.Other],
[/*start*/ 0x2054, WordBreakProperty.ExtendNumLet],
[/*start*/ 0x2055, WordBreakProperty.Other],
[/*start*/ 0x205F, WordBreakProperty.WSegSpace],
[/*start*/ 0x2060, WordBreakProperty.Format],
[/*start*/ 0x2065, WordBreakProperty.Other],
[/*start*/ 0x2066, WordBreakProperty.Format],
[/*start*/ 0x2070, WordBreakProperty.Other],
[/*start*/ 0x2071, WordBreakProperty.ALetter],
[/*start*/ 0x2072, WordBreakProperty.Other],
[/*start*/ 0x207F, WordBreakProperty.ALetter],
[/*start*/ 0x2080, WordBreakProperty.Other],
[/*start*/ 0x2090, WordBreakProperty.ALetter],
[/*start*/ 0x209D, WordBreakProperty.Other],
[/*start*/ 0x20D0, WordBreakProperty.Extend],
[/*start*/ 0x20F1, WordBreakProperty.Other],
[/*start*/ 0x2102, WordBreakProperty.ALetter],
[/*start*/ 0x2103, WordBreakProperty.Other],
[/*start*/ 0x2107, WordBreakProperty.ALetter],
[/*start*/ 0x2108, WordBreakProperty.Other],
[/*start*/ 0x210A, WordBreakProperty.ALetter],
[/*start*/ 0x2114, WordBreakProperty.Other],
[/*start*/ 0x2115, WordBreakProperty.ALetter],
[/*start*/ 0x2116, WordBreakProperty.Other],
[/*start*/ 0x2119, WordBreakProperty.ALetter],
[/*start*/ 0x211E, WordBreakProperty.Other],
[/*start*/ 0x2124, WordBreakProperty.ALetter],
[/*start*/ 0x2125, WordBreakProperty.Other],
[/*start*/ 0x2126, WordBreakProperty.ALetter],
[/*start*/ 0x2127, WordBreakProperty.Other],
[/*start*/ 0x2128, WordBreakProperty.ALetter],
[/*start*/ 0x2129, WordBreakProperty.Other],
[/*start*/ 0x212A, WordBreakProperty.ALetter],
[/*start*/ 0x212E, WordBreakProperty.Other],
[/*start*/ 0x212F, WordBreakProperty.ALetter],
[/*start*/ 0x213A, WordBreakProperty.Other],
[/*start*/ 0x213C, WordBreakProperty.ALetter],
[/*start*/ 0x2140, WordBreakProperty.Other],
[/*start*/ 0x2145, WordBreakProperty.ALetter],
[/*start*/ 0x214A, WordBreakProperty.Other],
[/*start*/ 0x214E, WordBreakProperty.ALetter],
[/*start*/ 0x214F, WordBreakProperty.Other],
[/*start*/ 0x2160, WordBreakProperty.ALetter],
[/*start*/ 0x2189, WordBreakProperty.Other],
[/*start*/ 0x24B6, WordBreakProperty.ALetter],
[/*start*/ 0x24EA, WordBreakProperty.Other],
[/*start*/ 0x2C00, WordBreakProperty.ALetter],
[/*start*/ 0x2C2F, WordBreakProperty.Other],
[/*start*/ 0x2C30, WordBreakProperty.ALetter],
[/*start*/ 0x2C5F, WordBreakProperty.Other],
[/*start*/ 0x2C60, WordBreakProperty.ALetter],
[/*start*/ 0x2CE5, WordBreakProperty.Other],
[/*start*/ 0x2CEB, WordBreakProperty.ALetter],
[/*start*/ 0x2CEF, WordBreakProperty.Extend],
[/*start*/ 0x2CF2, WordBreakProperty.ALetter],
[/*start*/ 0x2CF4, WordBreakProperty.Other],
[/*start*/ 0x2D00, WordBreakProperty.ALetter],
[/*start*/ 0x2D26, WordBreakProperty.Other],
[/*start*/ 0x2D27, WordBreakProperty.ALetter],
[/*start*/ 0x2D28, WordBreakProperty.Other],
[/*start*/ 0x2D2D, WordBreakProperty.ALetter],
[/*start*/ 0x2D2E, WordBreakProperty.Other],
[/*start*/ 0x2D30, WordBreakProperty.ALetter],
[/*start*/ 0x2D68, WordBreakProperty.Other],
[/*start*/ 0x2D6F, WordBreakProperty.ALetter],
[/*start*/ 0x2D70, WordBreakProperty.Other],
[/*start*/ 0x2D7F, WordBreakProperty.Extend],
[/*start*/ 0x2D80, WordBreakProperty.ALetter],
[/*start*/ 0x2D97, WordBreakProperty.Other],
[/*start*/ 0x2DA0, WordBreakProperty.ALetter],
[/*start*/ 0x2DA7, WordBreakProperty.Other],
[/*start*/ 0x2DA8, WordBreakProperty.ALetter],
[/*start*/ 0x2DAF, WordBreakProperty.Other],
[/*start*/ 0x2DB0, WordBreakProperty.ALetter],
[/*start*/ 0x2DB7, WordBreakProperty.Other],
[/*start*/ 0x2DB8, WordBreakProperty.ALetter],
[/*start*/ 0x2DBF, WordBreakProperty.Other],
[/*start*/ 0x2DC0, WordBreakProperty.ALetter],
[/*start*/ 0x2DC7, WordBreakProperty.Other],
[/*start*/ 0x2DC8, WordBreakProperty.ALetter],
[/*start*/ 0x2DCF, WordBreakProperty.Other],
[/*start*/ 0x2DD0, WordBreakProperty.ALetter],
[/*start*/ 0x2DD7, WordBreakProperty.Other],
[/*start*/ 0x2DD8, WordBreakProperty.ALetter],
[/*start*/ 0x2DDF, WordBreakProperty.Other],
[/*start*/ 0x2DE0, WordBreakProperty.Extend],
[/*start*/ 0x2E00, WordBreakProperty.Other],
[/*start*/ 0x2E2F, WordBreakProperty.ALetter],
[/*start*/ 0x2E30, WordBreakProperty.Other],
[/*start*/ 0x3000, WordBreakProperty.WSegSpace],
[/*start*/ 0x3001, WordBreakProperty.Other],
[/*start*/ 0x3005, WordBreakProperty.ALetter],
[/*start*/ 0x3006, WordBreakProperty.Other],
[/*start*/ 0x302A, WordBreakProperty.Extend],
[/*start*/ 0x3030, WordBreakProperty.Other],
[/*start*/ 0x3031, WordBreakProperty.Katakana],
[/*start*/ 0x3036, WordBreakProperty.Other],
[/*start*/ 0x303B, WordBreakProperty.ALetter],
[/*start*/ 0x303D, WordBreakProperty.Other],
[/*start*/ 0x3099, WordBreakProperty.Extend],
[/*start*/ 0x309B, WordBreakProperty.Katakana],
[/*start*/ 0x309D, WordBreakProperty.Other],
[/*start*/ 0x30A0, WordBreakProperty.Katakana],
[/*start*/ 0x30FB, WordBreakProperty.Other],
[/*start*/ 0x30FC, WordBreakProperty.Katakana],
[/*start*/ 0x3100, WordBreakProperty.Other],
[/*start*/ 0x3105, WordBreakProperty.ALetter],
[/*start*/ 0x3130, WordBreakProperty.Other],
[/*start*/ 0x3131, WordBreakProperty.ALetter],
[/*start*/ 0x318F, WordBreakProperty.Other],
[/*start*/ 0x31A0, WordBreakProperty.ALetter],
[/*start*/ 0x31C0, WordBreakProperty.Other],
[/*start*/ 0x31F0, WordBreakProperty.Katakana],
[/*start*/ 0x3200, WordBreakProperty.Other],
[/*start*/ 0x32D0, WordBreakProperty.Katakana],
[/*start*/ 0x32FF, WordBreakProperty.Other],
[/*start*/ 0x3300, WordBreakProperty.Katakana],
[/*start*/ 0x3358, WordBreakProperty.Other],
[/*start*/ 0xA000, WordBreakProperty.ALetter],
[/*start*/ 0xA48D, WordBreakProperty.Other],
[/*start*/ 0xA4D0, WordBreakProperty.ALetter],
[/*start*/ 0xA4FE, WordBreakProperty.Other],
[/*start*/ 0xA500, WordBreakProperty.ALetter],
[/*start*/ 0xA60D, WordBreakProperty.Other],
[/*start*/ 0xA610, WordBreakProperty.ALetter],
[/*start*/ 0xA620, WordBreakProperty.Numeric],
[/*start*/ 0xA62A, WordBreakProperty.ALetter],
[/*start*/ 0xA62C, WordBreakProperty.Other],
[/*start*/ 0xA640, WordBreakProperty.ALetter],
[/*start*/ 0xA66F, WordBreakProperty.Extend],
[/*start*/ 0xA673, WordBreakProperty.Other],
[/*start*/ 0xA674, WordBreakProperty.Extend],
[/*start*/ 0xA67E, WordBreakProperty.Other],
[/*start*/ 0xA67F, WordBreakProperty.ALetter],
[/*start*/ 0xA69E, WordBreakProperty.Extend],
[/*start*/ 0xA6A0, WordBreakProperty.ALetter],
[/*start*/ 0xA6F0, WordBreakProperty.Extend],
[/*start*/ 0xA6F2, WordBreakProperty.Other],
[/*start*/ 0xA708, WordBreakProperty.ALetter],
[/*start*/ 0xA7C0, WordBreakProperty.Other],
[/*start*/ 0xA7C2, WordBreakProperty.ALetter],
[/*start*/ 0xA7CB, WordBreakProperty.Other],
[/*start*/ 0xA7F5, WordBreakProperty.ALetter],
[/*start*/ 0xA802, WordBreakProperty.Extend],
[/*start*/ 0xA803, WordBreakProperty.ALetter],
[/*start*/ 0xA806, WordBreakProperty.Extend],
[/*start*/ 0xA807, WordBreakProperty.ALetter],
[/*start*/ 0xA80B, WordBreakProperty.Extend],
[/*start*/ 0xA80C, WordBreakProperty.ALetter],
[/*start*/ 0xA823, WordBreakProperty.Extend],
[/*start*/ 0xA828, WordBreakProperty.Other],
[/*start*/ 0xA82C, WordBreakProperty.Extend],
[/*start*/ 0xA82D, WordBreakProperty.Other],
[/*start*/ 0xA840, WordBreakProperty.ALetter],
[/*start*/ 0xA874, WordBreakProperty.Other],
[/*start*/ 0xA880, WordBreakProperty.Extend],
[/*start*/ 0xA882, WordBreakProperty.ALetter],
[/*start*/ 0xA8B4, WordBreakProperty.Extend],
[/*start*/ 0xA8C6, WordBreakProperty.Other],
[/*start*/ 0xA8D0, WordBreakProperty.Numeric],
[/*start*/ 0xA8DA, WordBreakProperty.Other],
[/*start*/ 0xA8E0, WordBreakProperty.Extend],
[/*start*/ 0xA8F2, WordBreakProperty.ALetter],
[/*start*/ 0xA8F8, WordBreakProperty.Other],
[/*start*/ 0xA8FB, WordBreakProperty.ALetter],
[/*start*/ 0xA8FC, WordBreakProperty.Other],
[/*start*/ 0xA8FD, WordBreakProperty.ALetter],
[/*start*/ 0xA8FF, WordBreakProperty.Extend],
[/*start*/ 0xA900, WordBreakProperty.Numeric],
[/*start*/ 0xA90A, WordBreakProperty.ALetter],
[/*start*/ 0xA926, WordBreakProperty.Extend],
[/*start*/ 0xA92E, WordBreakProperty.Other],
[/*start*/ 0xA930, WordBreakProperty.ALetter],
[/*start*/ 0xA947, WordBreakProperty.Extend],
[/*start*/ 0xA954, WordBreakProperty.Other],
[/*start*/ 0xA960, WordBreakProperty.ALetter],
[/*start*/ 0xA97D, WordBreakProperty.Other],
[/*start*/ 0xA980, WordBreakProperty.Extend],
[/*start*/ 0xA984, WordBreakProperty.ALetter],
[/*start*/ 0xA9B3, WordBreakProperty.Extend],
[/*start*/ 0xA9C1, WordBreakProperty.Other],
[/*start*/ 0xA9CF, WordBreakProperty.ALetter],
[/*start*/ 0xA9D0, WordBreakProperty.Numeric],
[/*start*/ 0xA9DA, WordBreakProperty.Other],
[/*start*/ 0xA9E5, WordBreakProperty.Extend],
[/*start*/ 0xA9E6, WordBreakProperty.Other],
[/*start*/ 0xA9F0, WordBreakProperty.Numeric],
[/*start*/ 0xA9FA, WordBreakProperty.Other],
[/*start*/ 0xAA00, WordBreakProperty.ALetter],
[/*start*/ 0xAA29, WordBreakProperty.Extend],
[/*start*/ 0xAA37, WordBreakProperty.Other],
[/*start*/ 0xAA40, WordBreakProperty.ALetter],
[/*start*/ 0xAA43, WordBreakProperty.Extend],
[/*start*/ 0xAA44, WordBreakProperty.ALetter],
[/*start*/ 0xAA4C, WordBreakProperty.Extend],
[/*start*/ 0xAA4E, WordBreakProperty.Other],
[/*start*/ 0xAA50, WordBreakProperty.Numeric],
[/*start*/ 0xAA5A, WordBreakProperty.Other],
[/*start*/ 0xAA7B, WordBreakProperty.Extend],
[/*start*/ 0xAA7E, WordBreakProperty.Other],
[/*start*/ 0xAAB0, WordBreakProperty.Extend],
[/*start*/ 0xAAB1, WordBreakProperty.Other],
[/*start*/ 0xAAB2, WordBreakProperty.Extend],
[/*start*/ 0xAAB5, WordBreakProperty.Other],
[/*start*/ 0xAAB7, WordBreakProperty.Extend],
[/*start*/ 0xAAB9, WordBreakProperty.Other],
[/*start*/ 0xAABE, WordBreakProperty.Extend],
[/*start*/ 0xAAC0, WordBreakProperty.Other],
[/*start*/ 0xAAC1, WordBreakProperty.Extend],
[/*start*/ 0xAAC2, WordBreakProperty.Other],
[/*start*/ 0xAAE0, WordBreakProperty.ALetter],
[/*start*/ 0xAAEB, WordBreakProperty.Extend],
[/*start*/ 0xAAF0, WordBreakProperty.Other],
[/*start*/ 0xAAF2, WordBreakProperty.ALetter],
[/*start*/ 0xAAF5, WordBreakProperty.Extend],
[/*start*/ 0xAAF7, WordBreakProperty.Other],
[/*start*/ 0xAB01, WordBreakProperty.ALetter],
[/*start*/ 0xAB07, WordBreakProperty.Other],
[/*start*/ 0xAB09, WordBreakProperty.ALetter],
[/*start*/ 0xAB0F, WordBreakProperty.Other],
[/*start*/ 0xAB11, WordBreakProperty.ALetter],
[/*start*/ 0xAB17, WordBreakProperty.Other],
[/*start*/ 0xAB20, WordBreakProperty.ALetter],
[/*start*/ 0xAB27, WordBreakProperty.Other],
[/*start*/ 0xAB28, WordBreakProperty.ALetter],
[/*start*/ 0xAB2F, WordBreakProperty.Other],
[/*start*/ 0xAB30, WordBreakProperty.ALetter],
[/*start*/ 0xAB6A, WordBreakProperty.Other],
[/*start*/ 0xAB70, WordBreakProperty.ALetter],
[/*start*/ 0xABE3, WordBreakProperty.Extend],
[/*start*/ 0xABEB, WordBreakProperty.Other],
[/*start*/ 0xABEC, WordBreakProperty.Extend],
[/*start*/ 0xABEE, WordBreakProperty.Other],
[/*start*/ 0xABF0, WordBreakProperty.Numeric],
[/*start*/ 0xABFA, WordBreakProperty.Other],
[/*start*/ 0xAC00, WordBreakProperty.ALetter],
[/*start*/ 0xD7A4, WordBreakProperty.Other],
[/*start*/ 0xD7B0, WordBreakProperty.ALetter],
[/*start*/ 0xD7C7, WordBreakProperty.Other],
[/*start*/ 0xD7CB, WordBreakProperty.ALetter],
[/*start*/ 0xD7FC, WordBreakProperty.Other],
[/*start*/ 0xFB00, WordBreakProperty.ALetter],
[/*start*/ 0xFB07, WordBreakProperty.Other],
[/*start*/ 0xFB13, WordBreakProperty.ALetter],
[/*start*/ 0xFB18, WordBreakProperty.Other],
[/*start*/ 0xFB1D, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB1E, WordBreakProperty.Extend],
[/*start*/ 0xFB1F, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB29, WordBreakProperty.Other],
[/*start*/ 0xFB2A, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB37, WordBreakProperty.Other],
[/*start*/ 0xFB38, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB3D, WordBreakProperty.Other],
[/*start*/ 0xFB3E, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB3F, WordBreakProperty.Other],
[/*start*/ 0xFB40, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB42, WordBreakProperty.Other],
[/*start*/ 0xFB43, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB45, WordBreakProperty.Other],
[/*start*/ 0xFB46, WordBreakProperty.Hebrew_Letter],
[/*start*/ 0xFB50, WordBreakProperty.ALetter],
[/*start*/ 0xFBB2, WordBreakProperty.Other],
[/*start*/ 0xFBD3, WordBreakProperty.ALetter],
[/*start*/ 0xFD3E, WordBreakProperty.Other],
[/*start*/ 0xFD50, WordBreakProperty.ALetter],
[/*start*/ 0xFD90, WordBreakProperty.Other],
[/*start*/ 0xFD92, WordBreakProperty.ALetter],
[/*start*/ 0xFDC8, WordBreakProperty.Other],
[/*start*/ 0xFDF0, WordBreakProperty.ALetter],
[/*start*/ 0xFDFC, WordBreakProperty.Other],
[/*start*/ 0xFE00, WordBreakProperty.Extend],
[/*start*/ 0xFE10, WordBreakProperty.MidNum],
[/*start*/ 0xFE11, WordBreakProperty.Other],
[/*start*/ 0xFE13, WordBreakProperty.MidLetter],
[/*start*/ 0xFE14, WordBreakProperty.MidNum],
[/*start*/ 0xFE15, WordBreakProperty.Other],
[/*start*/ 0xFE20, WordBreakProperty.Extend],
[/*start*/ 0xFE30, WordBreakProperty.Other],
[/*start*/ 0xFE33, WordBreakProperty.ExtendNumLet],
[/*start*/ 0xFE35, WordBreakProperty.Other],
[/*start*/ 0xFE4D, WordBreakProperty.ExtendNumLet],
[/*start*/ 0xFE50, WordBreakProperty.MidNum],
[/*start*/ 0xFE51, WordBreakProperty.Other],
[/*start*/ 0xFE52, WordBreakProperty.MidNumLet],
[/*start*/ 0xFE53, WordBreakProperty.Other],
[/*start*/ 0xFE54, WordBreakProperty.MidNum],
[/*start*/ 0xFE55, WordBreakProperty.MidLetter],
[/*start*/ 0xFE56, WordBreakProperty.Other],
[/*start*/ 0xFE70, WordBreakProperty.ALetter],
[/*start*/ 0xFE75, WordBreakProperty.Other],
[/*start*/ 0xFE76, WordBreakProperty.ALetter],
[/*start*/ 0xFEFD, WordBreakProperty.Other],
[/*start*/ 0xFEFF, WordBreakProperty.Format],
[/*start*/ 0xFF00, WordBreakProperty.Other],
[/*start*/ 0xFF07, WordBreakProperty.MidNumLet],
[/*start*/ 0xFF08, WordBreakProperty.Other],
[/*start*/ 0xFF0C, WordBreakProperty.MidNum],
[/*start*/ 0xFF0D, WordBreakProperty.Other],
[/*start*/ 0xFF0E, WordBreakProperty.MidNumLet],
[/*start*/ 0xFF0F, WordBreakProperty.Other],
[/*start*/ 0xFF10, WordBreakProperty.Numeric],
[/*start*/ 0xFF1A, WordBreakProperty.MidLetter],
[/*start*/ 0xFF1B, WordBreakProperty.MidNum],
[/*start*/ 0xFF1C, WordBreakProperty.Other],
[/*start*/ 0xFF21, WordBreakProperty.ALetter],
[/*start*/ 0xFF3B, WordBreakProperty.Other],
[/*start*/ 0xFF3F, WordBreakProperty.ExtendNumLet],
[/*start*/ 0xFF40, WordBreakProperty.Other],
[/*start*/ 0xFF41, WordBreakProperty.ALetter],
[/*start*/ 0xFF5B, WordBreakProperty.Other],
[/*start*/ 0xFF66, WordBreakProperty.Katakana],
[/*start*/ 0xFF9E, WordBreakProperty.Extend],
[/*start*/ 0xFFA0, WordBreakProperty.ALetter],
[/*start*/ 0xFFBF, WordBreakProperty.Other],
[/*start*/ 0xFFC2, WordBreakProperty.ALetter],
[/*start*/ 0xFFC8, WordBreakProperty.Other],
[/*start*/ 0xFFCA, WordBreakProperty.ALetter],
[/*start*/ 0xFFD0, WordBreakProperty.Other],
[/*start*/ 0xFFD2, WordBreakProperty.ALetter],
[/*start*/ 0xFFD8, WordBreakProperty.Other],
[/*start*/ 0xFFDA, WordBreakProperty.ALetter],
[/*start*/ 0xFFDD, WordBreakProperty.Other],
[/*start*/ 0xFFF9, WordBreakProperty.Format],
[/*start*/ 0xFFFC, WordBreakProperty.Other],
[/*start*/ 0x10000, WordBreakProperty.ALetter],
[/*start*/ 0x1000C, WordBreakProperty.Other],
[/*start*/ 0x1000D, WordBreakProperty.ALetter],
[/*start*/ 0x10027, WordBreakProperty.Other],
[/*start*/ 0x10028, WordBreakProperty.ALetter],
[/*start*/ 0x1003B, WordBreakProperty.Other],
[/*start*/ 0x1003C, WordBreakProperty.ALetter],
[/*start*/ 0x1003E, WordBreakProperty.Other],
[/*start*/ 0x1003F, WordBreakProperty.ALetter],
[/*start*/ 0x1004E, WordBreakProperty.Other],
[/*start*/ 0x10050, WordBreakProperty.ALetter],
[/*start*/ 0x1005E, WordBreakProperty.Other],
[/*start*/ 0x10080, WordBreakProperty.ALetter],
[/*start*/ 0x100FB, WordBreakProperty.Other],
[/*start*/ 0x10140, WordBreakProperty.ALetter],
[/*start*/ 0x10175, WordBreakProperty.Other],
[/*start*/ 0x101FD, WordBreakProperty.Extend],
[/*start*/ 0x101FE, WordBreakProperty.Other],
[/*start*/ 0x10280, WordBreakProperty.ALetter],
[/*start*/ 0x1029D, WordBreakProperty.Other],
[/*start*/ 0x102A0, WordBreakProperty.ALetter],
[/*start*/ 0x102D1, WordBreakProperty.Other],
[/*start*/ 0x102E0, WordBreakProperty.Extend],
[/*start*/ 0x102E1, WordBreakProperty.Other],
[/*start*/ 0x10300, WordBreakProperty.ALetter],
[/*start*/ 0x10320, WordBreakProperty.Other],
[/*start*/ 0x1032D, WordBreakProperty.ALetter],
[/*start*/ 0x1034B, WordBreakProperty.Other],
[/*start*/ 0x10350, WordBreakProperty.ALetter],
[/*start*/ 0x10376, WordBreakProperty.Extend],
[/*start*/ 0x1037B, WordBreakProperty.Other],
[/*start*/ 0x10380, WordBreakProperty.ALetter],
[/*start*/ 0x1039E, WordBreakProperty.Other],
[/*start*/ 0x103A0, WordBreakProperty.ALetter],
[/*start*/ 0x103C4, WordBreakProperty.Other],
[/*start*/ 0x103C8, WordBreakProperty.ALetter],
[/*start*/ 0x103D0, WordBreakProperty.Other],
[/*start*/ 0x103D1, WordBreakProperty.ALetter],
[/*start*/ 0x103D6, WordBreakProperty.Other],
[/*start*/ 0x10400, WordBreakProperty.ALetter],
[/*start*/ 0x1049E, WordBreakProperty.Other],
[/*start*/ 0x104A0, WordBreakProperty.Numeric],
[/*start*/ 0x104AA, WordBreakProperty.Other],
[/*start*/ 0x104B0, WordBreakProperty.ALetter],
[/*start*/ 0x104D4, WordBreakProperty.Other],
[/*start*/ 0x104D8, WordBreakProperty.ALetter],
[/*start*/ 0x104FC, WordBreakProperty.Other],
[/*start*/ 0x10500, WordBreakProperty.ALetter],
[/*start*/ 0x10528, WordBreakProperty.Other],
[/*start*/ 0x10530, WordBreakProperty.ALetter],
[/*start*/ 0x10564, WordBreakProperty.Other],
[/*start*/ 0x10600, WordBreakProperty.ALetter],
[/*start*/ 0x10737, WordBreakProperty.Other],
[/*start*/ 0x10740, WordBreakProperty.ALetter],
[/*start*/ 0x10756, WordBreakProperty.Other],
[/*start*/ 0x10760, WordBreakProperty.ALetter],
[/*start*/ 0x10768, WordBreakProperty.Other],
[/*start*/ 0x10800, WordBreakProperty.ALetter],
[/*start*/ 0x10806, WordBreakProperty.Other],
[/*start*/ 0x10808, WordBreakProperty.ALetter],
[/*start*/ 0x10809, WordBreakProperty.Other],
[/*start*/ 0x1080A, WordBreakProperty.ALetter],
[/*start*/ 0x10836, WordBreakProperty.Other],
[/*start*/ 0x10837, WordBreakProperty.ALetter],
[/*start*/ 0x10839, WordBreakProperty.Other],
[/*start*/ 0x1083C, WordBreakProperty.ALetter],
[/*start*/ 0x1083D, WordBreakProperty.Other],
[/*start*/ 0x1083F, WordBreakProperty.ALetter],
[/*start*/ 0x10856, WordBreakProperty.Other],
[/*start*/ 0x10860, WordBreakProperty.ALetter],
[/*start*/ 0x10877, WordBreakProperty.Other],
[/*start*/ 0x10880, WordBreakProperty.ALetter],
[/*start*/ 0x1089F, WordBreakProperty.Other],
[/*start*/ 0x108E0, WordBreakProperty.ALetter],
[/*start*/ 0x108F3, WordBreakProperty.Other],
[/*start*/ 0x108F4, WordBreakProperty.ALetter],
[/*start*/ 0x108F6, WordBreakProperty.Other],
[/*start*/ 0x10900, WordBreakProperty.ALetter],
[/*start*/ 0x10916, WordBreakProperty.Other],
[/*start*/ 0x10920, WordBreakProperty.ALetter],
[/*start*/ 0x1093A, WordBreakProperty.Other],
[/*start*/ 0x10980, WordBreakProperty.ALetter],
[/*start*/ 0x109B8, WordBreakProperty.Other],
[/*start*/ 0x109BE, WordBreakProperty.ALetter],
[/*start*/ 0x109C0, WordBreakProperty.Other],
[/*start*/ 0x10A00, WordBreakProperty.ALetter],
[/*start*/ 0x10A01, WordBreakProperty.Extend],
[/*start*/ 0x10A04, WordBreakProperty.Other],
[/*start*/ 0x10A05, WordBreakProperty.Extend],
[/*start*/ 0x10A07, WordBreakProperty.Other],
[/*start*/ 0x10A0C, WordBreakProperty.Extend],
[/*start*/ 0x10A10, WordBreakProperty.ALetter],
[/*start*/ 0x10A14, WordBreakProperty.Other],
[/*start*/ 0x10A15, WordBreakProperty.ALetter],
[/*start*/ 0x10A18, WordBreakProperty.Other],
[/*start*/ 0x10A19, WordBreakProperty.ALetter],
[/*start*/ 0x10A36, WordBreakProperty.Other],
[/*start*/ 0x10A38, WordBreakProperty.Extend],
[/*start*/ 0x10A3B, WordBreakProperty.Other],
[/*start*/ 0x10A3F, WordBreakProperty.Extend],
[/*start*/ 0x10A40, WordBreakProperty.Other],
[/*start*/ 0x10A60, WordBreakProperty.ALetter],
[/*start*/ 0x10A7D, WordBreakProperty.Other],
[/*start*/ 0x10A80, WordBreakProperty.ALetter],
[/*start*/ 0x10A9D, WordBreakProperty.Other],
[/*start*/ 0x10AC0, WordBreakProperty.ALetter],
[/*start*/ 0x10AC8, WordBreakProperty.Other],
[/*start*/ 0x10AC9, WordBreakProperty.ALetter],
[/*start*/ 0x10AE5, WordBreakProperty.Extend],
[/*start*/ 0x10AE7, WordBreakProperty.Other],
[/*start*/ 0x10B00, WordBreakProperty.ALetter],
[/*start*/ 0x10B36, WordBreakProperty.Other],
[/*start*/ 0x10B40, WordBreakProperty.ALetter],
[/*start*/ 0x10B56, WordBreakProperty.Other],
[/*start*/ 0x10B60, WordBreakProperty.ALetter],
[/*start*/ 0x10B73, WordBreakProperty.Other],
[/*start*/ 0x10B80, WordBreakProperty.ALetter],
[/*start*/ 0x10B92, WordBreakProperty.Other],
[/*start*/ 0x10C00, WordBreakProperty.ALetter],
[/*start*/ 0x10C49, WordBreakProperty.Other],
[/*start*/ 0x10C80, WordBreakProperty.ALetter],
[/*start*/ 0x10CB3, WordBreakProperty.Other],
[/*start*/ 0x10CC0, WordBreakProperty.ALetter],
[/*start*/ 0x10CF3, WordBreakProperty.Other],
[/*start*/ 0x10D00, WordBreakProperty.ALetter],
[/*start*/ 0x10D24, WordBreakProperty.Extend],
[/*start*/ 0x10D28, WordBreakProperty.Other],
[/*start*/ 0x10D30, WordBreakProperty.Numeric],
[/*start*/ 0x10D3A, WordBreakProperty.Other],
[/*start*/ 0x10E80, WordBreakProperty.ALetter],
[/*start*/ 0x10EAA, WordBreakProperty.Other],
[/*start*/ 0x10EAB, WordBreakProperty.Extend],
[/*start*/ 0x10EAD, WordBreakProperty.Other],
[/*start*/ 0x10EB0, WordBreakProperty.ALetter],
[/*start*/ 0x10EB2, WordBreakProperty.Other],
[/*start*/ 0x10F00, WordBreakProperty.ALetter],
[/*start*/ 0x10F1D, WordBreakProperty.Other],
[/*start*/ 0x10F27, WordBreakProperty.ALetter],
[/*start*/ 0x10F28, WordBreakProperty.Other],
[/*start*/ 0x10F30, WordBreakProperty.ALetter],
[/*start*/ 0x10F46, WordBreakProperty.Extend],
[/*start*/ 0x10F51, WordBreakProperty.Other],
[/*start*/ 0x10FB0, WordBreakProperty.ALetter],
[/*start*/ 0x10FC5, WordBreakProperty.Other],
[/*start*/ 0x10FE0, WordBreakProperty.ALetter],
[/*start*/ 0x10FF7, WordBreakProperty.Other],
[/*start*/ 0x11000, WordBreakProperty.Extend],
[/*start*/ 0x11003, WordBreakProperty.ALetter],
[/*start*/ 0x11038, WordBreakProperty.Extend],
[/*start*/ 0x11047, WordBreakProperty.Other],
[/*start*/ 0x11066, WordBreakProperty.Numeric],
[/*start*/ 0x11070, WordBreakProperty.Other],
[/*start*/ 0x1107F, WordBreakProperty.Extend],
[/*start*/ 0x11083, WordBreakProperty.ALetter],
[/*start*/ 0x110B0, WordBreakProperty.Extend],
[/*start*/ 0x110BB, WordBreakProperty.Other],
[/*start*/ 0x110BD, WordBreakProperty.Format],
[/*start*/ 0x110BE, WordBreakProperty.Other],
[/*start*/ 0x110CD, WordBreakProperty.Format],
[/*start*/ 0x110CE, WordBreakProperty.Other],
[/*start*/ 0x110D0, WordBreakProperty.ALetter],
[/*start*/ 0x110E9, WordBreakProperty.Other],
[/*start*/ 0x110F0, WordBreakProperty.Numeric],
[/*start*/ 0x110FA, WordBreakProperty.Other],
[/*start*/ 0x11100, WordBreakProperty.Extend],
[/*start*/ 0x11103, WordBreakProperty.ALetter],
[/*start*/ 0x11127, WordBreakProperty.Extend],
[/*start*/ 0x11135, WordBreakProperty.Other],
[/*start*/ 0x11136, WordBreakProperty.Numeric],
[/*start*/ 0x11140, WordBreakProperty.Other],
[/*start*/ 0x11144, WordBreakProperty.ALetter],
[/*start*/ 0x11145, WordBreakProperty.Extend],
[/*start*/ 0x11147, WordBreakProperty.ALetter],
[/*start*/ 0x11148, WordBreakProperty.Other],
[/*start*/ 0x11150, WordBreakProperty.ALetter],
[/*start*/ 0x11173, WordBreakProperty.Extend],
[/*start*/ 0x11174, WordBreakProperty.Other],
[/*start*/ 0x11176, WordBreakProperty.ALetter],
[/*start*/ 0x11177, WordBreakProperty.Other],
[/*start*/ 0x11180, WordBreakProperty.Extend],
[/*start*/ 0x11183, WordBreakProperty.ALetter],
[/*start*/ 0x111B3, WordBreakProperty.Extend],
[/*start*/ 0x111C1, WordBreakProperty.ALetter],
[/*start*/ 0x111C5, WordBreakProperty.Other],
[/*start*/ 0x111C9, WordBreakProperty.Extend],
[/*start*/ 0x111CD, WordBreakProperty.Other],
[/*start*/ 0x111CE, WordBreakProperty.Extend],
[/*start*/ 0x111D0, WordBreakProperty.Numeric],
[/*start*/ 0x111DA, WordBreakProperty.ALetter],
[/*start*/ 0x111DB, WordBreakProperty.Other],
[/*start*/ 0x111DC, WordBreakProperty.ALetter],
[/*start*/ 0x111DD, WordBreakProperty.Other],
[/*start*/ 0x11200, WordBreakProperty.ALetter],
[/*start*/ 0x11212, WordBreakProperty.Other],
[/*start*/ 0x11213, WordBreakProperty.ALetter],
[/*start*/ 0x1122C, WordBreakProperty.Extend],
[/*start*/ 0x11238, WordBreakProperty.Other],
[/*start*/ 0x1123E, WordBreakProperty.Extend],
[/*start*/ 0x1123F, WordBreakProperty.Other],
[/*start*/ 0x11280, WordBreakProperty.ALetter],
[/*start*/ 0x11287, WordBreakProperty.Other],
[/*start*/ 0x11288, WordBreakProperty.ALetter],
[/*start*/ 0x11289, WordBreakProperty.Other],
[/*start*/ 0x1128A, WordBreakProperty.ALetter],
[/*start*/ 0x1128E, WordBreakProperty.Other],
[/*start*/ 0x1128F, WordBreakProperty.ALetter],
[/*start*/ 0x1129E, WordBreakProperty.Other],
[/*start*/ 0x1129F, WordBreakProperty.ALetter],
[/*start*/ 0x112A9, WordBreakProperty.Other],
[/*start*/ 0x112B0, WordBreakProperty.ALetter],
[/*start*/ 0x112DF, WordBreakProperty.Extend],
[/*start*/ 0x112EB, WordBreakProperty.Other],
[/*start*/ 0x112F0, WordBreakProperty.Numeric],
[/*start*/ 0x112FA, WordBreakProperty.Other],
[/*start*/ 0x11300, WordBreakProperty.Extend],
[/*start*/ 0x11304, WordBreakProperty.Other],
[/*start*/ 0x11305, WordBreakProperty.ALetter],
[/*start*/ 0x1130D, WordBreakProperty.Other],
[/*start*/ 0x1130F, WordBreakProperty.ALetter],
[/*start*/ 0x11311, WordBreakProperty.Other],
[/*start*/ 0x11313, WordBreakProperty.ALetter],
[/*start*/ 0x11329, WordBreakProperty.Other],
[/*start*/ 0x1132A, WordBreakProperty.ALetter],
[/*start*/ 0x11331, WordBreakProperty.Other],
[/*start*/ 0x11332, WordBreakProperty.ALetter],
[/*start*/ 0x11334, WordBreakProperty.Other],
[/*start*/ 0x11335, WordBreakProperty.ALetter],
[/*start*/ 0x1133A, WordBreakProperty.Other],
[/*start*/ 0x1133B, WordBreakProperty.Extend],
[/*start*/ 0x1133D, WordBreakProperty.ALetter],
[/*start*/ 0x1133E, WordBreakProperty.Extend],
[/*start*/ 0x11345, WordBreakProperty.Other],
[/*start*/ 0x11347, WordBreakProperty.Extend],
[/*start*/ 0x11349, WordBreakProperty.Other],
[/*start*/ 0x1134B, WordBreakProperty.Extend],
[/*start*/ 0x1134E, WordBreakProperty.Other],
[/*start*/ 0x11350, WordBreakProperty.ALetter],
[/*start*/ 0x11351, WordBreakProperty.Other],
[/*start*/ 0x11357, WordBreakProperty.Extend],
[/*start*/ 0x11358, WordBreakProperty.Other],
[/*start*/ 0x1135D, WordBreakProperty.ALetter],
[/*start*/ 0x11362, WordBreakProperty.Extend],
[/*start*/ 0x11364, WordBreakProperty.Other],
[/*start*/ 0x11366, WordBreakProperty.Extend],
[/*start*/ 0x1136D, WordBreakProperty.Other],
[/*start*/ 0x11370, WordBreakProperty.Extend],
[/*start*/ 0x11375, WordBreakProperty.Other],
[/*start*/ 0x11400, WordBreakProperty.ALetter],
[/*start*/ 0x11435, WordBreakProperty.Extend],
[/*start*/ 0x11447, WordBreakProperty.ALetter],
[/*start*/ 0x1144B, WordBreakProperty.Other],
[/*start*/ 0x11450, WordBreakProperty.Numeric],
[/*start*/ 0x1145A, WordBreakProperty.Other],
[/*start*/ 0x1145E, WordBreakProperty.Extend],
[/*start*/ 0x1145F, WordBreakProperty.ALetter],
[/*start*/ 0x11462, WordBreakProperty.Other],
[/*start*/ 0x11480, WordBreakProperty.ALetter],
[/*start*/ 0x114B0, WordBreakProperty.Extend],
[/*start*/ 0x114C4, WordBreakProperty.ALetter],
[/*start*/ 0x114C6, WordBreakProperty.Other],
[/*start*/ 0x114C7, WordBreakProperty.ALetter],
[/*start*/ 0x114C8, WordBreakProperty.Other],
[/*start*/ 0x114D0, WordBreakProperty.Numeric],
[/*start*/ 0x114DA, WordBreakProperty.Other],
[/*start*/ 0x11580, WordBreakProperty.ALetter],
[/*start*/ 0x115AF, WordBreakProperty.Extend],
[/*start*/ 0x115B6, WordBreakProperty.Other],
[/*start*/ 0x115B8, WordBreakProperty.Extend],
[/*start*/ 0x115C1, WordBreakProperty.Other],
[/*start*/ 0x115D8, WordBreakProperty.ALetter],
[/*start*/ 0x115DC, WordBreakProperty.Extend],
[/*start*/ 0x115DE, WordBreakProperty.Other],
[/*start*/ 0x11600, WordBreakProperty.ALetter],
[/*start*/ 0x11630, WordBreakProperty.Extend],
[/*start*/ 0x11641, WordBreakProperty.Other],
[/*start*/ 0x11644, WordBreakProperty.ALetter],
[/*start*/ 0x11645, WordBreakProperty.Other],
[/*start*/ 0x11650, WordBreakProperty.Numeric],
[/*start*/ 0x1165A, WordBreakProperty.Other],
[/*start*/ 0x11680, WordBreakProperty.ALetter],
[/*start*/ 0x116AB, WordBreakProperty.Extend],
[/*start*/ 0x116B8, WordBreakProperty.ALetter],
[/*start*/ 0x116B9, WordBreakProperty.Other],
[/*start*/ 0x116C0, WordBreakProperty.Numeric],
[/*start*/ 0x116CA, WordBreakProperty.Other],
[/*start*/ 0x1171D, WordBreakProperty.Extend],
[/*start*/ 0x1172C, WordBreakProperty.Other],
[/*start*/ 0x11730, WordBreakProperty.Numeric],
[/*start*/ 0x1173A, WordBreakProperty.Other],
[/*start*/ 0x11800, WordBreakProperty.ALetter],
[/*start*/ 0x1182C, WordBreakProperty.Extend],
[/*start*/ 0x1183B, WordBreakProperty.Other],
[/*start*/ 0x118A0, WordBreakProperty.ALetter],
[/*start*/ 0x118E0, WordBreakProperty.Numeric],
[/*start*/ 0x118EA, WordBreakProperty.Other],
[/*start*/ 0x118FF, WordBreakProperty.ALetter],
[/*start*/ 0x11907, WordBreakProperty.Other],
[/*start*/ 0x11909, WordBreakProperty.ALetter],
[/*start*/ 0x1190A, WordBreakProperty.Other],
[/*start*/ 0x1190C, WordBreakProperty.ALetter],
[/*start*/ 0x11914, WordBreakProperty.Other],
[/*start*/ 0x11915, WordBreakProperty.ALetter],
[/*start*/ 0x11917, WordBreakProperty.Other],
[/*start*/ 0x11918, WordBreakProperty.ALetter],
[/*start*/ 0x11930, WordBreakProperty.Extend],
[/*start*/ 0x11936, WordBreakProperty.Other],
[/*start*/ 0x11937, WordBreakProperty.Extend],
[/*start*/ 0x11939, WordBreakProperty.Other],
[/*start*/ 0x1193B, WordBreakProperty.Extend],
[/*start*/ 0x1193F, WordBreakProperty.ALetter],
[/*start*/ 0x11940, WordBreakProperty.Extend],
[/*start*/ 0x11941, WordBreakProperty.ALetter],
[/*start*/ 0x11942, WordBreakProperty.Extend],
[/*start*/ 0x11944, WordBreakProperty.Other],
[/*start*/ 0x11950, WordBreakProperty.Numeric],
[/*start*/ 0x1195A, WordBreakProperty.Other],
[/*start*/ 0x119A0, WordBreakProperty.ALetter],
[/*start*/ 0x119A8, WordBreakProperty.Other],
[/*start*/ 0x119AA, WordBreakProperty.ALetter],
[/*start*/ 0x119D1, WordBreakProperty.Extend],
[/*start*/ 0x119D8, WordBreakProperty.Other],
[/*start*/ 0x119DA, WordBreakProperty.Extend],
[/*start*/ 0x119E1, WordBreakProperty.ALetter],
[/*start*/ 0x119E2, WordBreakProperty.Other],
[/*start*/ 0x119E3, WordBreakProperty.ALetter],
[/*start*/ 0x119E4, WordBreakProperty.Extend],
[/*start*/ 0x119E5, WordBreakProperty.Other],
[/*start*/ 0x11A00, WordBreakProperty.ALetter],
[/*start*/ 0x11A01, WordBreakProperty.Extend],
[/*start*/ 0x11A0B, WordBreakProperty.ALetter],
[/*start*/ 0x11A33, WordBreakProperty.Extend],
[/*start*/ 0x11A3A, WordBreakProperty.ALetter],
[/*start*/ 0x11A3B, WordBreakProperty.Extend],
[/*start*/ 0x11A3F, WordBreakProperty.Other],
[/*start*/ 0x11A47, WordBreakProperty.Extend],
[/*start*/ 0x11A48, WordBreakProperty.Other],
[/*start*/ 0x11A50, WordBreakProperty.ALetter],
[/*start*/ 0x11A51, WordBreakProperty.Extend],
[/*start*/ 0x11A5C, WordBreakProperty.ALetter],
[/*start*/ 0x11A8A, WordBreakProperty.Extend],
[/*start*/ 0x11A9A, WordBreakProperty.Other],
[/*start*/ 0x11A9D, WordBreakProperty.ALetter],
[/*start*/ 0x11A9E, WordBreakProperty.Other],
[/*start*/ 0x11AC0, WordBreakProperty.ALetter],
[/*start*/ 0x11AF9, WordBreakProperty.Other],
[/*start*/ 0x11C00, WordBreakProperty.ALetter],
[/*start*/ 0x11C09, WordBreakProperty.Other],
[/*start*/ 0x11C0A, WordBreakProperty.ALetter],
[/*start*/ 0x11C2F, WordBreakProperty.Extend],
[/*start*/ 0x11C37, WordBreakProperty.Other],
[/*start*/ 0x11C38, WordBreakProperty.Extend],
[/*start*/ 0x11C40, WordBreakProperty.ALetter],
[/*start*/ 0x11C41, WordBreakProperty.Other],
[/*start*/ 0x11C50, WordBreakProperty.Numeric],
[/*start*/ 0x11C5A, WordBreakProperty.Other],
[/*start*/ 0x11C72, WordBreakProperty.ALetter],
[/*start*/ 0x11C90, WordBreakProperty.Other],
[/*start*/ 0x11C92, WordBreakProperty.Extend],
[/*start*/ 0x11CA8, WordBreakProperty.Other],
[/*start*/ 0x11CA9, WordBreakProperty.Extend],
[/*start*/ 0x11CB7, WordBreakProperty.Other],
[/*start*/ 0x11D00, WordBreakProperty.ALetter],
[/*start*/ 0x11D07, WordBreakProperty.Other],
[/*start*/ 0x11D08, WordBreakProperty.ALetter],
[/*start*/ 0x11D0A, WordBreakProperty.Other],
[/*start*/ 0x11D0B, WordBreakProperty.ALetter],
[/*start*/ 0x11D31, WordBreakProperty.Extend],
[/*start*/ 0x11D37, WordBreakProperty.Other],
[/*start*/ 0x11D3A, WordBreakProperty.Extend],
[/*start*/ 0x11D3B, WordBreakProperty.Other],
[/*start*/ 0x11D3C, WordBreakProperty.Extend],
[/*start*/ 0x11D3E, WordBreakProperty.Other],
[/*start*/ 0x11D3F, WordBreakProperty.Extend],
[/*start*/ 0x11D46, WordBreakProperty.ALetter],
[/*start*/ 0x11D47, WordBreakProperty.Extend],
[/*start*/ 0x11D48, WordBreakProperty.Other],
[/*start*/ 0x11D50, WordBreakProperty.Numeric],
[/*start*/ 0x11D5A, WordBreakProperty.Other],
[/*start*/ 0x11D60, WordBreakProperty.ALetter],
[/*start*/ 0x11D66, WordBreakProperty.Other],
[/*start*/ 0x11D67, WordBreakProperty.ALetter],
[/*start*/ 0x11D69, WordBreakProperty.Other],
[/*start*/ 0x11D6A, WordBreakProperty.ALetter],
[/*start*/ 0x11D8A, WordBreakProperty.Extend],
[/*start*/ 0x11D8F, WordBreakProperty.Other],
[/*start*/ 0x11D90, WordBreakProperty.Extend],
[/*start*/ 0x11D92, WordBreakProperty.Other],
[/*start*/ 0x11D93, WordBreakProperty.Extend],
[/*start*/ 0x11D98, WordBreakProperty.ALetter],
[/*start*/ 0x11D99, WordBreakProperty.Other],
[/*start*/ 0x11DA0, WordBreakProperty.Numeric],
[/*start*/ 0x11DAA, WordBreakProperty.Other],
[/*start*/ 0x11EE0, WordBreakProperty.ALetter],
[/*start*/ 0x11EF3, WordBreakProperty.Extend],
[/*start*/ 0x11EF7, WordBreakProperty.Other],
[/*start*/ 0x11FB0, WordBreakProperty.ALetter],
[/*start*/ 0x11FB1, WordBreakProperty.Other],
[/*start*/ 0x12000, WordBreakProperty.ALetter],
[/*start*/ 0x1239A, WordBreakProperty.Other],
[/*start*/ 0x12400, WordBreakProperty.ALetter],
[/*start*/ 0x1246F, WordBreakProperty.Other],
[/*start*/ 0x12480, WordBreakProperty.ALetter],
[/*start*/ 0x12544, WordBreakProperty.Other],
[/*start*/ 0x13000, WordBreakProperty.ALetter],
[/*start*/ 0x1342F, WordBreakProperty.Other],
[/*start*/ 0x13430, WordBreakProperty.Format],
[/*start*/ 0x13439, WordBreakProperty.Other],
[/*start*/ 0x14400, WordBreakProperty.ALetter],
[/*start*/ 0x14647, WordBreakProperty.Other],
[/*start*/ 0x16800, WordBreakProperty.ALetter],
[/*start*/ 0x16A39, WordBreakProperty.Other],
[/*start*/ 0x16A40, WordBreakProperty.ALetter],
[/*start*/ 0x16A5F, WordBreakProperty.Other],
[/*start*/ 0x16A60, WordBreakProperty.Numeric],
[/*start*/ 0x16A6A, WordBreakProperty.Other],
[/*start*/ 0x16AD0, WordBreakProperty.ALetter],
[/*start*/ 0x16AEE, WordBreakProperty.Other],
[/*start*/ 0x16AF0, WordBreakProperty.Extend],
[/*start*/ 0x16AF5, WordBreakProperty.Other],
[/*start*/ 0x16B00, WordBreakProperty.ALetter],
[/*start*/ 0x16B30, WordBreakProperty.Extend],
[/*start*/ 0x16B37, WordBreakProperty.Other],
[/*start*/ 0x16B40, WordBreakProperty.ALetter],
[/*start*/ 0x16B44, WordBreakProperty.Other],
[/*start*/ 0x16B50, WordBreakProperty.Numeric],
[/*start*/ 0x16B5A, WordBreakProperty.Other],
[/*start*/ 0x16B63, WordBreakProperty.ALetter],
[/*start*/ 0x16B78, WordBreakProperty.Other],
[/*start*/ 0x16B7D, WordBreakProperty.ALetter],
[/*start*/ 0x16B90, WordBreakProperty.Other],
[/*start*/ 0x16E40, WordBreakProperty.ALetter],
[/*start*/ 0x16E80, WordBreakProperty.Other],
[/*start*/ 0x16F00, WordBreakProperty.ALetter],
[/*start*/ 0x16F4B, WordBreakProperty.Other],
[/*start*/ 0x16F4F, WordBreakProperty.Extend],
[/*start*/ 0x16F50, WordBreakProperty.ALetter],
[/*start*/ 0x16F51, WordBreakProperty.Extend],
[/*start*/ 0x16F88, WordBreakProperty.Other],
[/*start*/ 0x16F8F, WordBreakProperty.Extend],
[/*start*/ 0x16F93, WordBreakProperty.ALetter],
[/*start*/ 0x16FA0, WordBreakProperty.Other],
[/*start*/ 0x16FE0, WordBreakProperty.ALetter],
[/*start*/ 0x16FE2, WordBreakProperty.Other],
[/*start*/ 0x16FE3, WordBreakProperty.ALetter],
[/*start*/ 0x16FE4, WordBreakProperty.Extend],
[/*start*/ 0x16FE5, WordBreakProperty.Other],
[/*start*/ 0x16FF0, WordBreakProperty.Extend],
[/*start*/ 0x16FF2, WordBreakProperty.Other],
[/*start*/ 0x1B000, WordBreakProperty.Katakana],
[/*start*/ 0x1B001, WordBreakProperty.Other],
[/*start*/ 0x1B164, WordBreakProperty.Katakana],
[/*start*/ 0x1B168, WordBreakProperty.Other],
[/*start*/ 0x1BC00, WordBreakProperty.ALetter],
[/*start*/ 0x1BC6B, WordBreakProperty.Other],
[/*start*/ 0x1BC70, WordBreakProperty.ALetter],
[/*start*/ 0x1BC7D, WordBreakProperty.Other],
[/*start*/ 0x1BC80, WordBreakProperty.ALetter],
[/*start*/ 0x1BC89, WordBreakProperty.Other],
[/*start*/ 0x1BC90, WordBreakProperty.ALetter],
[/*start*/ 0x1BC9A, WordBreakProperty.Other],
[/*start*/ 0x1BC9D, WordBreakProperty.Extend],
[/*start*/ 0x1BC9F, WordBreakProperty.Other],
[/*start*/ 0x1BCA0, WordBreakProperty.Format],
[/*start*/ 0x1BCA4, WordBreakProperty.Other],
[/*start*/ 0x1D165, WordBreakProperty.Extend],
[/*start*/ 0x1D16A, WordBreakProperty.Other],
[/*start*/ 0x1D16D, WordBreakProperty.Extend],
[/*start*/ 0x1D173, WordBreakProperty.Format],
[/*start*/ 0x1D17B, WordBreakProperty.Extend],
[/*start*/ 0x1D183, WordBreakProperty.Other],
[/*start*/ 0x1D185, WordBreakProperty.Extend],
[/*start*/ 0x1D18C, WordBreakProperty.Other],
[/*start*/ 0x1D1AA, WordBreakProperty.Extend],
[/*start*/ 0x1D1AE, WordBreakProperty.Other],
[/*start*/ 0x1D242, WordBreakProperty.Extend],
[/*start*/ 0x1D245, WordBreakProperty.Other],
[/*start*/ 0x1D400, WordBreakProperty.ALetter],
[/*start*/ 0x1D455, WordBreakProperty.Other],
[/*start*/ 0x1D456, WordBreakProperty.ALetter],
[/*start*/ 0x1D49D, WordBreakProperty.Other],
[/*start*/ 0x1D49E, WordBreakProperty.ALetter],
[/*start*/ 0x1D4A0, WordBreakProperty.Other],
[/*start*/ 0x1D4A2, WordBreakProperty.ALetter],
[/*start*/ 0x1D4A3, WordBreakProperty.Other],
[/*start*/ 0x1D4A5, WordBreakProperty.ALetter],
[/*start*/ 0x1D4A7, WordBreakProperty.Other],
[/*start*/ 0x1D4A9, WordBreakProperty.ALetter],
[/*start*/ 0x1D4AD, WordBreakProperty.Other],
[/*start*/ 0x1D4AE, WordBreakProperty.ALetter],
[/*start*/ 0x1D4BA, WordBreakProperty.Other],
[/*start*/ 0x1D4BB, WordBreakProperty.ALetter],
[/*start*/ 0x1D4BC, WordBreakProperty.Other],
[/*start*/ 0x1D4BD, WordBreakProperty.ALetter],
[/*start*/ 0x1D4C4, WordBreakProperty.Other],
[/*start*/ 0x1D4C5, WordBreakProperty.ALetter],
[/*start*/ 0x1D506, WordBreakProperty.Other],
[/*start*/ 0x1D507, WordBreakProperty.ALetter],
[/*start*/ 0x1D50B, WordBreakProperty.Other],
[/*start*/ 0x1D50D, WordBreakProperty.ALetter],
[/*start*/ 0x1D515, WordBreakProperty.Other],
[/*start*/ 0x1D516, WordBreakProperty.ALetter],
[/*start*/ 0x1D51D, WordBreakProperty.Other],
[/*start*/ 0x1D51E, WordBreakProperty.ALetter],
[/*start*/ 0x1D53A, WordBreakProperty.Other],
[/*start*/ 0x1D53B, WordBreakProperty.ALetter],
[/*start*/ 0x1D53F, WordBreakProperty.Other],
[/*start*/ 0x1D540, WordBreakProperty.ALetter],
[/*start*/ 0x1D545, WordBreakProperty.Other],
[/*start*/ 0x1D546, WordBreakProperty.ALetter],
[/*start*/ 0x1D547, WordBreakProperty.Other],
[/*start*/ 0x1D54A, WordBreakProperty.ALetter],
[/*start*/ 0x1D551, WordBreakProperty.Other],
[/*start*/ 0x1D552, WordBreakProperty.ALetter],
[/*start*/ 0x1D6A6, WordBreakProperty.Other],
[/*start*/ 0x1D6A8, WordBreakProperty.ALetter],
[/*start*/ 0x1D6C1, WordBreakProperty.Other],
[/*start*/ 0x1D6C2, WordBreakProperty.ALetter],
[/*start*/ 0x1D6DB, WordBreakProperty.Other],
[/*start*/ 0x1D6DC, WordBreakProperty.ALetter],
[/*start*/ 0x1D6FB, WordBreakProperty.Other],
[/*start*/ 0x1D6FC, WordBreakProperty.ALetter],
[/*start*/ 0x1D715, WordBreakProperty.Other],
[/*start*/ 0x1D716, WordBreakProperty.ALetter],
[/*start*/ 0x1D735, WordBreakProperty.Other],
[/*start*/ 0x1D736, WordBreakProperty.ALetter],
[/*start*/ 0x1D74F, WordBreakProperty.Other],
[/*start*/ 0x1D750, WordBreakProperty.ALetter],
[/*start*/ 0x1D76F, WordBreakProperty.Other],
[/*start*/ 0x1D770, WordBreakProperty.ALetter],
[/*start*/ 0x1D789, WordBreakProperty.Other],
[/*start*/ 0x1D78A, WordBreakProperty.ALetter],
[/*start*/ 0x1D7A9, WordBreakProperty.Other],
[/*start*/ 0x1D7AA, WordBreakProperty.ALetter],
[/*start*/ 0x1D7C3, WordBreakProperty.Other],
[/*start*/ 0x1D7C4, WordBreakProperty.ALetter],
[/*start*/ 0x1D7CC, WordBreakProperty.Other],
[/*start*/ 0x1D7CE, WordBreakProperty.Numeric],
[/*start*/ 0x1D800, WordBreakProperty.Other],
[/*start*/ 0x1DA00, WordBreakProperty.Extend],
[/*start*/ 0x1DA37, WordBreakProperty.Other],
[/*start*/ 0x1DA3B, WordBreakProperty.Extend],
[/*start*/ 0x1DA6D, WordBreakProperty.Other],
[/*start*/ 0x1DA75, WordBreakProperty.Extend],
[/*start*/ 0x1DA76, WordBreakProperty.Other],
[/*start*/ 0x1DA84, WordBreakProperty.Extend],
[/*start*/ 0x1DA85, WordBreakProperty.Other],
[/*start*/ 0x1DA9B, WordBreakProperty.Extend],
[/*start*/ 0x1DAA0, WordBreakProperty.Other],
[/*start*/ 0x1DAA1, WordBreakProperty.Extend],
[/*start*/ 0x1DAB0, WordBreakProperty.Other],
[/*start*/ 0x1E000, WordBreakProperty.Extend],
[/*start*/ 0x1E007, WordBreakProperty.Other],
[/*start*/ 0x1E008, WordBreakProperty.Extend],
[/*start*/ 0x1E019, WordBreakProperty.Other],
[/*start*/ 0x1E01B, WordBreakProperty.Extend],
[/*start*/ 0x1E022, WordBreakProperty.Other],
[/*start*/ 0x1E023, WordBreakProperty.Extend],
[/*start*/ 0x1E025, WordBreakProperty.Other],
[/*start*/ 0x1E026, WordBreakProperty.Extend],
[/*start*/ 0x1E02B, WordBreakProperty.Other],
[/*start*/ 0x1E100, WordBreakProperty.ALetter],
[/*start*/ 0x1E12D, WordBreakProperty.Other],
[/*start*/ 0x1E130, WordBreakProperty.Extend],
[/*start*/ 0x1E137, WordBreakProperty.ALetter],
[/*start*/ 0x1E13E, WordBreakProperty.Other],
[/*start*/ 0x1E140, WordBreakProperty.Numeric],
[/*start*/ 0x1E14A, WordBreakProperty.Other],
[/*start*/ 0x1E14E, WordBreakProperty.ALetter],
[/*start*/ 0x1E14F, WordBreakProperty.Other],
[/*start*/ 0x1E2C0, WordBreakProperty.ALetter],
[/*start*/ 0x1E2EC, WordBreakProperty.Extend],
[/*start*/ 0x1E2F0, WordBreakProperty.Numeric],
[/*start*/ 0x1E2FA, WordBreakProperty.Other],
[/*start*/ 0x1E800, WordBreakProperty.ALetter],
[/*start*/ 0x1E8C5, WordBreakProperty.Other],
[/*start*/ 0x1E8D0, WordBreakProperty.Extend],
[/*start*/ 0x1E8D7, WordBreakProperty.Other],
[/*start*/ 0x1E900, WordBreakProperty.ALetter],
[/*start*/ 0x1E944, WordBreakProperty.Extend],
[/*start*/ 0x1E94B, WordBreakProperty.ALetter],
[/*start*/ 0x1E94C, WordBreakProperty.Other],
[/*start*/ 0x1E950, WordBreakProperty.Numeric],
[/*start*/ 0x1E95A, WordBreakProperty.Other],
[/*start*/ 0x1EE00, WordBreakProperty.ALetter],
[/*start*/ 0x1EE04, WordBreakProperty.Other],
[/*start*/ 0x1EE05, WordBreakProperty.ALetter],
[/*start*/ 0x1EE20, WordBreakProperty.Other],
[/*start*/ 0x1EE21, WordBreakProperty.ALetter],
[/*start*/ 0x1EE23, WordBreakProperty.Other],
[/*start*/ 0x1EE24, WordBreakProperty.ALetter],
[/*start*/ 0x1EE25, WordBreakProperty.Other],
[/*start*/ 0x1EE27, WordBreakProperty.ALetter],
[/*start*/ 0x1EE28, WordBreakProperty.Other],
[/*start*/ 0x1EE29, WordBreakProperty.ALetter],
[/*start*/ 0x1EE33, WordBreakProperty.Other],
[/*start*/ 0x1EE34, WordBreakProperty.ALetter],
[/*start*/ 0x1EE38, WordBreakProperty.Other],
[/*start*/ 0x1EE39, WordBreakProperty.ALetter],
[/*start*/ 0x1EE3A, WordBreakProperty.Other],
[/*start*/ 0x1EE3B, WordBreakProperty.ALetter],
[/*start*/ 0x1EE3C, WordBreakProperty.Other],
[/*start*/ 0x1EE42, WordBreakProperty.ALetter],
[/*start*/ 0x1EE43, WordBreakProperty.Other],
[/*start*/ 0x1EE47, WordBreakProperty.ALetter],
[/*start*/ 0x1EE48, WordBreakProperty.Other],
[/*start*/ 0x1EE49, WordBreakProperty.ALetter],
[/*start*/ 0x1EE4A, WordBreakProperty.Other],
[/*start*/ 0x1EE4B, WordBreakProperty.ALetter],
[/*start*/ 0x1EE4C, WordBreakProperty.Other],
[/*start*/ 0x1EE4D, WordBreakProperty.ALetter],
[/*start*/ 0x1EE50, WordBreakProperty.Other],
[/*start*/ 0x1EE51, WordBreakProperty.ALetter],
[/*start*/ 0x1EE53, WordBreakProperty.Other],
[/*start*/ 0x1EE54, WordBreakProperty.ALetter],
[/*start*/ 0x1EE55, WordBreakProperty.Other],
[/*start*/ 0x1EE57, WordBreakProperty.ALetter],
[/*start*/ 0x1EE58, WordBreakProperty.Other],
[/*start*/ 0x1EE59, WordBreakProperty.ALetter],
[/*start*/ 0x1EE5A, WordBreakProperty.Other],
[/*start*/ 0x1EE5B, WordBreakProperty.ALetter],
[/*start*/ 0x1EE5C, WordBreakProperty.Other],
[/*start*/ 0x1EE5D, WordBreakProperty.ALetter],
[/*start*/ 0x1EE5E, WordBreakProperty.Other],
[/*start*/ 0x1EE5F, WordBreakProperty.ALetter],
[/*start*/ 0x1EE60, WordBreakProperty.Other],
[/*start*/ 0x1EE61, WordBreakProperty.ALetter],
[/*start*/ 0x1EE63, WordBreakProperty.Other],
[/*start*/ 0x1EE64, WordBreakProperty.ALetter],
[/*start*/ 0x1EE65, WordBreakProperty.Other],
[/*start*/ 0x1EE67, WordBreakProperty.ALetter],
[/*start*/ 0x1EE6B, WordBreakProperty.Other],
[/*start*/ 0x1EE6C, WordBreakProperty.ALetter],
[/*start*/ 0x1EE73, WordBreakProperty.Other],
[/*start*/ 0x1EE74, WordBreakProperty.ALetter],
[/*start*/ 0x1EE78, WordBreakProperty.Other],
[/*start*/ 0x1EE79, WordBreakProperty.ALetter],
[/*start*/ 0x1EE7D, WordBreakProperty.Other],
[/*start*/ 0x1EE7E, WordBreakProperty.ALetter],
[/*start*/ 0x1EE7F, WordBreakProperty.Other],
[/*start*/ 0x1EE80, WordBreakProperty.ALetter],
[/*start*/ 0x1EE8A, WordBreakProperty.Other],
[/*start*/ 0x1EE8B, WordBreakProperty.ALetter],
[/*start*/ 0x1EE9C, WordBreakProperty.Other],
[/*start*/ 0x1EEA1, WordBreakProperty.ALetter],
[/*start*/ 0x1EEA4, WordBreakProperty.Other],
[/*start*/ 0x1EEA5, WordBreakProperty.ALetter],
[/*start*/ 0x1EEAA, WordBreakProperty.Other],
[/*start*/ 0x1EEAB, WordBreakProperty.ALetter],
[/*start*/ 0x1EEBC, WordBreakProperty.Other],
[/*start*/ 0x1F130, WordBreakProperty.ALetter],
[/*start*/ 0x1F14A, WordBreakProperty.Other],
[/*start*/ 0x1F150, WordBreakProperty.ALetter],
[/*start*/ 0x1F16A, WordBreakProperty.Other],
[/*start*/ 0x1F170, WordBreakProperty.ALetter],
[/*start*/ 0x1F18A, WordBreakProperty.Other],
[/*start*/ 0x1F1E6, WordBreakProperty.Regional_Indicator],
[/*start*/ 0x1F200, WordBreakProperty.Other],
[/*start*/ 0x1F3FB, WordBreakProperty.Extend],
[/*start*/ 0x1F400, WordBreakProperty.Other],
[/*start*/ 0x1FBF0, WordBreakProperty.Numeric],
[/*start*/ 0x1FBFA, WordBreakProperty.Other],
[/*start*/ 0xE0001, WordBreakProperty.Format],
[/*start*/ 0xE0002, WordBreakProperty.Other],
[/*start*/ 0xE0020, WordBreakProperty.Extend],
[/*start*/ 0xE0080, WordBreakProperty.Other],
[/*start*/ 0xE0100, WordBreakProperty.Extend],
[/*start*/ 0xE01F0, WordBreakProperty.Other],
];
}
} | the_stack |
import * as debug_ from "debug";
import { BrowserWindow, globalShortcut } from "electron";
import { Headers } from "node-fetch";
import { ToastType } from "readium-desktop/common/models/toast";
import { authActions, historyActions, toastActions } from "readium-desktop/common/redux/actions";
import { takeSpawnEvery } from "readium-desktop/common/redux/sagas/takeSpawnEvery";
import { takeSpawnLeadingChannel } from "readium-desktop/common/redux/sagas/takeSpawnLeading";
import { IOpdsLinkView } from "readium-desktop/common/views/opds";
import { diMainGet, getLibraryWindowFromDi } from "readium-desktop/main/di";
import {
getOpdsAuthenticationChannel, TOpdsAuthenticationChannel,
} from "readium-desktop/main/event";
import { cleanCookieJar } from "readium-desktop/main/network/fetch";
import {
httpPost,
httpSetAuthenticationToken,
IOpdsAuthenticationToken, wipeAuthenticationTokenStorage,
} from "readium-desktop/main/network/http";
import { ContentType } from "readium-desktop/utils/contentType";
import { tryCatchSync } from "readium-desktop/utils/tryCatch";
// eslint-disable-next-line local-rules/typed-redux-saga-use-typed-effects
import { all, call, cancel, delay, join, put, race } from "redux-saga/effects";
import { call as callTyped, fork as forkTyped, take as takeTyped } from "typed-redux-saga/macro";
import { URL } from "url";
import { OPDSAuthenticationDoc } from "@r2-opds-js/opds/opds2/opds2-authentication-doc";
import { encodeURIComponent_RFC3986 } from "@r2-utils-js/_utils/http/UrlUtils";
import { getOpdsRequestCustomProtocolEventChannel, ODPS_AUTH_SCHEME } from "./getEventChannel";
import { initClientSecretToken } from "./apiapp";
// Logger
const filename_ = "readium-desktop:main:saga:auth";
const debug = debug_(filename_);
debug("_");
type TLinkType = "refresh" | "authenticate";
type TLabelName = "login" | "password";
type TAuthName = "id" | "access_token" | "refresh_token" | "token_type";
type TAuthenticationType = "http://opds-spec.org/auth/oauth/password"
| "http://opds-spec.org/auth/oauth/password/apiapp"
| "http://opds-spec.org/auth/oauth/implicit"
| "http://opds-spec.org/auth/basic"
| "http://opds-spec.org/auth/local"
| "http://librarysimplified.org/authtype/SAML-2.0";
const AUTHENTICATION_TYPE: TAuthenticationType[] = [
"http://opds-spec.org/auth/oauth/password",
"http://opds-spec.org/auth/oauth/password/apiapp",
"http://opds-spec.org/auth/oauth/implicit",
"http://opds-spec.org/auth/basic",
"http://opds-spec.org/auth/local",
"http://librarysimplified.org/authtype/SAML-2.0",
];
const LINK_TYPE: TLinkType[] = [
"refresh",
"authenticate",
];
// const LABEL_NAME: TLabelName[] = [
// "login",
// "password",
// ];
const opdsAuthFlow =
(opdsRequestFromCustomProtocol: ReturnType<typeof getOpdsRequestCustomProtocolEventChannel>) =>
function*([doc, baseUrl]: TOpdsAuthenticationChannel) {
debug("opds authenticate flow");
const baseUrlParsed = tryCatchSync(() => new URL(baseUrl), filename_);
if (!baseUrlParsed) {
debug("no valid base url", baseUrl);
return;
}
const authParsed = tryCatchSync(() => opdsAuthDocConverter(doc, baseUrl), filename_);
if (!authParsed) {
debug("authentication doc parsing error");
return;
}
debug("authentication doc parsed", authParsed);
const browserUrl = getHtmlAuthenticationUrl(authParsed);
if (!browserUrl) {
debug("no valid authentication html url");
return;
}
debug("Browser URL", browserUrl);
const authCredentials: IOpdsAuthenticationToken = {
id: authParsed?.id || undefined,
opdsAuthenticationUrl: baseUrl,
tokenType: "Bearer",
refreshUrl: authParsed?.links?.refresh?.url || undefined,
authenticateUrl: authParsed?.links?.authenticate?.url || undefined,
};
debug("authentication credential config", authCredentials);
yield* callTyped(httpSetAuthenticationToken, authCredentials);
const task = yield* forkTyped(function*() {
const parsedRequest = yield* takeTyped(opdsRequestFromCustomProtocol);
return {
request: parseRequestFromCustomProtocol(parsedRequest.request),
callback: parsedRequest.callback,
};
});
const win =
tryCatchSync(
() => createOpdsAuthenticationModalWin(browserUrl),
filename_,
);
if (!win) {
debug("modal win undefined");
yield cancel(task);
return;
}
try {
yield race({
a: delay(60000),
b: join(task),
c: call(
async () =>
new Promise<void>((resolve) => win.on("close", () => resolve())),
),
});
if (task.isRunning()) {
debug("no authentication credentials received");
debug("perhaps timeout or closing authentication window occured");
return;
} else {
const { request: opdsCustomProtocolRequestParsed, callback } = task.result();
if (opdsCustomProtocolRequestParsed) {
if (!opdsCustomProtocolRequestParsed.data ||
!Object.keys(opdsCustomProtocolRequestParsed.data).length) {
debug("authentication window was cancelled");
return;
}
const [, err] = yield* callTyped(opdsSetAuthCredentials,
opdsCustomProtocolRequestParsed,
authCredentials,
authParsed.authenticationType,
);
callback({
url: undefined,
});
if (err instanceof Error) {
debug(err.message);
return;
} else {
yield put(historyActions.refresh.build());
yield put(authActions.done.build());
}
}
}
} finally {
if (win) {
win.close();
}
if (task.isRunning()) {
yield cancel(task);
}
}
};
function* opdsAuthWipeData() {
debug("Wipping authentication data");
yield* callTyped(cleanCookieJar);
yield* callTyped(wipeAuthenticationTokenStorage);
yield put(toastActions.openRequest.build(ToastType.Success, "👍"));
debug("End of wipping auth data");
}
export function saga() {
const opdsAuthChannel = getOpdsAuthenticationChannel();
const opdsRequestChannel = getOpdsRequestCustomProtocolEventChannel();
return all([
takeSpawnLeadingChannel(
opdsAuthChannel,
opdsAuthFlow(opdsRequestChannel),
(e) => debug("redux OPDS authentication channel error", e),
),
takeSpawnEvery(
authActions.wipeData.ID,
opdsAuthWipeData,
(e) => debug("opds authentication data wipping error", e),
),
]);
}
// -----
async function opdsSetAuthCredentials(
opdsCustomProtocolRequestParsed: IParseRequestFromCustomProtocol<TLabelName | TAuthName>,
authCredentials: IOpdsAuthenticationToken,
authenticationType: TAuthenticationType,
): Promise<[undefined, Error]> {
if (!opdsCustomProtocolRequestParsed) {
return [, new Error("")];
}
const { url: { host, searchParams }, method, data } = opdsCustomProtocolRequestParsed;
if (host === "authorize") {
// handle GET or POST request
if (method === "POST") {
let postDataCredential: IOpdsAuthenticationToken;
if (authenticationType === "http://opds-spec.org/auth/basic") {
postDataCredential = {
accessToken:
Buffer.from(
`${data.login}:${data.password}`,
).toString("base64"),
refreshToken: undefined,
tokenType: "basic",
};
} else {
const requestTokenFromCredentials =
await (async (): Promise<[IOpdsAuthenticationToken, Error]> => {
// payload in function of authenticationType
const payload: any = {
username: data.login,
password: data.password,
};
if (authenticationType === "http://opds-spec.org/auth/oauth/password") {
payload.grant_type = "password";
} else if (authenticationType === "http://opds-spec.org/auth/local") {
// do nothing
} else if (authenticationType === "http://opds-spec.org/auth/oauth/password/apiapp") {
payload.client_secret = await initClientSecretToken(authCredentials.id) || "";
payload.client_id = authCredentials.id;
}
const { authenticateUrl } = authCredentials || {};
if (!authenticateUrl) {
return [, new Error("unable to retrieve the authenticate url !!")];
}
const headers = new Headers();
headers.set("Content-Type", ContentType.FormUrlEncoded);
const body = Object.entries(payload).reduce((pv, [k,v]) => `${pv}${pv ? "&" : pv}${k}=${v}`, "");
const { data: postData } = await httpPost<IOpdsAuthenticationToken>(
authenticateUrl,
{
body,
headers,
},
async (res) => {
if (res.isSuccess) {
const _data: any = await res.response.json();
if (typeof _data === "object") {
res.data = {
accessToken: typeof _data.access_token === "string"
? _data.access_token
: undefined,
refreshToken: typeof _data.refresh_token === "string"
? _data.refresh_token
: undefined,
tokenType: (typeof _data.token_type === "string"
? _data.token_type
: undefined) || "Bearer",
};
}
}
return res;
},
);
return [postData, undefined];
})();
const [, err] = requestTokenFromCredentials;
if (err) {
return [, err];
}
[postDataCredential] = requestTokenFromCredentials;
}
if (postDataCredential) {
postDataCredential.tokenType = postDataCredential.tokenType || authCredentials.tokenType || "Bearer";
postDataCredential.tokenType =
postDataCredential.tokenType.charAt(0).toUpperCase() + postDataCredential.tokenType.slice(1);
const newCredentials = { ...authCredentials, ...postDataCredential };
if (typeof newCredentials.accessToken === "string") {
debug("new opds authentication credentials");
await httpSetAuthenticationToken(newCredentials);
return [, undefined];
}
// newCredentials maybe an opds feed
return [, new Error("no accessToken received")];
}
}
if (method === "GET") {
const newCredentials = {
...authCredentials,
id: data.id || searchParams?.get("id") || authCredentials.id || undefined,
tokenType: data.token_type || searchParams?.get("token_type") || authCredentials.tokenType || "Bearer",
refreshToken: data.refresh_token || searchParams?.get("refresh_token") || undefined,
accessToken: data.access_token || searchParams?.get("access_token") || undefined,
};
newCredentials.tokenType =
newCredentials.tokenType.charAt(0).toUpperCase() + newCredentials.tokenType.slice(1);
if (typeof newCredentials.accessToken === "string") {
debug("new opds authentication credentials");
await httpSetAuthenticationToken(newCredentials);
return [, undefined];
}
return [, new Error("no accessToken received")];
}
} else {
return [, new Error("not host path authorize")];
}
return [, new Error("")];
}
function getHtmlAuthenticationUrl(auth: IOPDSAuthDocParsed) {
let browserUrl: string;
switch (auth.authenticationType) {
case "http://opds-spec.org/auth/oauth/implicit": {
browserUrl = auth.links?.authenticate?.url;
break;
}
case "http://librarysimplified.org/authtype/SAML-2.0": {
browserUrl = `${
auth.links?.authenticate?.url
}&redirect_uri=${encodeURIComponent_RFC3986("opds://authorize")}`;
break;
}
case "http://opds-spec.org/auth/local":
case "http://opds-spec.org/auth/basic":
case "http://opds-spec.org/auth/oauth/password":
case "http://opds-spec.org/auth/oauth/password/apiapp": {
const html = encodeURIComponent_RFC3986(
htmlLoginTemplate(
"opds://authorize",
auth.labels?.login,
auth.labels?.password,
auth.title,
auth.logo?.url,
),
);
browserUrl = `data:text/html;charset=utf-8,${html}`;
break;
}
default: {
debug("authentication method not found", auth.authenticationType);
return undefined;
}
}
return browserUrl;
}
interface IOPDSAuthDocParsed {
title: string;
id: string;
authenticationType: TAuthenticationType;
links?: {
[str in TLinkType]?: IOpdsLinkView | undefined;
} | undefined;
labels?: {
[str in TLabelName]?: string | undefined;
} | undefined;
logo?: IOpdsLinkView | undefined;
}
function opdsAuthDocConverter(doc: OPDSAuthenticationDoc, baseUrl: string): IOPDSAuthDocParsed | undefined {
if (!doc || !(doc instanceof OPDSAuthenticationDoc)) {
debug("opds authentication doc is not an instance of the model");
return undefined;
}
if (!doc.Authentication) {
debug("no authentication data in the opds authentication doc");
return undefined;
}
const viewConvert = tryCatchSync(() => {
return diMainGet("opds-feed-view-converter");
}, filename_);
if (!viewConvert) {
debug("no viewConverter !!");
return undefined;
}
const authentication = doc.Authentication.find((v) => AUTHENTICATION_TYPE.includes(v.Type as any));
const links = Array.isArray(authentication.Links)
? authentication.Links.reduce((pv, cv) => {
const rel = (cv.Rel || [])
.reduce((pvRel, cvRel) => pvRel || LINK_TYPE.find((v) => v === cvRel) || "", "") as TLinkType;
if (
rel
&& typeof cv.Href === "string"
) {
const l = viewConvert.convertLinkToView(cv, baseUrl);
return { ...pv, [rel]: l } as IOPDSAuthDocParsed["links"]; // typing error why ?
}
return pv;
}, {} as IOPDSAuthDocParsed["links"])
: undefined;
const labels: IOPDSAuthDocParsed["labels"] = {};
if (typeof authentication.Labels?.Login === "string") {
labels.login = authentication.Labels.Login;
}
if (typeof authentication.Labels?.Password === "string") {
labels.password = authentication.Labels.Password;
}
const logo = tryCatchSync(() => {
const ln = Array.isArray(doc.Links)
? doc.Links.find((v) => {
debug(v);
return (v.Rel || []).includes("logo");
})
: undefined;
if (ln) {
const linkView = viewConvert.convertLinkToView(ln, baseUrl);
return linkView;
}
return undefined;
}, filename_);
return {
title: doc.Title || "",
id: doc.Id || "",
authenticationType: authentication.Type as TAuthenticationType,
links,
labels,
logo,
};
}
function createOpdsAuthenticationModalWin(url: string): BrowserWindow | undefined {
const libWin = tryCatchSync(() => getLibraryWindowFromDi(), filename_);
if (!libWin) {
debug("no lib win !!");
return undefined;
}
const libWinBound = libWin.getBounds();
const win = new BrowserWindow(
{
width: libWinBound?.width || 800,
height: libWinBound?.height || 600,
parent: libWin,
modal: true,
show: false,
});
const handler = () => win.close();
globalShortcut.register("esc", handler);
win.on("close", () => {
globalShortcut.unregister("esc");
});
win.once("ready-to-show", () => {
win.show();
});
// tslint:disable-next-line: no-floating-promises
win.loadURL(url);
return win;
}
interface IParseRequestFromCustomProtocol<T = string> {
url: URL;
method: "GET" | "POST";
data: {
[key in T & string]?: string;
};
}
function parseRequestFromCustomProtocol(req: Electron.ProtocolRequest)
: IParseRequestFromCustomProtocol<TLabelName> | undefined {
debug("########");
debug("opds:// request:", req);
debug("########");
if (typeof req === "object") {
const { method, url, uploadData } = req;
const urlParsed = tryCatchSync(() => new URL(url), filename_);
if (!urlParsed) {
debug("authentication: can't parse the opds:// request url", url);
return undefined;
}
const { protocol: urlProtocol, host } = urlParsed;
if (urlProtocol !== `${ODPS_AUTH_SCHEME}:`) {
debug("bad opds protocol !!", urlProtocol);
return undefined;
}
if (method === "POST") {
if (host === "authorize") {
debug("POST request", uploadData);
if (Array.isArray(uploadData)) {
const [res] = uploadData;
if ((res as any).type === "rawData") {
debug("RAW DATA received");
}
const data =
tryCatchSync(
() => Buffer.from(res.bytes).toString(),
filename_,
) || "";
// do not risk showing plaintext password in console / command line shell
// debug("data", data);
const keyValue = data.split("&");
const values = tryCatchSync(
() => keyValue.reduce(
(pv, cv) => {
const splt = cv.split("=");
const key = decodeURIComponent(splt[0]);
const val = decodeURIComponent(splt[1]);
return {
...pv,
[key]: val,
};
},
{},
),
filename_,
) || {};
// do not risk showing plaintext password in console / command line shell
// debug(values);
return {
url: urlParsed,
method: "POST",
data: values,
};
}
}
}
if (method === "GET") {
if (host === "authorize") {
const urlSearchParam = url.replace("#", "?");
const urlObject = new URL(urlSearchParam);
const data: Record<string, string> = {};
for (const [key, value] of urlObject.searchParams) {
data[key] = value;
}
return {
url: urlParsed,
method: "GET",
data,
};
}
}
}
return undefined;
}
// tslint:disable-next-line: max-line-length
const htmlLoginTemplate = (
urlToSubmit = "",
loginLabel = "login",
passLabel = "password",
title: string | undefined,
logoUrl?: string,
) => {
if (!title) { // includes empty string
title = diMainGet("translator").translate("catalog.opds.auth.login");
}
return `
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>${title}</title>
<!-- Custom styles for this template -->
<style>
body {
font: 13px/20px "Lucida Grande", Tahoma, Verdana, sans-serif;
color: #404040;
background: white;
}
.login {
position: relative;
margin: 30px auto;
padding: 20px 20px 20px;
width: 310px;
background: white;
border-radius: 3px;
-webkit-box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
}
.login:before {
content: '';
position: absolute;
top: -8px;
right: -8px;
bottom: -8px;
left: -8px;
z-index: -1;
background: rgba(0, 0, 0, 0.08);
border-radius: 4px;
}
.login h1 {
margin: -20px -20px 21px;
line-height: 40px;
font-size: 15px;
font-weight: bold;
color: #555;
text-align: center;
text-shadow: 0 1px white;
background: #f3f3f3;
border-bottom: 1px solid #cfcfcf;
border-radius: 3px 3px 0 0;
background-image: -webkit-linear-gradient(top, whiteffd, #eef2f5);
background-image: -moz-linear-gradient(top, whiteffd, #eef2f5);
background-image: -o-linear-gradient(top, whiteffd, #eef2f5);
background-image: linear-gradient(to bottom, whiteffd, #eef2f5);
-webkit-box-shadow: 0 1px whitesmoke;
box-shadow: 0 1px whitesmoke;
}
.login img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
.login p {
margin: 20px 0 0;
}
.login p:first-child {
margin-top: 0;
}
.login input[type=text], .login input[type=password] {
width: 278px;
}
.login p.remember_me {
float: left;
line-height: 31px;
}
.login p.remember_me label {
font-size: 12px;
color: #777;
cursor: pointer;
}
.login p.remember_me input {
position: relative;
bottom: 1px;
margin-right: 4px;
vertical-align: middle;
}
.login p.submit {
text-align: right;
}
.login-help {
margin: 20px 0;
font-size: 11px;
color: white;
text-align: center;
text-shadow: 0 1px #2a85a1;
}
.login-help a {
color: #cce7fa;
text-decoration: none;
}
.login-help a:hover {
text-decoration: underline;
}
:-moz-placeholder {
color: #c9c9c9 !important;
font-size: 13px;
}
::-webkit-input-placeholder {
color: #ccc;
font-size: 13px;
}
input {
font-family: 'Lucida Grande', Tahoma, Verdana, sans-serif;
font-size: 14px;
}
input[type=text], input[type=password] {
margin: 5px;
padding: 0 10px;
width: 200px;
height: 34px;
color: #404040;
background: white;
border: 1px solid;
border-color: #c4c4c4 #d1d1d1 #d4d4d4;
border-radius: 2px;
outline: 5px solid #eff4f7;
-moz-outline-radius: 3px;
-webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
}
input[type=text]:focus, input[type=password]:focus {
border-color: #7dc9e2;
outline-color: #dceefc;
outline-offset: 0;
}
input[type=submit], input[type=button] {
padding: 0 18px;
height: 29px;
font-size: 12px;
font-weight: bold;
color: #527881;
text-shadow: 0 1px #e3f1f1;
background: #cde5ef;
border: 1px solid;
border-color: #b4ccce #b3c0c8 #9eb9c2;
border-radius: 16px;
outline: 0;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
background-image: -webkit-linear-gradient(top, #edf5f8, #cde5ef);
background-image: -moz-linear-gradient(top, #edf5f8, #cde5ef);
background-image: -o-linear-gradient(top, #edf5f8, #cde5ef);
background-image: linear-gradient(to bottom, #edf5f8, #cde5ef);
-webkit-box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
padding-left: 1em;
}
input[type=submit]:active, input[type=button]:active {
background: #cde5ef;
border-color: #9eb9c2 #b3c0c8 #b4ccce;
-webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
}
.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
line-height: 34px;
}
</style>
</head>
<body class="text-center">
<div class="login">
<h1>${title}</h1>
<form method="post" action="${urlToSubmit}">
${logoUrl ? `<img src="${logoUrl}" alt="login logo">` : ""}
<p><input type="text" name="login" value="" placeholder="${loginLabel}"></p>
<p><input type="password" name="password" value="" placeholder="${passLabel}"></p>
<p class="submit">
<input type="button" name="cancel" value="${diMainGet("translator").translate("catalog.opds.auth.cancel")}" onClick="window.location.href='${urlToSubmit}';">
<input type="submit" name="commit" value="${diMainGet("translator").translate("catalog.opds.auth.login")}">
</p>
</form>
</div>
</body>
</html>`;
}; | the_stack |
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import { PubSub } from "@google-cloud/pubsub";
import equal from "fast-deep-equal";
import { loadAuthorMetadata, loadProjectMetadata } from "./metadata";
import { loadBlogStats, makeRepoStats } from "./stats";
import {
deleteAuthorData,
deleteBlogData,
deleteRepoData,
getBlogData,
getRepoData,
listAuthorIds,
listProjectIds,
saveAuthorData,
saveBlogData,
saveRepoData,
saveRepoPage,
} from "./firestore";
import * as content from "./content";
import * as github from "./github";
import { BlogMetadata } from "../../shared/types/BlogMetadata";
import { RepoMetadata } from "../../shared/types/RepoMetadata";
import { AuthorData, ProductKey, RepoPage } from "../../shared/types";
import {
index,
indexAuthor,
unIndexAuthor,
unIndexBlog,
unIndexRepo,
} from "./search";
// See: https://firebase.google.com/docs/functions/writing-and-viewing-logs#console-log
require("firebase-functions/lib/logger/compat");
admin.initializeApp();
const pubsub = new PubSub();
/** Proxy functions */
export { queryProxy, docProxy, emojis } from "./proxy";
/** Search functions */
export { elasticSearch } from "./search";
/** Photo functions */
export { authorPhoto } from "./photos";
/** Sitemap generator */
export { sitemap } from "./sitemap";
/**
* Return elements of a that are not in b
*/
function getDiff<T>(a: T[], b: T[]): T[] {
const setB = new Set(b);
return a.filter((x) => !setB.has(x));
}
async function refreshAllProjects() {
const products = Object.values(ProductKey);
for (const product of products) {
console.log("Refreshing product", product);
// Refresh or create a blog/repo entry for each config JSON
const { blogs, repos } = await loadProjectMetadata(product);
for (const [id, metadata] of Object.entries(blogs)) {
await pubsub.topic("refresh-blog").publishJSON({
product,
id,
metadata,
force: false,
});
}
for (const [id, metadata] of Object.entries(repos)) {
await pubsub.topic("refresh-repo").publishJSON({
product,
id,
metadata,
force: false,
});
}
// Update search indices
await index(product, repos, blogs);
// List all of the existing blogs/repos and
// delete any entries where the JSON no longer exists
const existingIds = await listProjectIds(product);
const newBlogIds = Object.keys(blogs);
const blogsToDelete = getDiff(existingIds.blogs, newBlogIds);
for (const b of blogsToDelete) {
console.log(`Deleting ${product} blog ${b}`);
await deleteBlogData(product, b);
await unIndexBlog(b);
}
const newRepoIds = Object.keys(repos);
const reposToDelete = getDiff(existingIds.repos, newRepoIds);
for (const r of reposToDelete) {
console.log(`Deleting ${product} repo ${r}`);
await deleteRepoData(product, r);
await unIndexRepo(r);
}
}
}
async function refreshAllAuthors() {
const authors = await loadAuthorMetadata();
for (const id in authors) {
const data: AuthorData = {
id,
metadata: authors[id],
};
await saveAuthorData(id, data);
await indexAuthor(data);
}
// List all of the existing authors and
// delete any entries where the JSON no longer exists
const existingIds = await listAuthorIds();
const newAuthorIds = Object.keys(authors);
const authorsToDelete = getDiff(existingIds, newAuthorIds);
for (const a of authorsToDelete) {
console.log(`Deleting author ${a}`);
await deleteAuthorData(a);
await unIndexAuthor(a);
}
// TODO: Author search indexing
}
async function refreshRepoInternal(
product: string,
id: string,
metadata: RepoMetadata,
force: boolean = false
) {
console.log("Refreshing repo", product, id);
// Get the existing repo data from the database
const existing = await getRepoData(product, id);
if (!existing) {
console.log(`[${product}/${id}] is new.`);
}
// Get the latest repo stats from GitHub
const ghRepo = await github.getRepo(metadata.owner, metadata.repo);
const stats = makeRepoStats(existing, ghRepo);
// First save the repo's stats and metadata
const repo = {
id,
product,
metadata,
stats,
};
await saveRepoData(product, repo);
const recentlyPushed =
existing && stats.lastUpdated > existing.stats.lastUpdated;
if (recentlyPushed) {
console.log(
`[${product}/${id}] has been updated since last pull (lastUpdated = ${stats.lastUpdated}).`
);
} else {
console.log(
`[${product}/${id}] not recently pushed (lastUpdated = ${stats.lastUpdated}).`
);
}
const metadataChanged = existing && !equal(existing.metadata, metadata);
if (existing && metadataChanged) {
console.log(`[${product}/${id}] repo has metadata changes.`);
console.log("old", JSON.stringify(existing.metadata));
console.log("new", JSON.stringify(metadata));
} else {
console.log(`[${product}/${id}] does not have metadata changes.`);
}
// We consider the repo recently changed if any of:
// - It did not exist before
// - It had a recent metadata change (on our side)
// - It was recently pushed (on their side)
//
// If the repo is not recently changed, we can exit early to save API calls
const shouldUpdate = !existing || recentlyPushed || metadataChanged || force;
if (!shouldUpdate) {
console.log(`[${product}/${id}] skipping update.`);
return;
}
// First check the license
const license = await github.getRepoLicense(metadata.owner, metadata.repo);
if (!(license.key === "mit" || license.key === "apache-2.0")) {
console.warn(
`Invalid license ${license.key} for repo ${metadata.owner}/${metadata.repo}`
);
// Delete the repo and exit early
await deleteRepoData(product, id);
return;
}
// Then save a document for each page
const pages = [
{
name: "main",
path: metadata.content,
},
...(metadata.pages || []),
];
const branch = ghRepo.default_branch || "master";
let emojis = {};
try {
emojis = await github.getEmojiMap();
} catch (e) {
console.warn("Failed to get emojis from GitHub", e);
}
for (const p of pages) {
// Get Markdown from GitHub
const md = await github.getFileContent(
metadata.owner,
metadata.repo,
branch,
p.path
);
// Render into a series of HTML "sections"
const sections = content.renderContent(
product,
repo,
p.path,
md,
branch,
emojis
);
const data: RepoPage = {
name: p.name,
path: p.path,
sections,
};
await saveRepoPage(product, repo, p.path, data);
}
// Save the licesne as a page
const licensePage: RepoPage = {
name: "License",
path: "license",
sections: [
{
name: "License",
content: `<pre>${license.content}</pre>`,
},
],
};
await saveRepoPage(product, repo, licensePage.path, licensePage);
}
// Cron job to refresh all projects each day
export const refreshProjectsCron = functions
.runWith({
memory: "2GB",
timeoutSeconds: 540,
})
.pubsub.schedule("0 0 * * *")
.onRun(async (context) => {
await refreshAllProjects();
await refreshAllAuthors();
});
// When in the functions emulator we provide some simple webhooks to refresh things
if (process.env.FUNCTIONS_EMULATOR) {
exports.refreshProjects = functions.https.onRequest(
async (request, response) => {
await refreshAllProjects();
response.json({ status: "ok" });
}
);
exports.refreshAuthors = functions.https.onRequest(
async (request, response) => {
await refreshAllAuthors();
response.json({ status: "ok" });
}
);
exports.forceRefreshRepo = functions.https.onRequest(
async (request, response) => {
const product = request.query["product"] as string | undefined;
const id = request.query["id"] as string | undefined;
const forceParam = request.query["force"] as string | undefined;
if (!(product && id)) {
response.status(400).send("Must include product and id query params");
return;
}
const { repos } = await loadProjectMetadata(product);
const metadata = repos[id];
if (!metadata) {
response
.status(404)
.send(`Repo /products/${product}/repos/${id} not found`);
return;
}
// Force is default, ?force=false overrides it
const force = forceParam === "false" ? false : true;
await refreshRepoInternal(product, id, metadata, force);
response.status(200).send(`Refreshed /products/${product}/repos/${id}`);
}
);
}
export const refreshBlog = functions.pubsub
.topic("refresh-blog")
.onPublish(async (message, context) => {
if (!(message.json.product && message.json.id && message.json.metadata)) {
throw new Error(`Invalid message: ${JSON.stringify(message.json)}`);
}
const product = message.json.product as string;
const id = message.json.id as string;
const metadata = message.json.metadata as BlogMetadata;
console.log("Refreshing blog", product, id);
const existing = await getBlogData(product, id);
const stats = await loadBlogStats(metadata, existing);
const blog = {
id,
product,
metadata,
stats,
};
await saveBlogData(product, blog);
});
export const refreshRepo = functions.pubsub
.topic("refresh-repo")
.onPublish(async (message, context) => {
if (!(message.json.product && message.json.id && message.json.metadata)) {
throw new Error(`Invalid message: ${JSON.stringify(message.json)}`);
}
const product = message.json.product as string;
const id = message.json.id as string;
const metadata = message.json.metadata as RepoMetadata;
const force = !!message.json.force;
await refreshRepoInternal(product, id, metadata, force);
}); | the_stack |
import { FlowKind, ShapeBpmnElementKind, ShapeUtil } from '../../../model/bpmn/internal';
import { AssociationDirectionKind, SequenceFlowKind } from '../../../model/bpmn/internal/edge/kinds';
import { MarkerIdentifier, StyleDefault, StyleIdentifier } from '../StyleUtils';
import { BpmnMxGraph } from '../BpmnMxGraph';
import { mxgraph } from '../initializer';
import { mxStylesheet, StyleMap } from 'mxgraph'; // for types
/**
* Configure the styles used for BPMN rendering.
* @category BPMN Theme
* @experimental You may use this to customize the BPMN theme as proposed in the examples. But be aware that the way we store and allow to change the defaults is subject to change.
*/
export class StyleConfigurator {
private specificFlowStyles: Map<FlowKind, (style: StyleMap) => void> = new Map([
[
FlowKind.SEQUENCE_FLOW,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_ENDARROW] = mxgraph.mxConstants.ARROW_BLOCK_THIN;
},
],
[
FlowKind.MESSAGE_FLOW,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_DASHED] = true;
style[mxgraph.mxConstants.STYLE_DASH_PATTERN] = '8 5';
style[mxgraph.mxConstants.STYLE_STARTARROW] = mxgraph.mxConstants.ARROW_OVAL;
style[mxgraph.mxConstants.STYLE_STARTSIZE] = 8;
style[mxgraph.mxConstants.STYLE_STARTFILL] = true;
style[StyleIdentifier.EDGE_START_FILL_COLOR] = StyleDefault.MESSAGE_FLOW_MARKER_START_FILL_COLOR;
style[mxgraph.mxConstants.STYLE_ENDARROW] = mxgraph.mxConstants.ARROW_BLOCK_THIN;
style[mxgraph.mxConstants.STYLE_ENDFILL] = true;
style[StyleIdentifier.EDGE_END_FILL_COLOR] = StyleDefault.MESSAGE_FLOW_MARKER_END_FILL_COLOR;
},
],
[
FlowKind.ASSOCIATION_FLOW,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_DASHED] = true;
style[mxgraph.mxConstants.STYLE_DASH_PATTERN] = '1 2';
style[mxgraph.mxConstants.STYLE_ENDARROW] = mxgraph.mxConstants.ARROW_OPEN_THIN;
style[mxgraph.mxConstants.STYLE_STARTARROW] = mxgraph.mxConstants.ARROW_OPEN_THIN;
style[mxgraph.mxConstants.STYLE_STARTSIZE] = 12;
},
],
]);
private specificSequenceFlowStyles: Map<SequenceFlowKind, (style: StyleMap) => void> = new Map([
[
SequenceFlowKind.DEFAULT,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_STARTARROW] = MarkerIdentifier.ARROW_DASH;
},
],
[
SequenceFlowKind.CONDITIONAL_FROM_ACTIVITY,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_STARTARROW] = mxgraph.mxConstants.ARROW_DIAMOND_THIN;
style[mxgraph.mxConstants.STYLE_STARTSIZE] = 18;
style[mxgraph.mxConstants.STYLE_STARTFILL] = true;
style[StyleIdentifier.EDGE_START_FILL_COLOR] = StyleDefault.SEQUENCE_FLOW_CONDITIONAL_FROM_ACTIVITY_MARKER_FILL_COLOR;
},
],
]);
private specificAssociationFlowStyles: Map<AssociationDirectionKind, (style: StyleMap) => void> = new Map([
[
AssociationDirectionKind.NONE,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_STARTARROW] = undefined;
style[mxgraph.mxConstants.STYLE_ENDARROW] = undefined;
style[mxgraph.mxConstants.STYLE_EDGE] = undefined; // ensure no orthogonal segments, see also https://github.com/process-analytics/bpmn-visualization-js/issues/295
},
],
[
AssociationDirectionKind.ONE,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_STARTARROW] = undefined;
style[mxgraph.mxConstants.STYLE_EDGE] = undefined; // ensure no orthogonal segments, see also https://github.com/process-analytics/bpmn-visualization-js/issues/295
},
],
[
AssociationDirectionKind.BOTH,
(style: StyleMap) => {
style[mxgraph.mxConstants.STYLE_EDGE] = undefined; // ensure no orthogonal segments, see also https://github.com/process-analytics/bpmn-visualization-js/issues/295
},
],
]);
constructor(private graph: BpmnMxGraph) {}
configureStyles(): void {
this.configureDefaultVertexStyle();
this.configurePoolStyle();
this.configureLaneStyle();
this.configureTextAnnotationStyle();
this.configureGroupStyle();
this.configureActivityStyles();
this.configureEventStyles();
this.configureGatewayStyles();
this.configureDefaultEdgeStyle();
this.configureFlowStyles();
}
private getStylesheet(): mxStylesheet {
return this.graph.getStylesheet();
}
private putCellStyle(name: ShapeBpmnElementKind, style: StyleMap): void {
this.getStylesheet().putCellStyle(name, style);
}
private configureDefaultVertexStyle(): void {
StyleConfigurator.configureCommonDefaultStyle(this.getStylesheet().getDefaultVertexStyle());
}
private configurePoolStyle(): void {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = mxgraph.mxConstants.SHAPE_SWIMLANE;
// label style
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_MIDDLE;
style[mxgraph.mxConstants.STYLE_ALIGN] = mxgraph.mxConstants.ALIGN_CENTER;
style[mxgraph.mxConstants.STYLE_STARTSIZE] = StyleDefault.POOL_LABEL_SIZE;
style[mxgraph.mxConstants.STYLE_FILLCOLOR] = StyleDefault.POOL_LABEL_FILL_COLOR;
this.graph.getStylesheet().putCellStyle(ShapeBpmnElementKind.POOL, style);
}
private configureLaneStyle(): void {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = mxgraph.mxConstants.SHAPE_SWIMLANE;
// label style
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_MIDDLE;
style[mxgraph.mxConstants.STYLE_ALIGN] = mxgraph.mxConstants.ALIGN_CENTER;
style[mxgraph.mxConstants.STYLE_SWIMLANE_LINE] = 0; // hide the line between the title region and the content area
style[mxgraph.mxConstants.STYLE_STARTSIZE] = StyleDefault.LANE_LABEL_SIZE;
style[mxgraph.mxConstants.STYLE_FILLCOLOR] = StyleDefault.LANE_LABEL_FILL_COLOR;
this.graph.getStylesheet().putCellStyle(ShapeBpmnElementKind.LANE, style);
}
private configureEventStyles(): void {
ShapeUtil.eventKinds().forEach(kind => {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = kind;
style[mxgraph.mxConstants.STYLE_PERIMETER] = mxgraph.mxPerimeter.EllipsePerimeter;
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = kind == ShapeBpmnElementKind.EVENT_END ? StyleDefault.STROKE_WIDTH_THICK : StyleDefault.STROKE_WIDTH_THIN;
style[mxgraph.mxConstants.STYLE_VERTICAL_LABEL_POSITION] = mxgraph.mxConstants.ALIGN_BOTTOM;
this.putCellStyle(kind, style);
});
}
private configureTextAnnotationStyle(): void {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = ShapeBpmnElementKind.TEXT_ANNOTATION;
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_MIDDLE;
style[mxgraph.mxConstants.STYLE_ALIGN] = mxgraph.mxConstants.ALIGN_LEFT;
style[mxgraph.mxConstants.STYLE_SPACING_LEFT] = 5;
style[mxgraph.mxConstants.STYLE_FILLCOLOR] = StyleDefault.TEXT_ANNOTATION_FILL_COLOR;
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = StyleDefault.STROKE_WIDTH_THIN;
this.putCellStyle(ShapeBpmnElementKind.TEXT_ANNOTATION, style);
}
private configureGroupStyle(): void {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_ROUNDED] = true;
style[mxgraph.mxConstants.STYLE_ABSOLUTE_ARCSIZE] = true;
style[mxgraph.mxConstants.STYLE_ARCSIZE] = StyleDefault.SHAPE_ARC_SIZE;
style[mxgraph.mxConstants.STYLE_DASHED] = true;
style[mxgraph.mxConstants.STYLE_DASH_PATTERN] = '7 4 1 4';
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = StyleDefault.STROKE_WIDTH_THIN;
style[mxgraph.mxConstants.STYLE_FILLCOLOR] = StyleDefault.GROUP_FILL_COLOR;
// Default label positioning
style[mxgraph.mxConstants.STYLE_ALIGN] = mxgraph.mxConstants.ALIGN_CENTER;
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_TOP;
this.putCellStyle(ShapeBpmnElementKind.GROUP, style);
}
private configureActivityStyles(): void {
ShapeUtil.activityKinds().forEach(kind => {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = kind;
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_MIDDLE;
style[mxgraph.mxConstants.STYLE_ABSOLUTE_ARCSIZE] = true;
style[mxgraph.mxConstants.STYLE_ARCSIZE] = StyleDefault.SHAPE_ARC_SIZE;
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = kind == ShapeBpmnElementKind.CALL_ACTIVITY ? StyleDefault.STROKE_WIDTH_THICK : StyleDefault.STROKE_WIDTH_THIN;
this.putCellStyle(kind, style);
});
}
private configureGatewayStyles(): void {
ShapeUtil.gatewayKinds().forEach(kind => {
const style: StyleMap = {};
style[mxgraph.mxConstants.STYLE_SHAPE] = kind;
style[mxgraph.mxConstants.STYLE_PERIMETER] = mxgraph.mxPerimeter.RhombusPerimeter;
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = StyleDefault.STROKE_WIDTH_THIN;
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_TOP;
// Default label positioning
style[mxgraph.mxConstants.STYLE_LABEL_POSITION] = mxgraph.mxConstants.ALIGN_LEFT;
style[mxgraph.mxConstants.STYLE_VERTICAL_LABEL_POSITION] = mxgraph.mxConstants.ALIGN_TOP;
this.putCellStyle(kind, style);
});
}
private configureDefaultEdgeStyle(): void {
const style = this.getStylesheet().getDefaultEdgeStyle();
style[mxgraph.mxConstants.STYLE_SHAPE] = StyleIdentifier.EDGE;
style[mxgraph.mxConstants.STYLE_EDGE] = mxgraph.mxConstants.EDGESTYLE_SEGMENT;
style[mxgraph.mxConstants.STYLE_ENDSIZE] = 12;
style[mxgraph.mxConstants.STYLE_STROKEWIDTH] = 1.5;
style[mxgraph.mxConstants.STYLE_ROUNDED] = 1;
style[mxgraph.mxConstants.STYLE_ARCSIZE] = 5;
style[mxgraph.mxConstants.STYLE_VERTICAL_ALIGN] = mxgraph.mxConstants.ALIGN_BOTTOM;
delete style[mxgraph.mxConstants.STYLE_ENDARROW];
StyleConfigurator.configureCommonDefaultStyle(style);
}
private static configureCommonDefaultStyle(style: StyleMap): void {
style[mxgraph.mxConstants.STYLE_FONTFAMILY] = StyleDefault.DEFAULT_FONT_FAMILY;
style[mxgraph.mxConstants.STYLE_FONTSIZE] = StyleDefault.DEFAULT_FONT_SIZE;
style[mxgraph.mxConstants.STYLE_FONTCOLOR] = StyleDefault.DEFAULT_FONT_COLOR;
style[mxgraph.mxConstants.STYLE_FILLCOLOR] = StyleDefault.DEFAULT_FILL_COLOR;
style[mxgraph.mxConstants.STYLE_STROKECOLOR] = StyleDefault.DEFAULT_STROKE_COLOR;
style[mxgraph.mxConstants.STYLE_LABEL_BACKGROUNDCOLOR] = mxgraph.mxConstants.NONE;
// only works with html labels (enabled by MxGraphConfigurator)
style[mxgraph.mxConstants.STYLE_WHITE_SPACE] = 'wrap';
}
private configureEdgeStyles<T>(styleKinds: T[], specificStyles: Map<T, (style: StyleMap) => void>): void {
styleKinds.forEach(kind => {
const style: StyleMap = {};
const updateEdgeStyle =
specificStyles.get(kind) ||
(() => {
// Do nothing
});
updateEdgeStyle(style);
this.graph.getStylesheet().putCellStyle(kind.toString(), style);
});
}
private configureSequenceFlowStyles(): void {
this.configureEdgeStyles<SequenceFlowKind>(Object.values(SequenceFlowKind), this.specificSequenceFlowStyles);
}
private configureAssociationFlowStyles(): void {
this.configureEdgeStyles<AssociationDirectionKind>(Object.values(AssociationDirectionKind), this.specificAssociationFlowStyles);
}
private configureFlowStyles(): void {
this.configureEdgeStyles<FlowKind>(Object.values(FlowKind), this.specificFlowStyles);
this.configureSequenceFlowStyles();
this.configureAssociationFlowStyles();
}
} | the_stack |
import { createElement, attributes, Browser, L10n, EmitType, isUndefined, detach } from '@syncfusion/ej2-base';
import { isNullOrUndefined, EventHandler } from '@syncfusion/ej2-base';
import { createSpinner, showSpinner } from '@syncfusion/ej2-popups';
import { Uploader } from '../src/uploader/uploader';
import {profile , inMB, getMemoryProfile} from './common.spec';
describe('Uploader Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Basics', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
element.setAttribute('name', 'files');
uploadObj = new Uploader({ autoUpload: false});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('get module name', () => {
expect(uploadObj.getModuleName()).toBe('uploader');
});
it('control class validation', () => {
expect(uploadObj.element.classList.contains('e-control')).toBe(true);
expect(uploadObj.element.classList.contains('e-uploader')).toBe(true);
})
it('default value validation', () => {
expect(uploadObj.multiple).toBe(true);
expect(uploadObj.autoUpload).toBe(false);
expect(uploadObj.enableRtl).toBe(false);
expect(uploadObj.enabled).toBe(true);
})
it('element structure testing', () => {
expect(uploadObj.element.parentElement.classList.contains('e-file-select')).toBe(true);
expect(uploadObj.browseButton.innerText).toEqual('Browse...');
expect(uploadObj.uploadWrapper.classList.contains('e-upload')).toBe(true);
})
it('file selection validate', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(2);
})
it('check li elements', () => {
let liElement = uploadObj.listParent.querySelectorAll('li');
expect(liElement.length).toBe(2);
expect(liElement[0].classList.contains('e-upload-file-list')).toBe(true);
})
it('clear method test', () => {
let liElement = uploadObj.listParent.querySelectorAll('li');
expect(liElement.length).toBe(2);
uploadObj.clearAll();
expect(uploadObj.listParent).toBe(null);
});
});
describe('API testing for', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {name: 'fileUpload'}});
document.body.appendChild(element);
element.setAttribute('tabindex', '2');
element.setAttribute('type', 'file');
element.setAttribute('name', 'files');
uploadObj = new Uploader({
autoUpload: false, showFileList: false,
asyncSettings: {
saveUrl: 'http://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'http://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('ShowFileList', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.browseButton.getAttribute('tabindex')).toEqual('2');
});
it('Auto Upload', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 151347452, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "764.png", rawFile: "", size: 151, status: 'Ready to upload', statusCode: '1', type: 'png', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.autoUpload = true;
uploadObj.dataBind();
uploadObj.createFileList(fileList);
expect(uploadObj.uploadWrapper.querySelector('.e-file-upload-btn')).toBe(null);
});
});
describe('prevent file list keyboard navigation testing', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('uploader with disableKeyboardNavigation as false', () => {
uploadObj = new Uploader({
autoUpload: false
});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList[0].querySelector('.e-file-remove-btn').tabIndex).toEqual(0);
expect(uploadObj.actionButtons.querySelector('.e-file-clear-btn').tabIndex).toEqual(0);
expect(uploadObj.actionButtons.querySelector('.e-file-upload-btn').tabIndex).toEqual(0);
});
it('Preload files', () => {
let preLoadFiles: any = [
{name: 'ASP.Net books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({
files: preLoadFiles,
autoUpload: false
});
uploadObj.appendTo(document.getElementById('upload'));
let liElements: HTMLElement[] = uploadObj.listParent.querySelectorAll('li');
expect(liElements.length).toEqual(3);
expect(liElements[0].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[2].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[1].querySelector('.e-icons').classList.contains('e-file-delete-btn')).toBe(true);
expect(liElements[0].querySelector('.e-icons').getAttribute('title')).toEqual('Delete file');
expect(uploadObj.getFilesData()[0].name).toEqual('ASP.Net books.png');
expect(uploadObj.browseButton.getAttribute('tabindex')).toEqual('0');
expect(uploadObj.fileList[0].querySelector('.e-file-delete-btn').tabIndex).toEqual(0);
expect(uploadObj.fileList[1].querySelector('.e-file-delete-btn').tabIndex).toEqual(0);
expect(uploadObj.actionButtons.querySelector('.e-file-clear-btn').tabIndex).toEqual(0);
expect(uploadObj.actionButtons.querySelector('.e-file-upload-btn').tabIndex).toEqual(0);
});
it('Ensure button tabIndex after upload', (done) => {
uploadObj = new Uploader({
showFileList: true,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}
});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList[0].querySelector('.e-file-remove-btn').tabIndex).toEqual(0);
expect(uploadObj.getFilesData().length).toEqual(1);
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[0].statusCode).toBe('2');
expect(uploadObj.fileList[0].querySelector('.e-icons').tabIndex).toEqual(0);
done();
}, 3000)
});
});
describe('preload file testing', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('files with autoUpload', () => {
let preLoadFiles: any = [
{name: 'ASP.Net books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({ files: preLoadFiles });
uploadObj.appendTo(document.getElementById('upload'));
let liElements: HTMLElement[] = uploadObj.listParent.querySelectorAll('li');
expect(liElements.length).toEqual(3);
expect(liElements[0].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[2].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[1].querySelector('.e-icons').classList.contains('e-file-delete-btn')).toBe(true);
expect(liElements[0].querySelector('.e-icons').getAttribute('title')).toEqual('Delete file');
expect(uploadObj.getFilesData()[0].name).toEqual('ASP.Net books.png');
expect(uploadObj.browseButton.getAttribute('tabindex')).toEqual('0');
});
it('Dynamically update files without autoUpload', () => {
let preLoadFiles: any = [
{name: 'Books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({autoUpload: false});
uploadObj.appendTo('#upload');
expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
uploadObj.files = preLoadFiles;
uploadObj.dataBind();
let liElements: HTMLElement[] = uploadObj.listParent.querySelectorAll('li');
expect(liElements.length).toEqual(3);
expect(liElements[0].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[2].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[1].querySelector('.e-icons').classList.contains('e-file-delete-btn')).toBe(true);
});
it('preload files in single file upload', () => {
let preLoadFiles: any = [
{name: 'Books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({ autoUpload: false, multiple: false });
uploadObj.appendTo('#upload');
expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
uploadObj.files = preLoadFiles;
uploadObj.dataBind();
let liElements: HTMLElement[] = uploadObj.listParent.querySelectorAll('li');
expect(liElements.length).toEqual(1);
expect(liElements[0].querySelector('.e-file-name').textContent).toEqual('Books');
expect(liElements[0].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[0].querySelector('.e-file-status').textContent).toEqual('File uploaded successfully');
expect(liElements[0].querySelector('.e-icons').classList.contains('e-file-delete-btn')).toBe(true);
});
})
describe('preload file testing within form', () => {
let uploadObj: any;
beforeEach((): void => {
let form: Element = createElement('form', {attrs: {id: 'form1'}})
let element: HTMLElement = createElement('input', {id: 'upload'});
form.appendChild(element);
document.body.appendChild(form);
element.setAttribute('type', 'file');
})
afterEach((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('files with autoUpload false', () => {
let preLoadFiles: any = [
{name: 'ASP.Net books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({ files: preLoadFiles,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
},
autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
expect(isNullOrUndefined(uploadObj.uploadWrapper.querySelector('.e-file-upload-btn'))).toBe(false);
expect(isNullOrUndefined(uploadObj.uploadWrapper.querySelector('.e-file-upload-btn').getAttribute('disabled'))).toBe(false);
});
})
describe('preload file testing within form', () => {
let uploadObj: any;
beforeEach((): void => {
let form: Element = createElement('form', {attrs: {id: 'form1'}})
let element: HTMLElement = createElement('input', {id: 'upload'});
form.appendChild(element);
document.body.appendChild(form);
element.setAttribute('type', 'file');
})
afterEach((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('files with autoUpload', () => {
let preLoadFiles: any = [
{name: 'ASP.Net books', size: 500, type: '.png'},
{name: 'Movies', size: 12000, type: '.pdf'},
{name: 'Study materials', size: 500000, type: '.docx'},
];
uploadObj = new Uploader({ files: preLoadFiles });
uploadObj.appendTo(document.getElementById('upload'));
expect(isNullOrUndefined(uploadObj.uploadWrapper.querySelector('.e-file-upload-btn'))).toBe(true);
});
})
describe('cssClass Api testing', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
});
afterEach((): void => {
document.body.innerHTML = '';
});
it('cssClass testing single class', () => {
uploadObj = new Uploader({cssClass: 'class1'}, '#upload');
expect(uploadObj.uploadWrapper.classList.contains('class1')).toEqual(true);
});
it('cssClass separated by comma', () => {
uploadObj = new Uploader({cssClass: 'class1,class2'}, '#upload');
expect(uploadObj.uploadWrapper.classList.contains('class1')).toEqual(true);
expect(uploadObj.uploadWrapper.classList.contains('class2')).toEqual(true);
});
})
describe('cssClass Api testing with null and undefined', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
});
afterEach((): void => {
document.body.innerHTML = '';
});
it('cssClass testing initial null', () => {
uploadObj = new Uploader({cssClass: null}, '#upload');
expect(uploadObj.uploadWrapper.classList.length).toEqual(4);
});
it('cssClass testing initial undefined', () => {
uploadObj = new Uploader({cssClass: undefined}, '#upload');
expect(uploadObj.uploadWrapper.classList.length).toEqual(4);
});
});
describe('cssClass Api', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({cssClass: 'class1 class2' }, '#upload');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('cssClass testing multiclass', () => {
expect(uploadObj.uploadWrapper.classList.contains('class1')).toEqual(true);
expect(uploadObj.uploadWrapper.classList.contains('class2')).toEqual(true);
});
it('cssClass testing undefined', () => {
let length=uploadObj.uploadWrapper.classList.length;
uploadObj.cssClass = undefined;
expect(uploadObj.uploadWrapper.classList.length).toBe(length);
});
it('cssClass testing null check', () => {
let length=uploadObj.uploadWrapper.classList.length;
uploadObj.cssClass = null;
expect(uploadObj.uploadWrapper.classList.length).toBe(length);
});
})
describe('onProperty changes ', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('buttons text change ', () => {
uploadObj.buttons = {browse: 'Choose File', clear:'', upload: 'Load File'};
uploadObj.dataBind();
expect(uploadObj.buttons.browse).toBe('Choose File');
expect(uploadObj.buttons.upload).toBe('Load File');
expect(uploadObj.buttons.clear).toBe('');
});
it('enabled false ', () => {
let fileObj1: File = new File(["2nd File"], "image.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.enabled = false;
uploadObj.dataBind();
uploadObj.onSelectFiles();
expect(uploadObj.enabled).toBe(false);
expect(uploadObj.element.hasAttribute('disabled')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
});
it('enabled true ', () => {
uploadObj.enabled = true;
uploadObj.dataBind();
expect(uploadObj.enabled).toBe(true);
expect(uploadObj.element.hasAttribute('disabled')).toBe(false);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(false);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(false);
});
it('single file upload ', () => {
uploadObj.multiple = false;
uploadObj.dataBind();
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "image.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(1);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
});
it('upload method with single file upload ', (done) => {
uploadObj.progressInterval = '1';
uploadObj.dataBind();
uploadObj.upload([uploadObj.filesData[0]]);
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(1);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
done();
}, 1500);
});
it('upload method with single file without array type ', (done) => {
uploadObj.progressInterval = '1';
uploadObj.dataBind();
uploadObj.upload(uploadObj.filesData[0]);
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(1);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
done();
}, 1500);
});
it('upload method with single file without array type ', (done) => {
uploadObj.progressInterval = '1';
uploadObj.dataBind();
uploadObj.upload(uploadObj.filesData[0]);
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(1);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
done();
}, 1500);
});
it('upload method with multiple file upload ', (done) => {
uploadObj.asyncSettings = { saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save' };
uploadObj.upload([uploadObj.filesData[0]]);
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(1);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
done();
}, 1500);
});
it('rtl support enabled', () => {
let previousButton: boolean = isNullOrUndefined(uploadObj.actionButtons);
uploadObj.enableRtl = true;
uploadObj.dataBind();
expect(isNullOrUndefined(uploadObj.actionButtons)).toBe(previousButton);
expect(uploadObj.enableRtl).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('e-rtl')).toBe(true);
});
it('rtl support disabled', () => {
let previousButton: boolean = isNullOrUndefined(uploadObj.actionButtons);
uploadObj.enableRtl = false;
uploadObj.dataBind();
expect(uploadObj.enableRtl).toBe(false);
expect(isNullOrUndefined(uploadObj.actionButtons)).toBe(previousButton);
expect(uploadObj.uploadWrapper.classList.contains('e-rtl')).toBe(false);
});
it('enable auto upload ', () => {
uploadObj.autoUpload = true;
uploadObj.dataBind();
expect(uploadObj.autoUpload).toBe(true);
});
it('auto upload false ', () => {
uploadObj.autoUpload = false;
uploadObj.dataBind();
expect(uploadObj.autoUpload).toBe(false);
});
it('drop area set value ', () => {
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj.dropArea = document.getElementById('dropele');
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
});
it('drop area set null ', () => {
uploadObj.dropArea = null;
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
});
it('set allowed extensions ', () => {
uploadObj.allowedExtensions = '.pdf';
uploadObj.dataBind();
expect(uploadObj.allowedExtensions).toBe('.pdf');
expect(uploadObj.element.getAttribute('accept')).toEqual('.pdf');
});
it('set empty string to allowed extensions ', () => {
uploadObj.allowedExtensions = '';
uploadObj.dataBind();
expect(uploadObj.allowedExtensions).toBe('');
expect(uploadObj.element.getAttribute('accept')).toEqual(null);
});
it('set min file size ', () => {
uploadObj.minFileSize = 20000;
uploadObj.dataBind();
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 200, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
let message : any = uploadObj.validatedFileSize(200);
expect(message.minSize).toEqual('File size is too small');
});
it('set max file size ', () => {
uploadObj.maxFileSize = 20000000;
uploadObj.dataBind();
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 1500000000, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
let message : any = uploadObj.validatedFileSize(1500000000);
expect(message.maxSize).toEqual('File size is too large');
});
it('multiple file upload ', () => {
uploadObj.multiple = true;
uploadObj.dataBind();
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "image.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(2);
expect(uploadObj.element.hasAttribute('multiple')).toBe(true);
});
it('change the save and remove urls ', () => {
uploadObj.asyncSettings = { saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save', removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'};
uploadObj.dataBind();
expect(uploadObj.asyncSettings.saveUrl).toEqual('https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save');
expect(uploadObj.asyncSettings.removeUrl).toEqual('https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove');
});
it('change DirectoryUpload property ', () => {
uploadObj.directoryUpload = true;
uploadObj.dataBind();
expect(uploadObj.element.hasAttribute('directory')).toBe(true);
expect(uploadObj.element.hasAttribute('webkitdirectory')).toBe(true);
});
});
describe('destroy method', () => {
let uploadObj: any;
let uploadele: HTMLElement;
beforeEach((): void => {
uploadele = createElement('input', {id: 'upload'});
document.body.appendChild(uploadele);
uploadele.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('destroy uploader', () => {
uploadObj = new Uploader();
uploadObj.appendTo(uploadele);
expect(uploadele.classList.contains('e-control')).toBe(true);
expect(uploadele.classList.contains('e-uploader')).toBe(true);
uploadObj.destroy();
expect(uploadele.classList.contains('e-control')).toBe(false);
expect(uploadele.classList.contains('e-uploader')).toBe(false);
expect(uploadele.hasAttribute('multiple')).toBe(false);
});
it('set multiple at initial', () => {
let multiple: Attr = document.createAttribute('multiple');
uploadele.setAttributeNode(multiple);
uploadObj = new Uploader();
uploadObj.appendTo(uploadele);
expect(uploadele.classList.contains('e-uploader')).toBe(true);
expect(uploadele.hasAttribute('multiple')).toBe(true);
uploadObj.destroy();
expect(uploadele.hasAttribute('multiple')).toBe(true);
expect(uploadele.classList.contains('e-uploader')).toBe(false);
});
it('with initial attributes', () => {
uploadele.setAttribute('disabled', 'disabled');
uploadele.setAttribute('accept', '.png');
uploadObj = new Uploader();
uploadObj.appendTo(uploadele);
expect(uploadele.classList.contains('e-uploader')).toBe(true);
expect(uploadObj.multiple).toBe(true);
expect(uploadObj.allowedExtensions).toEqual('.png');
expect(uploadObj.enabled).toEqual(false);
uploadObj.destroy();
expect(uploadele.hasAttribute('multiple')).toBe(false);
expect(uploadele.hasAttribute('accept')).toBe(true);
expect(uploadele.hasAttribute('disabled')).toBe(true);
expect(uploadele.classList.contains('e-uploader')).toBe(false);
})
})
describe('Angular tag', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('div', { id: 'parentEle' });
element.innerHTML = "<ejs-uploader id='ngUploader'></ejs-uploader>";
document.body.appendChild(element);
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('Initial rendering', () => {
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('ngUploader'));
expect(uploadObj.uploadWrapper.classList.contains('e-upload')).toBe(true);
expect(uploadObj.uploadWrapper.parentElement.tagName).toBe('EJS-UPLOADER');
expect(uploadObj.element.hasAttribute('type')).toBe(true);
expect(uploadObj.element.getAttribute('type')).toBe('file');
});
})
describe('dropArea testing', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('dropArea as other then parent element', () => {
uploadObj = new Uploader({autoUpload: false, dropArea: document.getElementById('dropele') });
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
});
it('dropArea as parent element', () => {
let element1: HTMLElement = createElement('input', {id: 'upload1'});
document.getElementById('dropele').appendChild(element1);
element1.setAttribute('type', 'file');
uploadObj = new Uploader({autoUpload: false, dropArea: document.getElementById('dropele') });
uploadObj.appendTo(document.getElementById('upload1'));
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop').textContent).toBe('Or drop files here');
});
it('drag enter ', () => {
let dragEventArgs: any = { preventDefault: (): void => {}, action: null, target: null, stopPropagation: (): void => {}, };
uploadObj.onDragEnter(dragEventArgs);
expect(uploadObj.dropZoneElement.classList.contains('e-upload-drag-hover')).toBe(true);
})
it('drag leave ', () => {
uploadObj.onDragLeave();
expect(uploadObj.dropZoneElement.classList.contains('e-upload-drag-hover')).toBe(false);
});
})
describe('Interactions', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('default button text', () => {
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.localizedTexts('Browse')).toBe('Browse...');
expect(uploadObj.localizedTexts('Upload')).toBe('Upload');
expect(uploadObj.localizedTexts('Clear')).toBe('Clear');
});
it('buttons with text', () => {
uploadObj = new Uploader({autoUpload: false, buttons: {browse: 'Choose File', clear:'', upload: 'Load File'}});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["demo file"], "first.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.buttons.browse).toBe('Choose File');
expect(uploadObj.browseButton.innerText).toBe('Choose File');
uploadObj.buttons.browse = 'Browse any file';
uploadObj.dataBind();
expect(uploadObj.buttons.browse).toBe('Browse any file');
expect(uploadObj.browseButton.innerText).toBe('Browse any file');
expect(uploadObj.buttons.upload).toBe('Load File');
expect(uploadObj.uploadButton.innerText).toBe('Load File');
uploadObj.buttons.upload = 'Upload Files';
uploadObj.dataBind();
expect(uploadObj.buttons.upload).toBe('Upload Files');
expect(uploadObj.uploadButton.innerText).toBe('Upload Files');
expect(uploadObj.clearButton.innerText).toBe('');
expect(uploadObj.buttons.clear).toBe('');
uploadObj.buttons.clear = 'Clear Files';
uploadObj.dataBind();
expect(uploadObj.buttons.clear).toBe('Clear Files');
expect(uploadObj.clearButton.innerText).toBe('Clear Files');
});
it('buttons with HTMLElements', (done) => {
let item1 = createElement('span', { id: 'item1', className: 'select'});
document.body.appendChild(item1);
let item2 = createElement('span', { id: 'item2', className: 'load'});
document.body.appendChild(item2);
let item3 = createElement('span', { id: 'item3', className: 'clear'});
document.body.appendChild(item3);
uploadObj = new Uploader({autoUpload: false, buttons: {
browse: document.getElementById('item1'),
clear:document.getElementById('item3'),
upload: document.getElementById('item2')},
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.buttons.browse.classList.contains('select')).toBe(true);
expect(uploadObj.buttons.upload.classList.contains('load')).toBe(true);
expect(uploadObj.buttons.clear.classList.contains('clear')).toBe(true);
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.browseButtonClick();
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).not.toBe('Ready to upload');
expect(uploadObj.filesData[0].statusCode).not.toBe('1');
done();
}, 1500)
});
it('enable multiple at initial rendering', () => {
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(true);
expect(uploadObj.element.hasAttribute('multiple')).toBe(true);
uploadObj.setMultipleSelection();
expect(uploadObj.element.hasAttribute('multiple')).toBe(true);
})
it('disable multiple at initial rendering', () => {
uploadObj = new Uploader({autoUpload: false, multiple: false });
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(false);
expect(uploadObj.element.hasAttribute('multiple')).toBe(false);
});
it('name truncate', () => {
let element: HTMLElement = createElement('div', {id:'name'});
element.textContent = 'ChatLog 190841 _ Incident 188885 is not closed_ The drop down selected value is not selected_ 2017_11_16 15_34.rtf';
let parentElement: HTMLElement = createElement('div', {id:'Parentname'});
parentElement.style.width = '250px';
parentElement.style.overflow = 'hidden';
parentElement.style.textOverflow = 'ellipsis';
parentElement.style.whiteSpace = 'nowrap';
parentElement.appendChild(element);
document.body.appendChild(parentElement);
document.body.style.width = '500px';
uploadObj.truncateName(element);
expect(element.hasAttribute('data-tail')).toBe(true);
})
});
describe('sorting', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader();
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('sorting drop files', () => {
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "image.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.listParent.children[0].querySelector('.e-file-name').textContent).toBe('last');
});
it('2nd time drop files for sorting', () => {
let fileObj: File = new File(["example"], "awesews.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["demos"], "first.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.listParent.children[0].querySelector('.e-file-name').textContent).toBe('last');
expect(uploadObj.listParent.children[3].querySelector('.e-file-name').textContent).toBe('first');
});
})
describe('Events', () => {
let uploadObj: any;
let select: EmitType<Object> = jasmine.createSpy('selected');
let clear: EmitType<Object> = jasmine.createSpy('clearing');
let remove: EmitType<Object> = jasmine.createSpy('removing');
let onfileListRendering: EmitType<Object> = jasmine.createSpy('fileListRendering');
let originalTimeout: number;
beforeAll((): void => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
selected: select, multiple: true, clearing: clear, removing: remove, fileListRendering: onfileListRendering, autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Selected event trigger', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(select).toHaveBeenCalled();
expect(uploadObj.fileList.length).toEqual(2);
});
it('Clear event triggered', () => {
uploadObj.clearAll();
expect(clear).toHaveBeenCalled();
expect(uploadObj.fileList.length).toEqual(0);
});
it('Remove the selected files ', () => {
let fileObj: File = new File(["Nice One"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "image.png", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let removeEventArgs = { type: 'click', target: (uploadObj.fileList[0]).children[1], preventDefault: (): void => { } };
uploadObj.removeFiles(removeEventArgs);
expect(remove).toHaveBeenCalled();
expect(uploadObj.fileList.length).toEqual(1);
expect(uploadObj.filesData.length).toEqual(1);
});
it('Rendering event triggered', function () {
var fileObj = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
expect(onfileListRendering).toHaveBeenCalled();
uploadObj.onSelectFiles(eventArgs);
});
});
describe('Check spinner hided after upload canceled', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('Cancel uploading', function (done) {
var item1 = createElement('span', { id: 'item1', className: 'cancel' });
document.body.appendChild(item1);
uploadObj = new Uploader({ autoUpload: false, buttons: {
browse: document.getElementById('item1') },
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
},
uploading: function(e: any) { e.cancel = true }
});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.buttons.browse.classList.contains('cancel')).toBe(true);
var fileObj = new File(["Nice One"], "last.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.browseButtonClick();
uploadObj.uploadButtonClick();
setTimeout(function () {
expect(uploadObj.getFilesData()[0].statusCode).toBe('5');
done();
}, 1500);
});
});
describe('Event canceling ', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('Selected event canceled', () => {
uploadObj = new Uploader({ selected: function(e: any) {
e.cancel = true
} });
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.listParent).toBe(undefined);
expect(uploadObj.actionButtons).toBe(undefined);
});
it('Removing event canceled', () => {
let uploadObj1: any = new Uploader({ autoUpload: false, removing: function(e: any) {
e.cancel = true
} });
uploadObj1.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj1.onSelectFiles(eventArgs);
expect(uploadObj1.listParent).not.toBe(undefined);
expect(uploadObj1.actionButtons).not.toBe(undefined);
expect(uploadObj1.listParent.querySelectorAll('li').length).toEqual(1);
uploadObj1.remove(uploadObj1.filesData);
expect(uploadObj1.listParent).not.toBe(undefined);
expect(uploadObj1.actionButtons).not.toBe(undefined);
expect(uploadObj1.listParent.querySelectorAll('li').length).toEqual(1);
});
it('clearing event canceled', () => {
let uploadObj2: any = new Uploader({ autoUpload: false, clearing: function(e: any) {
e.cancel = true
} });
uploadObj2.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj2.onSelectFiles(eventArgs);
expect(uploadObj2.listParent).not.toBe(undefined);
expect(uploadObj2.actionButtons).not.toBe(undefined);
expect(uploadObj2.fileList.length).toBe(1);
expect(uploadObj2.filesData.length).toBe(1);
expect(uploadObj2.listParent.querySelectorAll('li').length).toEqual(1);
uploadObj2.clearAll();
expect(uploadObj2.listParent).not.toBe(undefined);
expect(uploadObj2.actionButtons).not.toBe(undefined);
expect(uploadObj2.fileList.length).toBe(1);
expect(uploadObj2.filesData.length).toBe(1);
expect(uploadObj2.listParent.querySelectorAll('li').length).toEqual(1);
});
it('Uploading event cancel', (done) => {
let uploadObj2: any = new Uploader({ uploading: function(e: any) {
e.cancel = true
} });
uploadObj2.appendTo(document.getElementById('upload'));
uploadObj2.asyncSettings = { saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save'};
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj2.onSelectFiles(eventArgs);
setTimeout(() => {
expect(uploadObj2.getFilesData()[0].statusCode).toBe('5');
done();
}, 500);
});
// it('Uploading event cancel in chunk upload', (done) => {
// let uploadObj2: any = new Uploader({ uploading: function(e: any) {
// e.cancel = true
// } });
// uploadObj2.appendTo(document.getElementById('upload'));
// uploadObj2.asyncSettings = { saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save', chunkSize: 1};
// let fileObj: File = new File(["Nice two"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj2.onSelectFiles(eventArgs);
// setTimeout(() => {
// expect(uploadObj2.getFilesData()[0].statusCode).toBe('5');
// done();
// }, 500);
// });
// it('args.cancel in cancel event', () => {
// uploadObj = new Uploader({
// multiple: true, autoUpload: false, canceling: function(e: any) {
// e.cancel = true
// },
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1, retryAfterDelay: 0 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// uploadObj.upload([uploadObj.filesData[0]]);
// // setTimeout(() => {
// // uploadObj.uploadWrapper.querySelector('.e-file-abort-btn').click();
// // setTimeout(() => {
// // expect(uploadObj.filesData[0].statusCode).not.toEqual('5');
// // let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// // expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(false);
// // done();
// // }, 500);
// // }, 50);
// });
// it('args.response in failure event', (done) => {
// uploadObj = new Uploader({
// multiple: true, asyncSettings: { saveUrl: 'js.syncfusion.comm', chunkSize: 2 },
// chunkFailure: function(args: any) {
// expect(Object.keys(args.response).length).toBe(5);
// expect(args.response.readyState).toBe(4);
// expect(args.response.headers).not.toBe("");
// expect(args.response.withCredentials).toBe(false);
// },
// failure: function(args: any) {
// expect(Object.keys(args.response).length).toBe(5);
// expect(args.response.readyState).toBe(4);
// expect(args.response.headers).not.toBe("");
// expect(args.response.withCredentials).toBe(false);
// },
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// setTimeout(() => {
// done();
// }, 1500);
// });
// it('args.response in success and progress events', (done) => {
// uploadObj = new Uploader({
// multiple: true, success: function(args: any) {
// expect(Object.keys(args.response).length).toBe(5);
// expect(args.response.readyState).toBe(4);
// expect(args.response.headers).not.toBe("");
// expect(args.response.withCredentials).toBe(false);
// },
// progress: function(args: any) {
// expect(Object.keys(args.response).length).toBe(5);
// expect(args.response.readyState).toBe(4);
// expect(args.response.headers).not.toBe("");
// expect(args.response.withCredentials).toBe(false);
// },
// chunkSuccess: function(args: any) {
// expect(Object.keys(args.response).length).toBe(5);
// expect(args.response.readyState).toBe(4);
// expect(args.response.headers).not.toBe("");
// expect(args.response.withCredentials).toBe(false);
// },
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// }
// });
// uploadObj.appendTo(document.getElementById('upload'));let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// setTimeout(() => {
// done();
// }, 1000);
// });
})
describe('Methods', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('getFileType ', () => {
let fileName: string = 'Rose.png';
let extension: string = uploadObj.getFileType(fileName);
expect(extension).toEqual('png');
});
it('checkAutoUpload ', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.checkAutoUpload(eventArgs);
expect(uploadObj.actionButtons.style.display).toBe("");
})
it('onSelectFiles ', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(2);
})
it('Clear ', () => {
uploadObj.clearAll();
expect(uploadObj.fileList.length).toEqual(0);
});
it('getFilesData ', () => {
let data = uploadObj.getFilesData();
expect(data).toEqual(uploadObj.filesData);
})
it('getPersistData method ', () => {
let stringItems: any = uploadObj.getPersistData();
expect(stringItems.length).toBe(16);
});
it('format the size in KB ', () => {
let size: string = uploadObj.bytesToSize(20000);
expect(size).toEqual('19.5 KB');
});
it('format the size in MB ', () => {
let size: string = uploadObj.bytesToSize(2000000);
expect(size).toEqual('1.9 MB');
});
it('format the 0 size file ', () => {
let size: string = uploadObj.bytesToSize(0);
expect(size).toEqual('0.0 KB');
});
it('format the large size ', () => {
let size: string = uploadObj.bytesToSize(1500000000);
expect(size).toEqual('1430.5 MB');
});
it('remove the uploaded files', () => {
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let selectEventArgs: any = { preventDefault: (): void => {}, target: {files: [fileObj]}, type: 'click', stopPropagation:(): void => {} };
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, statusCode: '2', status: 'File uploaded successfully', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.uploadedFilesData.push(fileList);
uploadObj.selected = function (args: any) {
args.isModified = true,
args.modifiedFilesData = fileList,
args.progressInterval = '30'
}
uploadObj.asyncSettings = { removeUrl: 'js.syncfusion.comm' };
uploadObj.dataBind();
uploadObj.onSelectFiles(selectEventArgs);
expect(uploadObj.listParent.children[0].querySelector('.e-file-status').textContent).toBe('File uploaded successfully');
expect(uploadObj.uploadedFilesData.length).toBe(1);
createSpinner({target: uploadObj.uploadWrapper.querySelector('.e-file-delete-btn') as HTMLElement});
showSpinner(uploadObj.uploadWrapper.querySelector('.e-file-delete-btn') as HTMLElement);
uploadObj.remove(fileList);
// setTimeout(() => {
// expect(uploadObj.uploadedFilesData.length).toBe(0);
// expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
// done();
// }, 1500);
})
});
describe('Localization', () => {
let uploadObj: any;
beforeAll((): void => {
L10n.load({
'fr-BE': {
'uploader' : {
'Browse' : 'Feuilleter',
'Clear' : 'clair',
'Upload' : 'télécharger',
'dropFilesHint' : 'ou Déposez les fichiers ici',
'readyToUploadMessage' : 'Prêt à télécharger',
'inProgress' : 'Télécharger en cours',
'uploadFailedMessage' : 'Impossible d`importer le fichier',
'uploadSuccessMessage' : 'Fichiers chargés avec succès',
'invalidMaxFileSize' : 'La taille du fichier est trop grande',
'invalidMinFileSize' : 'La taille du fichier est trop petite',
'invalidFileType' : 'File type is not allowed'
}
}
});
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, locale: 'fr-BE', minFileSize: 15000, maxFileSize: 150000 });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Button Text', () => {
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 1513472, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
let message : any = uploadObj.validatedFileSize(1513472);
expect(message.maxSize).toEqual('La taille du fichier est trop grande');
})
});
describe('Allowed Extenstions and File size validation', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ allowedExtensions: '.html, .png', minFileSize: 1500000, maxFileSize: 150000000, enableRtl: true });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Extensions API', () => {
let ele : Element = uploadObj.element;
expect(ele.getAttribute('accept')).toEqual('.html, .png');
})
it('Min File Size', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
let message : any = uploadObj.validatedFileSize(15);
expect(message.minSize).toEqual('File size is too small');
})
it('Max File Size', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 1500000000, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
let message : any = uploadObj.validatedFileSize(1500000000);
expect(message.maxSize).toEqual('File size is too large');
})
it('Enable RTL', () => {
expect(uploadObj.uploadWrapper.classList.contains('e-rtl')).toBe(true);
})
it ('disable upload button supports', () => {
uploadObj.autoUpload = false;
uploadObj.dataBind();
let fileObj: File = new File(["Nice One"], "saple.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "dmo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.uploadButton.hasAttribute('disabled')).toBe(true);
})
it ('again enable the upload button', () => {
uploadObj.minFileSize = 0;
uploadObj.dataBind();
let fileObj1: File = new File(["2nd File"], "dmo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.uploadButton.hasAttribute('disabled')).toBe(true);
uploadObj.destroy();
})
})
describe('File List Template UI', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
let item1 = createElement('span', { id: 'item1', className: 'select', innerHTML: "Select"});
document.body.appendChild(item1);
let item2 = createElement('span', { id: 'item2', className: 'load', innerHTML: 'Load'});
document.body.appendChild(item2);
let item3 = createElement('span', { id: 'item3', className: 'clear', innerHTML: 'Clear Data'});
document.body.appendChild(item3);
uploadObj = new Uploader({
buttons: {
browse: document.getElementById('item1'),
upload: document.getElementById('item2'),
clear: document.getElementById('item3'),
},
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>"
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Initial template support', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
expect(uploadObj.uploadWrapper.querySelector('li').querySelector('.file-name').textContent).toEqual('7z938-x64.msi');
expect(uploadObj.uploadWrapper.querySelector('li').querySelector('.file-size').textContent).toEqual('15 bytes');
});
it('template with file rendering ', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(3);
uploadObj.upload(uploadObj.filesData[0]);
});
it('Template changed dynamically', () => {
uploadObj.template = "<span class='wrapper'></span><span class='icon file-icon ${type}'></span><span class='name file-name'>${name}</span>"
uploadObj.dataBind();
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toBe(1);
//expect(uploadObj.listParent.querySelector('li').children.length).toBe(3);
})
it ('uploadFailed method', () => {
let fileObj: File = new File(["Nicee1"], "ChatLog 192680_Dropdown value property binding is not working in case the dropdown contains large number.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let uploadEventArgs = { type: 'click', target: (uploadObj.fileList[0]), preventDefault: (): void => { } };
uploadObj.uploadFailed(uploadEventArgs, uploadObj.filesData[1]);
expect(uploadObj.filesData[1].status).toEqual('File failed to upload');
});
})
describe('File List Template UI with ID', () => {
let uploadObj: any;
beforeAll((): void => {
let template: Element = createElement('div', { id: 'template' });
template.innerHTML = "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span><span class='e-file-delete-btn e-spinner-pane' style='display:block;height:30px; width: 30px;'></span></td></tr></tbody></table></div>";
document.body.appendChild(template);
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ template: "#template" });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Template support with ID', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
expect(uploadObj.uploadWrapper.querySelector('li').querySelector('.file-name').textContent).toEqual('7z938-x64.msi');
expect(uploadObj.uploadWrapper.querySelector('li').querySelector('.file-size').textContent).toEqual('15 bytes');
})
it ('customTemplate with uploader', () => {
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg: any = { type: 'click', target: {files: [ fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
let length: number = uploadObj.filesData.length;
uploadObj.removeFilesData(uploadObj.filesData[0], true);
expect(uploadObj.filesData.length).toBe(length);
let event = { type: 'click', target: {files: [uploadObj.filesData[0]]}, preventDefault: (): void => { } };
createSpinner({target: uploadObj.uploadWrapper.querySelector('.e-file-delete-btn')});
showSpinner(uploadObj.uploadWrapper.querySelector('.e-file-delete-btn'));
expect(isNullOrUndefined(uploadObj.uploadWrapper.querySelector('.e-spinner-pane'))).toBe(false);
});
it ('FilesData value when enabling showFileList', () => {
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg: any = { type: 'click', target: {files: [ fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
let length: number = uploadObj.filesData.length;
uploadObj.removeFilesData(uploadObj.filesData[0], true);
expect(uploadObj.filesData.length).toBe(length);
let event = { type: 'click', target: {files: [uploadObj.filesData[0]]}, preventDefault: (): void => { } };
createSpinner({target: uploadObj.uploadWrapper.querySelector('.e-file-delete-btn')});
showSpinner(uploadObj.uploadWrapper.querySelector('.e-file-delete-btn'));
expect(isNullOrUndefined(uploadObj.uploadWrapper.querySelector('.e-spinner-pane'))).toBe(false);
});
})
describe('File List Template UI with ID', () => {
let uploadObj: any;
beforeAll((): void => {
let template: Element = createElement('div', { id: 'template' });
template.innerHTML = "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span><span class='e-file-delete-btn e-spinner-pane' style='display:block;height:30px; width: 30px;'></span></td></tr></tbody></table></div>";
document.body.appendChild(template);
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ showFileList: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it ('FilesData value when enabling showFileList', () => {
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg: any = { type: 'click', target: {files: [ fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
let length: number = uploadObj.filesData.length;
expect(uploadObj.filesData.length).toBe(1);
uploadObj.removeFilesData(uploadObj.filesData[0], true);
expect(uploadObj.filesData.length).toBe(0);
});
})
describe('Disable', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, enabled: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Control Disable State', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.element.hasAttribute('disabled')).toBe(true);
})
it('Control Disable with remove files method', () => {
expect(uploadObj.listParent.querySelectorAll('li').length).toEqual(1);
let removeEventArgs = { type: 'click', target: (uploadObj.fileList[0]).children[1], preventDefault: (): void => { } };
uploadObj.removeFiles(removeEventArgs);
expect(uploadObj.listParent.querySelectorAll('li').length).toEqual(1);
})
it('Control Disable with drag enter', () => {
let dragEventArgs: any = { preventDefault: (): void => {}, action: null, target: null, stopPropagation: (): void => {}, };
uploadObj.onDragEnter(dragEventArgs);
expect(uploadObj.dropZoneElement.classList.contains('e-upload-drag-hover')).toBe(false);
})
})
describe('Enable', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Control enable state', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(false);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(false);
expect(uploadObj.element.hasAttribute('disabled')).toBe(false);
})
})
describe('KeyBoard Navigation', () => {
let uploadObj: any;
let keyboardEventArgs: any = {
preventDefault: (): void => {},
action: null,
target: null,
stopImmediatePropagation: (): void => {},
stopPropagation: (): void => {},
};
let iconElement : any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('set focus to browse button', () => {
expect(document.activeElement).not.toBe(uploadObj.browseButton);
uploadObj.browseButton.focus();
expect(document.activeElement).toBe(uploadObj.browseButton);
});
it('upload files to upload', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "default.html", rawFile: "", size:185675, status: 'Ready to upload', statusCode: '1', type: 'html', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.renderActionButtons();
uploadObj.filesData = fileList;
iconElement = uploadObj.listParent.querySelectorAll('.e-icons');
uploadObj.uploadButton.focus();
expect(document.activeElement).toBe(uploadObj.uploadButton);
});
it('enter key with upload button', () => {
keyboardEventArgs.action = 'enter';
keyboardEventArgs.target = uploadObj.uploadButton;
expect(iconElement[0].classList.contains('e-file-delete-btn')).toBe(false);
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// expect(iconElement[0].classList.contains('e-file-delete-btn')).toBe(true);
// expect(iconElement[1].classList.contains('e-file-delete-btn')).toBe(true);
// done();
// }, 3000);
})
it('enter key on clear button ', () => {
keyboardEventArgs.action = 'enter';
keyboardEventArgs.target = uploadObj.clearButton;
uploadObj.keyActionHandler(keyboardEventArgs);
expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
expect(isNullOrUndefined(uploadObj.actionButtons)).toBe(true);
});
it('set focus to clear button', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "default.html", rawFile: "", size:185675, status: 'Ready to upload', statusCode: '1', type: 'html', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.renderActionButtons();
uploadObj.filesData = fileList;
uploadObj.clearButton.focus();
expect(document.activeElement).toBe(uploadObj.clearButton);
});
it('Enter key with clear icon ', () => {
keyboardEventArgs.action = 'enter';
keyboardEventArgs.target = uploadObj.fileList[1].querySelector('.e-icons');
uploadObj.fileList[1].querySelector('.e-icons').focus();
uploadObj.keyActionHandler(keyboardEventArgs);
iconElement = uploadObj.listParent.querySelectorAll('.e-icons');
expect(iconElement.length).toBe(1);
expect(document.activeElement).toBe(uploadObj.browseButton);
});
it('set focus to upload button ', () => {
uploadObj.uploadButton.focus();
expect(document.activeElement).toBe(uploadObj.uploadButton);
});
it('Enter key with browse button ', () => {
uploadObj.browseButton.focus();
expect(document.activeElement).toBe(uploadObj.browseButton);
keyboardEventArgs.action = 'enter';
keyboardEventArgs.target = uploadObj.browseButton;
uploadObj.keyActionHandler(keyboardEventArgs);
expect(document.activeElement).toBe(uploadObj.browseButton);
});
})
describe('worst case testing', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, showFileList: false, allowedExtensions: '.pdf', multiple: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('bind drop events', () => {
uploadObj.dropZoneElement = null;
uploadObj.bindDropEvents();
uploadObj.unBindDropEvents();
expect(isNullOrUndefined(uploadObj.dropZoneElement)).toBe(true);
});
it('set rtl before list creation', () => {
uploadObj.enableRtl = true;
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.classList.contains('e-rtl')).toBe(true);
expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
});
it('clear the data before list creation', () => {
uploadObj.clearData();
expect(isNullOrUndefined(uploadObj.listParent)).toBe(true);
expect(isNullOrUndefined(uploadObj.actionButtons)).toBe(true);
});
it('get file type when there is no extension in file', () => {
let extension: string = uploadObj.getFileType('spelling');
expect(extension).toEqual('');
});
it ('null file object', () => {
let fileObj: any = { name: 'Image'}
uploadObj.uploadWrapper = null;
expect(isNullOrUndefined(uploadObj.removeFilesData(fileObj))).toBe(true);
});
it ('with custom UI', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'File upload successfully', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}]
uploadObj.asyncSettings = { saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save'};
uploadObj.upload(fileList, true);
expect(fileList[0].status).toBe('File upload successfully');
});
it ('undefined template', () => {
let template = null;
let compiledString = uploadObj.templateComplier(template);
expect(isUndefined(compiledString)).toBe(true);
});
it ('uploadRetry method', () => {
uploadObj.showFileList = true;
uploadObj.multiple = true;
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["One"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
uploadObj.pauseButton = uploadObj.fileList[1];
uploadObj.retry(uploadObj.filesData[0], true);
expect(uploadObj.filesData[0].statusCode).toBe('1');
});
it ('uploadCancel method', () => {
uploadObj.showFileList = true;
uploadObj.multiple = true;
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["One"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
uploadObj.cancel(uploadObj.filesData[0]);
expect(uploadObj.filesData[0].statusCode).toBe('0');
});
it ('uploadResume method', () => {
uploadObj.showFileList = true;
uploadObj.multiple = true;
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["One"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
uploadObj.resume(uploadObj.filesData[0]);
expect(uploadObj.filesData[0].statusCode).toBe('0');
});
it ('uploadPause method', () => {
uploadObj.showFileList = true;
uploadObj.multiple = true;
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["One"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArg = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArg);
uploadObj.pause(uploadObj.filesData[0]);
expect(uploadObj.filesData[0].statusCode).toBe('0');
});
});
describe('Default upload with', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterEach((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('cancel the request', (done) => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.upload(uploadObj.filesData);
setTimeout(() => {
expect(uploadObj.pauseButton).toBe(undefined);
let iconElement = uploadObj.fileList[0].querySelector('.e-icons');
iconElement.classList.remove('e-file-remove-btn');
iconElement.classList.add('e-file-abort-btn');
createSpinner({target:iconElement});
uploadObj.removecanceledFile(null, uploadObj.filesData[0]);
// expect(uploadObj.pauseButton).not.toBe(undefined);
done();
}, 500);
});
it('Reload the canceled file', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.pauseButton).toBe(undefined);
let iconElement = uploadObj.fileList[0].querySelector('.e-icons');
iconElement.classList.remove('e-file-remove-btn');
iconElement.classList.add('e-file-abort-btn');
createSpinner({target:iconElement});
uploadObj.removecanceledFile(null, uploadObj.filesData[0]);
expect(uploadObj.pauseButton).not.toBe(undefined);
uploadObj.reloadcanceledFile(null, uploadObj.filesData[0], uploadObj.fileList[0]);
expect(uploadObj.filesData[0].status).toBe('Ready to upload');
// setTimeout(() => {
// expect(uploadObj.filesData[0].status).toBe('File uploaded successfully');
// done();
// }, 1000);
});
it ('worst case', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.pauseButton).toBe(undefined);
let iconElement = uploadObj.fileList[0].querySelector('.e-icons');
createSpinner({target:iconElement});
uploadObj.removecanceledFile(null, uploadObj.filesData[0]);
})
});
describe('unused test cases', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, allowedExtensions: '.pdf', multiple: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it ('removeFailed method', () => {
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let removeEventArgs = { type: 'click', target: (uploadObj.fileList[0]), preventDefault: (): void => { } };
uploadObj.removeFailed(removeEventArgs, uploadObj.filesData[0]);
expect(uploadObj.listParent.querySelector('.e-file-status').textContent).toBe('Unable to remove file');
});
it ('uploadFailed method', () => {
let fileObj: File = new File(["Nice One"], "ChatLog 192680_Dropdown value property binding is not working in case the dropdown contains large number.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["2nd File"], "demo.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let uploadEventArgs = { type: 'click', target: (uploadObj.fileList[0]), preventDefault: (): void => { } };
uploadObj.template = '';
uploadObj.uploadFailed(uploadEventArgs, uploadObj.filesData[0]);
// expect(uploadObj.listParent.querySelector('.e-file-status').textContent).toEqual('File type is not allowed');
});
})
describe('Tooltip support', () => {
let uploadObj: any;
beforeAll((): void => {
L10n.load({
'fr-BE': {
'uploader' : {
'Browse' : 'Feuilleter',
'Clear' : 'clair',
'Upload' : 'télécharger',
'dropFilesHint' : 'ou Déposez les fichiers ici',
'readyToUploadMessage' : 'Prêt à télécharger',
'inProgress' : 'Télécharger en cours',
'uploadFailedMessage' : 'Impossible d`importer le fichier',
'uploadSuccessMessage' : 'Fichiers chargés avec succès',
'invalidMaxFileSize' : 'La taille du fichier est trop grande',
'invalidMinFileSize' : 'La taille du fichier est trop petite',
'invalidFileType' : 'File type is not allowed'
}
}
});
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, locale: 'fr-BE' });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Ensure title attributes', () => {
expect(uploadObj.browseButton.getAttribute('title')).toEqual('Feuilleter');
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "default.html", rawFile: "", size:185675, status: 'Ready to upload', statusCode: '1', type: 'html', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.renderActionButtons();
expect(uploadObj.uploadButton.getAttribute('title')).toEqual('télécharger');
expect(uploadObj.clearButton.getAttribute('title')).toEqual('clair');
})
})
describe('HTML5 attributes', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png', name:'images[]'}});
document.body.appendChild(element);
element.setAttribute('type', 'file');
element.setAttribute('disabled', 'disabled');
element.setAttribute('multiple', 'multiple');
uploadObj = new Uploader({ autoUpload: false, allowedExtensions: '.pdf', multiple: false });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('accept attribute', () => {
expect(uploadObj.allowedExtensions).toEqual('.pdf');
})
it('multiple selection', () => {
expect(uploadObj.multiple).toBe(false);
})
it('disabled attribute', () => {
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.enabled).toBe(false);
})
it('Change accept attr dynamically', () => {
uploadObj.allowedExtensions = 'images/*';
uploadObj.dataBind();
expect(uploadObj.element.getAttribute('accept')).toEqual('images/*');
uploadObj.allowedExtensions = 'images/jpg';
uploadObj.dataBind();
expect(uploadObj.element.getAttribute('accept')).toEqual('images/jpg');
})
})
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, asyncSettings: {saveUrl: '', removeUrl: ''} });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('name attribute', () => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.element.getAttribute('aria-label')).toEqual('Uploader');
uploadObj.resetForm();
expect(uploadObj.element.value).toEqual('');
});
it('name attribute with isModified', () => {
let fileObj: File = new File(["One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.selected = function(args: any){
args.isModified=true;
args.modifiedFilesData = [uploadObj.filesData[0]];
}
let fileObj1: File = new File(["Nice"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs1 = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs1);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.fileList.length).toEqual(1);
});
})
describe('HTML attributes at inline element testing', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png', name:'images[]'}});
document.body.appendChild(element);
element.setAttribute('disabled', 'disabled');
element.setAttribute('multiple', 'multiple');
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Inline element testing', () => {
uploadObj = new Uploader({});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.enabled).toBe(false);
})
it('Inline and API testing', () => {
uploadObj = new Uploader({multiple: false, enabled: true});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(false);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(false);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(false);
expect(uploadObj.enabled).toBe(true);
})
it('Inline and html attributes API testing', () => {
uploadObj = new Uploader({ htmlAttributes: {multiple: "false", disabled: "true"}});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(false);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.enabled).toBe(false);
})
it('Inline, API and html attributes API testing', () => {
uploadObj = new Uploader({ htmlAttributes: {multipe: "true", disabled: "true"}, multiple: false, enabled: true});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(false);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(false);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(false);
expect(uploadObj.enabled).toBe(true);
})
it('Other attribute testing with htmlAttributes API', () => {
uploadObj = new Uploader({ htmlAttributes:{ class: "test", title:"sample"}});
uploadObj.appendTo('#upload');
uploadObj.updateHTMLAttrToWrapper();
expect(uploadObj.uploadWrapper.getAttribute('title')).toBe('sample');
expect(uploadObj.uploadWrapper.classList.contains('test')).toBe(true);
});
});
describe('HTML attribute API dynamic testing', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png', name:'images[]'}});
document.body.appendChild(element);
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Dynamically change attributes with htmlAttributes API', () => {
uploadObj = new Uploader({ htmlAttributes: {multiple: "false", disabled: "true"}});
uploadObj.appendTo(document.getElementById('upload'));
expect(uploadObj.multiple).toBe(false);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.enabled).toBe(false);
uploadObj.htmlAttributes = { multiple: "true", disabled: "false"};
uploadObj.dataBind();
expect(uploadObj.multiple).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(false);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(false);
expect(uploadObj.enabled).toBe(true);
});
});
describe('HTML attribute API at inital rendering and dynamic rendering', () => {
let uploadObj: any;
beforeEach((): void => {
uploadObj = undefined;
let ele: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'upload' });
document.body.appendChild(ele);
});
afterEach((): void => {
if (uploadObj) {
uploadObj.destroy();
}
document.body.innerHTML = '';
});
it('Html attributes at initial rendering', () => {
uploadObj = new Uploader({ htmlAttributes:{class: "sample" } });
uploadObj.appendTo('#upload');
expect(uploadObj.uploadWrapper.classList.contains('sample')).toBe(true);
});
it('Pass multiple attributes dynamically', () => {
uploadObj = new Uploader({ });
uploadObj.appendTo('#upload');
uploadObj.htmlAttributes = { class:"sample", disabled: "true", style:"height:5px"};
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.classList.contains('sample')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
expect(uploadObj.uploadWrapper.getAttribute('style')).toBe('height:5px');
});
it('Pass null value in htmlAttributes', () => {
uploadObj = new Uploader({ htmlAttributes:{class: "sample" } });
uploadObj.appendTo('#upload');
uploadObj.htmlAttributes = { null: "null"};
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.classList.contains('sample')).toBe(true);
});
it('Pass undefined in htmlAttributes', () => {
uploadObj = new Uploader({htmlAttributes:{class: "sample"} });
uploadObj.appendTo('#upload');
uploadObj.htmlAttributes = { undefined: "undefined"};
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.classList.contains('sample')).toBe(true);
});
it('Pass empty value in htmlAttributes', () => {
uploadObj = new Uploader({ htmlAttributes: { disabled: "true" }});
uploadObj.appendTo('#upload');
uploadObj.htmlAttributes = {};
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.classList.contains('e-disabled')).toBe(true);
expect(uploadObj.browseButton.hasAttribute('disabled')).toBe(true);
});
});
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('without its predefined configurations for autoUpload true', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.element.getAttribute('aria-label')).toEqual('Uploader');
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
done()
});
})
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('without its predefined configurations for autoUpload false', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.element.getAttribute('aria-label')).toEqual('Uploader');
expect(uploadObj.isForm).toBe(true);
(document.getElementsByClassName('e-file-upload-btn')[0] as HTMLButtonElement).click();
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
done()
});
})
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
autoUpload: false
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('with its predefined configurations for autoUpload false', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.element.getAttribute('aria-label')).toEqual('Uploader');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
done();
});
})
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('with its predefined configurations for autoUpload true', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
expect(uploadObj.getFilesData()[0].statusCode).toBe('0');
done();
});
})
describe('Dynamic Localization update', () => {
let uploadObj: any;
beforeAll((): void => {
L10n.load({
'fr-BE': {
'uploader' : {
"invalidMinFileSize" : "La taille du fichier est trop petite! S'il vous plaît télécharger des fichiers avec une taille minimale de 10 Ko",
"invalidMaxFileSize" : "La taille du fichier dépasse 4 Mo",
"invalidFileType" : "Le type de fichier n'est pas autorisé",
"Browse" : "Feuilleter",
"Clear" : "Clair",
"Upload" : "Télécharger",
"dropFilesHint" : "ou Déposer des fichiers ici",
"uploadFailedMessage" : "Impossible d'importer le fichier",
"uploadSuccessMessage" : "Fichier téléchargé avec succès",
"removedSuccessMessage": "Fichier supprimé avec succès",
"removedFailedMessage": "Le fichier n'a pas pu être supprimé",
"inProgress": "Téléchargement",
"readyToUploadMessage": "Prêt à télécharger",
"remove": "Retirer",
"cancel": "Annuler",
"delete": "Supprimer le fichier"
}
}
});
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, maxFileSize: 4000000, minFileSize: 1000 });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('set locale through setModel', () => {
uploadObj.locale = 'fr-BE';
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 151347452, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "764.png", rawFile: "", size: 151, status: 'Ready to upload', statusCode: '1', type: 'png', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.renderActionButtons();
uploadObj.filesData = fileList;
uploadObj.dataBind();
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
let localeText : string = 'ou Déposer des fichiers ici';
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
})
it('set autoUpload true', () => {
uploadObj.locale = 'fr-BE';
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 151347452, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}},
{name: "764.png", rawFile: "", size: 151, status: 'Ready to upload', statusCode: '1', type: 'png', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.autoUpload = true;
uploadObj.filesData = fileList;
uploadObj.dataBind();
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
let localeText : string = 'ou Déposer des fichiers ici';
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
})
it('Test without filelist and file Data', () => {
uploadObj.locale = 'fr-BE';
uploadObj.filesData = [];
uploadObj.fileList = [];
uploadObj.dataBind();
expect(document.querySelector('.e-upload-files')).toBe(null);
})
});
describe('Button as Html Element in localization', () => {
let uploadObj: any;
beforeAll((): void => {
L10n.load({
'fr-BE': {
'uploader' : {
"invalidMinFileSize" : "La taille du fichier est trop petite! S'il vous plaît télécharger des fichiers avec une taille minimale de 10 Ko",
"invalidMaxFileSize" : "La taille du fichier dépasse 4 Mo",
"invalidFileType" : "Le type de fichier n'est pas autorisé",
"Browse" : "Feuilleter",
"Clear" : "Clair",
"Upload" : "Télécharger",
"dropFilesHint" : "ou Déposer des fichiers ici",
"uploadFailedMessage" : "Impossible d'importer le fichier",
"uploadSuccessMessage" : "Fichier téléchargé avec succès",
"removedSuccessMessage": "Fichier supprimé avec succès",
"removedFailedMessage": "Le fichier n'a pas pu être supprimé",
"inProgress": "Téléchargement",
"readyToUploadMessage": "Prêt à télécharger",
"remove": "Retirer",
"cancel": "Annuler",
"delete": "Supprimer le fichier"
}
}
});
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false, maxFileSize: 4000000, minFileSize: 1000 });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('set locale through with button as HTML element', () => {
let item1 = createElement('span', { id: 'item1', className: 'select'});
document.body.appendChild(item1);
let item2 = createElement('span', { id: 'item2', className: 'load'});
document.body.appendChild(item2);
let item3 = createElement('span', { id: 'item3', className: 'clear'});
document.body.appendChild(item3);
uploadObj.buttons.browse = document.getElementById('item1');
uploadObj.dataBind();
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
expect(document.getElementsByClassName('select')[0].innerHTML).not.toEqual('Feuilleter');
})
});
describe('Localization for Template support', () => {
let uploadObj: any;
beforeAll((): void => {
L10n.load({
'fr-BE': {
'uploader' : {
"invalidMinFileSize" : "La taille du fichier est trop petite! S'il vous plaît télécharger des fichiers avec une taille minimale de 10 Ko",
"invalidMaxFileSize" : "La taille du fichier dépasse 4 Mo",
"invalidFileType" : "Le type de fichier n'est pas autorisé",
"Browse" : "Feuilleter",
"Clear" : "Clair",
"Upload" : "Télécharger",
"dropFilesHint" : "ou Déposer des fichiers ici",
"uploadFailedMessage" : "Impossible d'importer le fichier",
"uploadSuccessMessage" : "Fichier téléchargé avec succès",
"removedSuccessMessage": "Fichier supprimé avec succès",
"removedFailedMessage": "Le fichier n'a pas pu être supprimé",
"inProgress": "Téléchargement",
"readyToUploadMessage": "Prêt à télécharger",
"remove": "Retirer",
"cancel": "Annuler",
"delete": "Supprimer le fichier"
}
}
});
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
uploadObj = new Uploader({ template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>" });
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Initial template support', () => {
let fileList = [{name: "7z938-x64.msi", rawFile: "", size: 15, status: 'Ready to upload', statusCode: '1', type: 'msi', validationMessages:{minsize: "", maxsize: ""}}];
uploadObj.createFileList(fileList);
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
expect(uploadObj.browseButton.innerText).toEqual('Browse...');
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe('Or drop files here');
});
})
// describe('Chunk upload support', () => {
// let uploadObj: any;
// let chunkSuccess: EmitType<Object> = jasmine.createSpy('chunkSuccess');
// let chunkFailure: EmitType<Object> = jasmine.createSpy('chunkFailure');
// let beforeChunkUpload: EmitType<Object> = jasmine.createSpy('chunkUploading');
// let originalTimeout: number;
// beforeEach((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// })
// afterEach((): void => {
// if (uploadObj.uploadWrapper) { uploadObj.destroy();}
// document.body.innerHTML = '';
// });
// it('chunk success and chunk uploading event trigger', (done) => {
// uploadObj = new Uploader({
// multiple: true, chunkSuccess: chunkSuccess, chunkUploading: beforeChunkUpload, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 4, retryAfterDelay: 100
// }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// expect(chunkSuccess).toHaveBeenCalled();
// expect(beforeChunkUpload).toHaveBeenCalled();
// done();
// }, 1500);
// });
// it('chunk failure event trigger', (done) => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: { saveUrl: 'js.syncfusion.comm', chunkSize: 4, retryAfterDelay: 100 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// expect(chunkFailure).toHaveBeenCalled();
// uploadObj.uploadWrapper.querySelector('.e-file-reload-btn').click();
// done();
// }, 1500);
// });
// it('Progressbar with worst case - remove chunk progress bar', () => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: { saveUrl: 'js.syncfusion.comm', chunkSize: 4, retryAfterDelay: 100 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// let metaData = { file: new File(["New"], "demo.txt"), chunkIndex: 0, };
// uploadObj.removeChunkProgressBar(metaData);
// expect(uploadObj.getLiElement(metaData.file)).toBe(undefined);
// uploadObj.chunkUploadInProgress(eventArgs, metaData);
// uploadObj.destroy();
// });
// it('cancel the request', () => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1, retryAfterDelay: 0 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// uploadObj.upload([uploadObj.filesData[0]]);
// // setTimeout(() => {
// // uploadObj.uploadWrapper.querySelector('.e-file-abort-btn').click();
// // setTimeout(() => {
// // expect(uploadObj.filesData[0].statusCode).toEqual('5');
// // expect(uploadObj.filesData[0].status).toEqual('File upload canceled');
// // let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// // expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(true);
// // done();
// // }, 1000);
// // }, 100);
// });
// it('Retry the canceled request', (done) => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1, retryAfterDelay: 0 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// uploadObj.uploadWrapper.querySelector('.e-file-abort-btn').click();
// setTimeout(() => {
// expect(uploadObj.filesData[0].statusCode).toEqual('5');
// expect(uploadObj.filesData[0].status).toEqual('File upload canceled');
// let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(true);
// pausebtn.click();
// setTimeout(() => {
// expect(uploadObj.filesData[0].status).not.toBe('File upload canceled');
// let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(false);
// expect(pausebtn.classList.contains('e-file-pause-btn')).toBe(true);
// done();
// }, 100);
// }, 100);
// }, 100);
// });
// it('Keyboard interaction with cancel the request', (done) => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1, retryAfterDelay: 0 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// var textContent = 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// let parts = [
// new Blob([textContent], {type: 'text/plain'}),
// new Uint16Array([33])
// ];
// // Construct a file
// let fileObj = new File(parts, 'sample.txt', {lastModified: 0, type: "overide/mimetype" });
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// let keyboardEventArgs: any = { preventDefault: (): void => {}, action: null, target: null, stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {} };
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// let abortBtn = uploadObj.uploadWrapper.querySelector('.e-file-abort-btn');
// abortBtn.focus();
// abortBtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.target = abortBtn;
// keyboardEventArgs.action = 'enter';
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// expect(uploadObj.filesData[0].statusCode).toEqual('5');
// let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(true);
// done();
// }, 800);
// }, 250);
// });
// it('Keyboard interaction with retry the canceled request', (done) => {
// uploadObj = new Uploader({
// multiple: true, chunkFailure: chunkFailure, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1, retryAfterDelay: 0 }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// let keyboardEventArgs: any = { preventDefault: (): void => {}, action: null, target: null, stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {} };
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// uploadObj.uploadWrapper.querySelector('.e-file-abort-btn').click();
// setTimeout(() => {
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('5');
// expect(uploadObj.getFilesData()[0].status).toEqual('File upload canceled');
// let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(true);
// pausebtn.focus();
// pausebtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.target = pausebtn;
// keyboardEventArgs.action = 'enter';
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// expect(uploadObj.filesData[0].status).not.toBe('File upload canceled');
// let pausebtn = uploadObj.uploadWrapper.querySelector('span.e-icons');
// expect(pausebtn.classList.contains('e-file-reload-btn')).toBe(false);
// expect(pausebtn.classList.contains('e-file-pause-btn')).toBe(true);
// done();
// }, 100);
// }, 100);
// }, 100);
// });
// })
// describe('Chunk upload KeyBoard support', () => {
// let iconElement : any;
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 3000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// })
// afterAll((): void => {
// document.body.innerHTML = '';
// });
// it('Pause and resume upload', (done) => {
// //let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
// var textContent = 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// let parts = [
// new Blob([textContent], {type: 'text/plain'}),
// new Uint16Array([33])
// ];
// // Construct a file
// let fileObj = new File(parts, 'sample.txt', {lastModified: 0, type: "overide/mimetype" });
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// let pauseBtn = uploadObj.uploadWrapper.querySelectorAll('.e-upload-file-list ')[0].querySelectorAll('.e-file-pause-btn')[0];
// expect(isNullOrUndefined(pauseBtn)).toBe(false);
// pauseBtn.focus();
// pauseBtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.action = 'enter';
// keyboardEventArgs.target = pauseBtn;
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// let playBtn = uploadObj.uploadWrapper.querySelectorAll('.e-upload-file-list ')[0].querySelectorAll('.e-file-play-btn')[0];
// expect(isNullOrUndefined(playBtn)).toBe(false);
// playBtn.focus();
// playBtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.action = 'enter';
// keyboardEventArgs.target = playBtn;
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// expect(isNullOrUndefined(pauseBtn)).toBe(false);
// done();
// }, 300);
// }, 400);
// }, 700);
// });
// })
// describe('Chunk upload Pause resume', () => {
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 3000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 5
// }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// })
// afterAll((): void => {
// uploadObj.destroy();
// document.body.innerHTML = '';
// });
// it('using UI interaction', (done) => {
// var textContent = 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// + 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
// + 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
// + 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
// + 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
// + 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
// + 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
// + 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
// + 'The uploader component is useful to upload images, documents, and other files to server.'
// let parts = [
// new Blob([textContent], {type: 'text/plain'}),
// new Uint16Array([33])
// ];
// // Construct a file
// let fileObj = new File(parts, 'sample.txt', {lastModified: 0, type: "overide/mimetype" });
// // let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// let pauseBtn: any = document.querySelector('.e-upload').querySelectorAll('.e-upload-file-list ')[0].querySelectorAll('.e-file-pause-btn')[0];
// expect(isNullOrUndefined(pauseBtn)).toBe(false);
// pauseBtn.focus();
// pauseBtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.action = 'enter';
// keyboardEventArgs.target = pauseBtn;
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// let playBtn = uploadObj.uploadWrapper.querySelectorAll('.e-upload-file-list ')[0].querySelectorAll('.e-file-play-btn')[0];
// expect(isNullOrUndefined(playBtn)).toBe(false);
// playBtn.focus();
// playBtn.classList.add('e-clear-icon-focus');
// keyboardEventArgs.action = 'enter';
// keyboardEventArgs.target = playBtn;
// uploadObj.keyActionHandler(keyboardEventArgs);
// setTimeout(() => {
// expect(isNullOrUndefined(pauseBtn)).toBe(false);
// done();
// }, 500);
// }, 500);
// }, 500);
// });
// });
// describe('Chunk upload pause & resume public methods', () => {
// let iconElement : any;
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 13000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 0.5
// },
// template: "<span class='wrapper'><span class='icon template-icons sf-icon-${type}'></span>" +
// "<span class='name file-name'>${name} ( ${size} bytes)</span><span class='upload-status'>${status}</span>" +
// "</span><span class='e-icons e-file-remove-btn' title='Remove'></span>"
// });
// })
// afterAll((): void => {
// uploadObj.destroy();
// document.body.innerHTML = '';
// });
// it('Pause, resume', (done) => {
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["pause upload"], "pauseData.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// uploadObj.pause(uploadObj.getFilesData()[0]);
// setTimeout(() => {
// //ensure the uploading is paused.
// // expect(uploadObj.getFilesData()[0].statusCode).toEqual('4');
// uploadObj.resume(uploadObj.getFilesData()[0]);
// //Reume the upload
// setTimeout(() => {
// // expect(uploadObj.getFilesData()[0].statusCode).toEqual('3');
// done();
// }, 100);
// }, 100);
// }, 200);
// });
// it('Remove the paused file', (done) => {
// let fileObj: File = new File(["remove pause"], "removePauseData.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(2);
// uploadObj.upload([uploadObj.filesData[1]]);
// setTimeout(() => {
// uploadObj.pause(uploadObj.getFilesData()[1]);
// setTimeout(() => {
// //ensure the uploading is paused.
// expect(uploadObj.getFilesData()[1].statusCode).toEqual('4');
// uploadObj.remove([uploadObj.getFilesData()[1]]);
// //Reume the upload
// setTimeout(() => {
// expect(uploadObj.fileList.length).toEqual(1);
// done();
// }, 5000);
// }, 100);
// }, 200);
// });
// });
// describe('Chunk upload pause & resume with single and multiple files its public methods', () => {
// let iconElement : any;
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// },
// template: "<span class='wrapper'><span class='icon template-icons sf-icon-${type}'></span>" +
// "<span class='name file-name'>${name} ( ${size} bytes)</span><span class='upload-status'>${status}</span>" +
// "</span><span class='e-icons e-file-remove-btn' title='Remove'></span>"
// });
// })
// afterAll((): void => {
// uploadObj.destroy();
// document.body.innerHTML = '';
// });
// it('Pause, resume', (done) => {
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["pause upload"], "pauseData.txt", {lastModified: 0, type: "overide/mimetype"});
// let fileObj1: File = new File(["pause upload file1"], "pauseData1.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(2);
// uploadObj.upload(uploadObj.filesData);
// setTimeout(() => {
// let getFileList: any = uploadObj.getFilesData()[0]
// uploadObj.pause(uploadObj.getFilesData());
// setTimeout(() => {
// //ensure the uploading is paused.
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('4');
// expect(uploadObj.getFilesData()[1].statusCode).toEqual('4');
// //Resume the upload
// setTimeout(() => {
// uploadObj.resume(uploadObj.getFilesData()[0]);
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('3');
// done();
// }, 100);
// }, 100);
// }, 200);
// });
// })
// describe('Cancel & retry public methods', () => {
// let iconElement : any;
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// })
// afterAll((): void => {
// document.body.innerHTML = '';
// });
// it('cancel, retry', (done) => {
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// },
// template: "<span class='wrapper'><span class='icon template-icons sf-icon-${type}'></span>" +
// "<span class='name file-name'>${name} ( ${size} bytes)</span><span class='upload-status'>${status}</span>" +
// "</span><span class='e-icons e-file-abort-icon' title='Remove'></span>"
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["pause upload"], "pauseData.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// uploadObj.cancel(uploadObj.getFilesData()[0]);
// setTimeout(() => {
// //expect(uploadObj.getFilesData()[0].statusCode).toEqual('5');
// //uploadObj.retry(uploadObj.getFilesData()[0], false);
// setTimeout(() => {
// //expect(uploadObj.getFilesData()[0].statusCode).toEqual('3')
// //uploadObj.cancel(uploadObj.getFilesData()[0]);
// setTimeout(() => {
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('5')
// done();
// }, 200);
// }, 50);
// }, 100);
// }, 50)
// });
// })
// describe('Cancel & retry public methods with uploading single and multiple file', () => {
// let iconElement : any;
// let uploadObj: any;
// let originalTimeout: number;
// let keyboardEventArgs: any = {
// preventDefault: (): void => {},
// action: null,
// target: null,
// stopImmediatePropagation: (): void => {},
// stopPropagation: (): void => {},
// };
// beforeAll((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 7000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// })
// afterAll((): void => {
// document.body.innerHTML = '';
// });
// it('cancel, retry', (done) => {
// uploadObj = new Uploader({
// multiple: true, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// },
// template: "<span class='wrapper'><span class='icon template-icons sf-icon-${type}'></span>" +
// "<span class='name file-name'>${name} ( ${size} bytes)</span><span class='upload-status'>${status}</span>" +
// "</span><span class='e-icons e-file-abort-icon' title='Remove'></span>"
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["pause upload"], "pauseData.txt", {lastModified: 0, type: "overide/mimetype"});
// let fileObj1: File = new File(["pause upload file1"], "pauseData1.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(2);
// uploadObj.upload(uploadObj.filesData);
// setTimeout(() => {
// uploadObj.cancel(uploadObj.getFilesData()[0]);
// setTimeout(() => {
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('5');
// uploadObj.retry(uploadObj.getFilesData()[0], false);
// setTimeout(() => {
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('3')
// uploadObj.cancel(uploadObj.getFilesData()[0]);
// setTimeout(() => {
// expect(uploadObj.getFilesData()[0].statusCode).toEqual('5')
// done();
// }, 200);
// }, 50);
// }, 100);
// }, 50)
// });
// })
describe('Uploading event ', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('canceled', () => {
uploadObj = new Uploader({ uploading: function(e: any) {
e.cancel = true
},
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
} });
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: { files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.upload([uploadObj.filesData[0]]);
expect(uploadObj.filesData[0].statusCode).toEqual('5');
});
});
describe('Uploading drop area customization ', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('change target dynamically', () => {
uploadObj = new Uploader({ });
uploadObj.appendTo(document.getElementById('upload'));
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
expect(document.querySelector('.e-file-drop').textContent).toEqual('Or drop files here');
uploadObj.dropArea = '#dropele';
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
uploadObj.dropArea = '.e-upload';
uploadObj.dataBind();
expect(document.querySelector('.e-file-drop').textContent).toEqual('Or drop files here');
});
});
describe('Disabling showFileList and checking', () => {
let uploadObj: any;
beforeEach((): void => {
let element: HTMLElement = createElement('input', {id: 'UploadFiles'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
document.body.innerHTML = '';
});
it('getFilesData method with autoUpload true', (done) => {
uploadObj = new Uploader({
showFileList: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
});
uploadObj.appendTo(document.getElementById('UploadFiles'));
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(1);
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[0].statusCode).toBe('2');
done();
}, 1500)
});
it('getFilesData method with autoUpload false', (done) => {
uploadObj = new Uploader({
showFileList: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
autoUpload: false
});
uploadObj.appendTo(document.getElementById('UploadFiles'));
let fileObj: File = new File(["Nice One"], "last.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(1);
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('Ready to upload');
expect(uploadObj.filesData[0].statusCode).toBe('1');
done();
}, 1500)
});
});
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({ autoUpload: false});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('Clearing values', () => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.getFilesData().length).toEqual(2);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
});
})
describe('Form support', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload', attrs: {accept : '.png'}});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let resetButton: HTMLElement = createElement('button',{attrs: {type: 'reset', id: 'reset'}});
form.appendChild(element);
form.appendChild(resetButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('Reset', () => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj, fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.getFilesData().length).toEqual(2);
expect(uploadObj.fileList.length).toEqual(2);
(document.querySelector('#reset') as HTMLButtonElement).click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
});
})
describe('Cancel & retry public methods for', () => {
let iconElement : any;
let uploadObj: any;
let originalTimeout: number;
let keyboardEventArgs: any = {
preventDefault: (): void => {},
action: null,
target: null,
stopImmediatePropagation: (): void => {},
stopPropagation: (): void => {},
};
beforeAll((): void => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('template UI upload', (done) => {
let callProgressEvent: boolean = true;
uploadObj = new Uploader({
multiple: true, autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
progress: function(e: any) {
if (callProgressEvent) {
uploadObj.cancel(uploadObj.getFilesData()[0]);
setTimeout(() => {
//expect(uploadObj.getFilesData()[0].statusCode).toEqual('5');
callProgressEvent = false;
uploadObj.retry(uploadObj.getFilesData()[0], false, true);
done();
setTimeout(() => {
expect(uploadObj.getFilesData()[0].statusCode).toEqual('2');
done();
}, 300);
}, 5)
}
},
template: "<span class='wrapper'><span class='icon template-icons sf-icon-${type}'></span>" +
"<span class='name file-name'>${name} ( ${size} bytes)</span><span class='upload-status'>${status}</span>" +
"</span><span class='e-icons e-file-abort-icon' title='Remove'></span>"
});
uploadObj.appendTo(document.getElementById('upload'));
var textContent = 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
let parts = [
new Blob([textContent], {type: 'text/plain'}),
new Uint16Array([1000])
];
// Construct a file
let fileObj: File = new File(parts, "BlobFile.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.upload([uploadObj.filesData[0]]);
});
})
describe('Cancel & retry public methods for', () => {
let iconElement : any;
let uploadObj: any;
let originalTimeout: number;
let keyboardEventArgs: any = {
preventDefault: (): void => {},
action: null,
target: null,
stopImmediatePropagation: (): void => {},
stopPropagation: (): void => {},
};
beforeAll((): void => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 7000;
let element: HTMLElement = createElement('input', {id: 'upload1'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('default UI upload', (done) => {
let callProgressEvent: boolean = true;
uploadObj = new Uploader({
multiple: true, autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
progress: function(e: any) {
if (callProgressEvent) {
uploadObj.cancel(uploadObj.getFilesData()[0]);
setTimeout(() => {
//expect(uploadObj.getFilesData()[0].statusCode).toEqual('5');
callProgressEvent = false;
uploadObj.retry(uploadObj.getFilesData()[0], false);
done();
setTimeout(() => {
//expect(uploadObj.getFilesData()[0].statusCode).toEqual('2');
done();
}, 200);
}, 10)
}
}
});
uploadObj.appendTo(document.getElementById('upload1'));
var textContent1 = 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
let parts1 = [
new Blob([textContent1], {type: 'text/plain'}),
new Uint16Array([1000])
];
// Construct a file
let fileObj: File = new File(parts1, "BlobFile1.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.upload([uploadObj.filesData[0]]);
});
})
describe('Sequential Upload testing on uploading', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('Dynamically enable sequential upload', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(2);
uploadObj.sequentialUpload = true;
uploadObj.dataBind();
expect(uploadObj.fileList.length).toEqual(0);
done();
});
})
describe('Sequential Upload testing with filesize', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
var textContent1 = 'The uploader component is useful to upload images, documents, and other files to server. The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
let parts1 = [
new Blob([textContent1], {type: 'text/plain'}),
new Uint16Array([33])
];
var textContent2 = 'The uploader component is useful to upload images, documents, and other files to server. The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server. The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
let parts2 = [
new Blob([textContent2], {type: 'text/plain'}),
new Uint16Array([33])
];
it('sequential upload size validation with autoupload false', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}, autoUpload: false, sequentialUpload: true,});
uploadObj.appendTo(document.getElementById('upload'));
uploadObj.minFileSize = 5000;
uploadObj.dataBind();
let fileObj: File = new File(parts1, "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(parts2, "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File size is too small');
expect(uploadObj.filesData[0].statusCode).toBe('0');
expect(uploadObj.filesData[1].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[1].statusCode).toBe('2');
done();
}, 500);
});
})
describe('Sequential Upload testing on uploading', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('sequential upload with autoupload false', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}, autoUpload: false, sequentialUpload: true,});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(2);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[0].statusCode).toBe('2');
//expect(uploadObj.filesData[1].status).toEqual('Ready to upload');
//expect(uploadObj.filesData[1].statusCode).toBe('1');
setTimeout(() => {
expect(uploadObj.filesData[1].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[1].statusCode).toBe('2');
done();
}, 300);
}, 40);
});
})
describe('Customize success message', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('upload with autoupload false', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
},
success: function (args: any) {
args.statusText = 'upload succeed';
} ,
autoUpload: false});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('upload succeed');
expect(uploadObj.filesData[0].statusCode).toBe('2');
expect(uploadObj.fileList[0].querySelector('.e-file-status').innerHTML).toBe('upload succeed');
done();
}, 800);
});
})
describe('Customize failure message', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('upload with autoupload false', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnet.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnet.syncfusion.com/services/api/uploadbox/Remove',
},
failure: function (args: any) {
args.statusText = 'upload failed'
} ,
autoUpload: false});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('upload failed');
expect(uploadObj.filesData[0].statusCode).toBe('0');
expect(uploadObj.fileList[0].querySelector('.e-file-status').innerHTML).toBe('upload failed');
done();
}, 800);
});
})
// describe('Sequential Upload testing on chunk uploading', () => {
// let uploadObj: any;
// beforeAll((): void => {
// let element: HTMLElement = createElement('input', {id: 'upload'});
// document.body.appendChild(element);
// element.setAttribute('type', 'file');
// })
// afterAll((): void => {
// uploadObj.destroy();
// document.body.innerHTML = '';
// });
// it('sequential upload with chunk upload on autoupload false', (done) => {
// uploadObj = new Uploader({ asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 1
// }, autoUpload: false, sequentialUpload: true,});
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
// let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.getFilesData().length).toEqual(2);
// uploadObj.uploadButtonClick();
// setTimeout(() => {
// expect(uploadObj.filesData[0].status).toEqual('Uploading');
// expect(uploadObj.filesData[0].statusCode).toBe('3');
// expect(uploadObj.filesData[1].status).toEqual('Ready to upload');
// expect(uploadObj.filesData[1].statusCode).toBe('1');
// done();
// }, 110);
// });
// })
describe('Sequential Upload testing on canceling', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('sequential upload with abort icon clicked', (done) => {
var textContent1 = 'The uploader component is useful to upload images, documents, and other files to server. The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server. The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
+ 'The uploader component is useful to upload images, documents, and other files to server.'
+ 'The component is the extended version of HTML5 that is uploaded with multiple file selection, auto upload, drag and drop, progress bar, preload files, and validation'
+ 'Asynchronous upload - Allows you to upload the files asynchronously. The upload process requires save and remove action URL to manage upload process in the server.'
+ 'Drag and drop - Allows you to drag files from the file explorer and drop into the drop area. By default, the uploader component act as drop area element.'
+ 'Form supports - The selected or dropped files are received as a collection in a form action when the form is submitted.'
+ 'Validation - Validates the selected file size and extension by using the allowedExtensions, maxFileSize, and minFileSize properties.'
+ 'Template - You can customize default appearance of the uploader using the template property along with the buttons property.'
+ 'Localization - Supports to localize the text content of action buttons, file status, clear icon title, tooltips, and text content of drag area.'
let parts1 = [
new Blob([textContent1], {type: 'text/plain'}),
new Uint16Array([33])
];
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}, autoUpload: false, sequentialUpload: true,});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(parts1, "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(parts1, "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(2);
uploadObj.uploadButtonClick();
setTimeout(() => {
uploadObj.cancel(uploadObj.getFilesData()[0]);
setTimeout(() =>{
//expect(uploadObj.filesData[0].status).toEqual('File upload canceled');
//expect(uploadObj.filesData[0].statusCode).toEqual('5');
expect(uploadObj.filesData[1].status).toEqual('Ready to upload');
expect(uploadObj.filesData[1].statusCode).toBe('1');
setTimeout(() => {
expect(uploadObj.filesData[1].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[1].statusCode).toBe('2');
done();
}, 900);
}, 15);
}, 5);
});
})
describe('Action complete event in uploader', () => {
let uploadObj: any;
let onComplete: EmitType<Object> = jasmine.createSpy('actionComplete');
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('action complete event on successfull upload', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}, autoUpload: false, actionComplete: onComplete});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj1: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj,fileObj1]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(2);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[0].statusCode).toBe('2');
expect(uploadObj.filesData[1].status).toEqual('File uploaded successfully');
expect(uploadObj.filesData[1].statusCode).toBe('2');
expect(onComplete).toHaveBeenCalled();
done();
}, 400);
});
})
describe('Action complete event in uploader', () => {
let uploadObj: any;
let onComplete: EmitType<Object> = jasmine.createSpy('actionComplete');
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('action complete event on upload failed', (done) => {
uploadObj = new Uploader({ asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Saved',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Removed',
}, autoUpload: false, actionComplete: onComplete});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj2: File = new File(["Nice One"], "sample1.txt", {lastModified: 0, type: "overide/mimetype"});
let fileObj3: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj2,fileObj3]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.getFilesData().length).toEqual(2);
uploadObj.uploadButtonClick();
setTimeout(() => {
expect(uploadObj.filesData[0].status).toEqual('File failed to upload');
expect(uploadObj.filesData[0].statusCode).toBe('0');
expect(uploadObj.filesData[1].status).toEqual('File failed to upload');
expect(uploadObj.filesData[1].statusCode).toBe('0');
expect(onComplete).toHaveBeenCalled();
done();
}, 400);
});
})
describe('File name truncating in uploader', () => {
let uploadObj: any;
let onComplete: EmitType<Object> = jasmine.createSpy('actionComplete');
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove'
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('name truncate', () => {
let element: HTMLElement = createElement('div', {id:'name'});
element.textContent = 'This is testing file for truncation functionality in uploader.rtf';
let parentElement: HTMLElement = createElement('div', {id:'Parentname'});
parentElement.style.width = '250px';
parentElement.style.overflow = 'hidden';
parentElement.style.textOverflow = 'ellipsis';
parentElement.style.whiteSpace = 'nowrap';
parentElement.appendChild(element);
document.body.appendChild(parentElement);
document.body.style.width = '500px';
uploadObj.truncateName(element);
expect(element.hasAttribute('data-tail')).toBe(true);
expect(element.getAttribute('data-tail')).toEqual('loader.rtf')
})
})
describe('File List Template UI for preload files', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
let preLoadFiles: any = [
{name: 'ASP.Net books', size: 500, type: 'png'},
{name: 'Movies', size: 12000, type: 'pdf'},
{name: 'Study materials', size: 500000, type: 'docx'},
];
uploadObj = new Uploader({
files: preLoadFiles,
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span><span class='upload-status'>${status}</span></td></tr></tbody></table></div>",
rendering: function (args: any) {
if(args.isPreload) {
args.element.querySelector('.upload-status').innerHTML = 'Status Customized';
}
}
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Check LI Count', (done) => {
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(3);
expect(uploadObj.uploadWrapper.querySelectorAll('li')[0].querySelector('.upload-status').innerHTML).toBe('Status Customized');
expect(uploadObj.uploadWrapper.querySelectorAll('li')[1].querySelector('.upload-status').innerHTML).toBe('Status Customized');
expect(uploadObj.uploadWrapper.querySelectorAll('li')[2].querySelector('.upload-status').innerHTML).toBe('Status Customized');
done();
}, 3000);
});
})
// describe('Form support', () => {
// let uploadObj: any;
// let SuccessCallback: EmitType<any> = jasmine.createSpy('success');
// let RemovingCallback: EmitType<any> = jasmine.createSpy('removing');
// let originalTimeout: number;
// beforeEach((): void => {
// originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
// jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
// let element: HTMLElement = createElement('input', {id: 'upload'});
// let form: HTMLElement = createElement('form', {id: 'MyForm'});
// form.appendChild(element);
// document.body.appendChild(form);
// element.setAttribute('type', 'file');
// })
// afterEach((): void => {
// if (uploadObj.uploadWrapper) { uploadObj.destroy();}
// document.body.innerHTML = '';
// });
// it('Remove uploaded file', (done) => {
// uploadObj = new Uploader({
// multiple: true, success: SuccessCallback, removing: RemovingCallback, autoUpload: false,
// asyncSettings: {
// saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
// removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
// chunkSize: 4
// }
// });
// uploadObj.appendTo(document.getElementById('upload'));
// let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
// let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
// uploadObj.onSelectFiles(eventArgs);
// expect(uploadObj.fileList.length).toEqual(1);
// uploadObj.upload([uploadObj.filesData[0]]);
// setTimeout(() => {
// uploadObj.remove([uploadObj.filesData[0]]);
// setTimeout(() => {
// expect(RemovingCallback).toHaveBeenCalledTimes(1);
// expect(SuccessCallback).toHaveBeenCalledTimes(2);
// done();
// }, 1500);
// }, 1500);
// });
// })
describe('PostRawFile in remove method argument', () => {
let uploadObj: any;
let SuccessCallback: EmitType<any> = jasmine.createSpy('success');
let RemovingCallback: EmitType<any> = jasmine.createSpy('removing');
let originalTimeout: number;
beforeEach((): void => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 6000;
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
})
afterEach((): void => {
if (uploadObj.uploadWrapper) { uploadObj.destroy();}
document.body.innerHTML = '';
});
it('Remove uploaded file', (done) => {
uploadObj = new Uploader({
multiple: true, success: SuccessCallback, removing: RemovingCallback, autoUpload: false,
asyncSettings: {
saveUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Save',
removeUrl: 'https://aspnetmvc.syncfusion.com/services/api/uploadbox/Remove',
}
});
uploadObj.appendTo(document.getElementById('upload'));
let fileObj: File = new File(["Nice One"], "sample.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.fileList.length).toEqual(1);
uploadObj.upload([uploadObj.filesData[0]]);
setTimeout(() => {
uploadObj.remove([uploadObj.filesData[0]], false, true, null, false);
setTimeout(() => {
expect(RemovingCallback).toHaveBeenCalledTimes(0);
expect(SuccessCallback).toHaveBeenCalledTimes(2);
done();
}, 1500);
}, 1500);
});
})
describe('EJ2-21915 - uploader HTML 5 validation', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
multiple: true
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Check HTML Attributes', () => {
expect(uploadObj.element.getAttribute('multiple')).toBe('multiple');
expect(uploadObj.element.getAttribute('accept')).not.toBe('');
});
})
it('memory leak testing', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(inMB(profile.samples[profile.samples.length - 1]) + 0.25);
});
describe('Render preload files as empty', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
document.body.appendChild(element);
element.setAttribute('type', 'file');
let preLoadFiles: any = [];
uploadObj = new Uploader({
files: preLoadFiles
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
document.body.innerHTML = '';
});
it('Checkx LI Count', (done) => {
setTimeout(() => {
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(0);
done();
}, 3000);
});
it('Check LI Count', () => {
uploadObj.files = [{name: 'books', size: 500, type: '.png'},
{name: 'movies', size: 12000, type: '.pdf'},
{name: 'study materials', size: 500000, type: '.docx'} ];
uploadObj.dataBind();
expect(uploadObj.uploadWrapper.querySelectorAll('li').length).toBe(3);
});
});
describe('Form support - UI changes - Single File', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].statusCode).toBe('1');
expect(uploadObj.getFilesData()[0].input.getAttribute('name')).toEqual('upload');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(false);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-status')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-information')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-size').length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(2);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Single File - RTL', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
enableRtl: true
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].statusCode).toBe('1');
expect(uploadObj.getFilesData()[0].input.getAttribute('name')).toEqual('upload');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(false);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-status')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-information')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-size').length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(2);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Single File - Invalid', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
allowedExtensions:'.pdf'
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with invalid files', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(true);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-status').length).toBe(1);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-information')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-size')).toBe(null);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Single File -Template', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>"
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].input.getAttribute('name')).toEqual('upload');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(false);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(2);
expect(uploadObj.fileList.length).toEqual(1);
expect(uploadObj.remove(uploadObj.getFilesData(0)));
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Single File -Template - invalid', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
allowedExtensions:'.pdf',
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>"
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with invalid files', (done) => {
let fileObj: File = new File(["Nice One"], "sample2.txt", {lastModified: 0, type: "overide/mimetype"});
let eventArgs = { type: 'click', target: {files: [fileObj]}, preventDefault: (): void => { } };
uploadObj.onSelectFiles(eventArgs);
let element : HTMLFormElement = <HTMLFormElement>document.getElementById("form1");
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(true);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
expect(uploadObj.fileList.length).toEqual(1);
expect(uploadObj.remove(uploadObj.getFilesData(0)));
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Multiple File - Template', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>"
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
var fileObj = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].input.getAttribute('name')).toEqual('upload');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(false);
expect(uploadObj.fileList.length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(2);
expect(uploadObj.remove(uploadObj.getFilesData(0)));
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Multiple File - Template - Invalid files', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
allowedExtensions:'.pdf',
template: "<div class='wrapper'><table><tbody><tr><td><span class='file-name'>${name}</span></td><td><span class='file-size'>${size} bytes</span></td></tr></tbody></table></div>"
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
var fileObj = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(true);
expect(uploadObj.fileList.length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
expect(uploadObj.remove(uploadObj.getFilesData(0)));
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Multiple File', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid files', (done) => {
var fileObj = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].statusCode).toBe('1');
expect(uploadObj.getFilesData()[0].input.getAttribute('name')).toEqual('upload');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(false);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-status')).toBe(null);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-information').length).toBe(1);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-size')).toBe(null);
expect(uploadObj.fileList.length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(2);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Multiple File - Invalid', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
allowedExtensions:'.pdf'
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with invalid files', (done) => {
var fileObj = new File(["Nice One"], "sample.txt", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(true);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-status').length).toBe(1);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-information').length).toBe(0);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-size')).toBe(null);
expect(uploadObj.fileList.length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('Form support - UI changes - Multiple File - Invalid /valid combination', () => {
let uploadObj: any;
beforeAll((): void => {
let element: HTMLElement = createElement('input', {id: 'upload'});
let form: Element = createElement('form', {attrs: {id: 'form1'}});
let submitButton: HTMLElement = createElement('button',{attrs: {type: 'submit'}});
form.appendChild(element);
form.appendChild(submitButton);
document.body.appendChild(form);
element.setAttribute('type', 'file');
uploadObj = new Uploader({
allowedExtensions:'.pdf'
});
uploadObj.appendTo(document.getElementById('upload'));
})
afterAll((): void => {
uploadObj.destroy();
document.body.innerHTML = '';
});
it('ensure form support UI changes with valid/invalid files', (done) => {
var fileObj = new File(["Nice One"], "sample.pdf", { lastModified: 0, type: "overide/mimetype" });
var fileObj1 = new File(["2nd File"], "demo.txt", { lastModified: 0, type: "overide/mimetype" });
var eventArgs = { type: 'click', target: { files: [fileObj, fileObj1] }, preventDefault: function () { } };
uploadObj.onSelectFiles(eventArgs);
expect(uploadObj.element.getAttribute('name')).toEqual('upload');
expect(uploadObj.isForm).toBe(true);
expect(uploadObj.element.value).toEqual('');
expect(uploadObj.getFilesData()[0].list.classList.contains('e-file-invalid')).toBe(true);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-status').length).toBe(1);
expect(uploadObj.getFilesData()[0].list.querySelectorAll('.e-file-information').length).toBe(0);
expect(uploadObj.getFilesData()[0].list.querySelector('.e-file-size')).toBe(null);
expect(uploadObj.fileList.length).toBe(1);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
uploadObj.uploadWrapper.querySelector('.e-file-remove-btn').click();
expect(uploadObj.getFilesData().length).toEqual(0);
expect(uploadObj.fileList.length).toEqual(0);
expect(uploadObj.uploadWrapper.querySelectorAll('input').length).toBe(1);
done()
});
});
describe('EJ2-36604 - While giving the class name with empty space for HtmlAttributes, console error is produced.', function () {
let uploadObj: any;
beforeEach(function () {
let inputElement: HTMLElement = createElement('input', { id: 'uploader' });
document.body.appendChild(inputElement);
});
afterEach(function () {
if (uploadObj) {
uploadObj.destroy();
document.body.innerHTML = '';
}
});
it('Entering the class name without any empty space', function () {
uploadObj = new Uploader({
htmlAttributes: { class: 'custom-class' }
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class')).toBe(true);
});
it('Giving empty space before and after the class name', function () {
uploadObj = new Uploader({
htmlAttributes: { class: ' custom-class ' }
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class')).toBe(true);
});
it('Giving more than one empty space between two class names', function () {
uploadObj = new Uploader({
htmlAttributes: { class: 'custom-class-one custom-class-two'}
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('custom-class-two')).toBe(true);
});
it('Giving more than one empty space between two class names as well before and after the class name', function () {
uploadObj = new Uploader({
htmlAttributes: { class: ' custom-class-one custom-class-two ' }
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('custom-class-two')).toBe(true);
});
it('Giving only empty space without entering any class Name', function () {
uploadObj = new Uploader({
});
uploadObj.appendTo('#uploader');
let beforeAddClass = uploadObj.uploadWrapper.classList.length;
uploadObj.htmlAttributes = { class: ' ' };
uploadObj.appendTo('#uploader');
let AfterAddClass = uploadObj.uploadWrapper.classList.length;
expect(beforeAddClass == AfterAddClass).toBe(true);
});
it('Keep input as empty without entering any class Name', function () {
uploadObj = new Uploader({
});
uploadObj.appendTo('#uploader');
let beforeAddClass = uploadObj.uploadWrapper.classList.length;
uploadObj.htmlAttributes = { class: '' };
uploadObj.appendTo('#uploader');
let AfterAddClass = uploadObj.uploadWrapper.classList.length;
expect(beforeAddClass == AfterAddClass).toBe(true);
});
it('Entering the class name without any empty space', function () {
uploadObj = new Uploader({
cssClass: 'custom-class'
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class')).toBe(true);
});
it('Giving empty space before and after the class name', function () {
uploadObj = new Uploader({
cssClass: ' custom-class '
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class')).toBe(true);
});
it('Giving more than one empty space between two class names', function () {
uploadObj = new Uploader({
cssClass: 'custom-class-one custom-class-two'
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('custom-class-two')).toBe(true);
});
it('Giving more than one empty space between two class names as well before and after the class name', function () {
uploadObj = new Uploader({
cssClass: ' custom-class-one custom-class-two '
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('custom-class-two')).toBe(true);
});
it('Keep input as empty without entering any class Name', function () {
uploadObj = new Uploader({
});
uploadObj.appendTo('#uploader');
let beforeAddClass = uploadObj.uploadWrapper.classList.length;
uploadObj.cssClass = '' ;
uploadObj.appendTo('#uploader');
let AfterAddClass = uploadObj.uploadWrapper.classList.length;
expect(beforeAddClass == AfterAddClass).toBe(true);
});
it('Keep input as empty without entering any class Name', function () {
uploadObj = new Uploader({
});
uploadObj.appendTo('#uploader');
let beforeAddClass = uploadObj.uploadWrapper.classList.length;
uploadObj.cssClass = ' ' ;
uploadObj.appendTo('#uploader');
let AfterAddClass = uploadObj.uploadWrapper.classList.length;
expect(beforeAddClass == AfterAddClass).toBe(true);
});
it('Giving class name with underscore in the beginning', function () {
uploadObj = new Uploader({
htmlAttributes : { class : ' _custom-class-one '},
cssClass : ' _custom-class-two '
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('_custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('_custom-class-two')).toBe(true);
});
it('Giving class name with empty space in both cases seperatly', function () {
uploadObj = new Uploader({
htmlAttributes : { class : ' custom-class-one '},
cssClass : ' custom-class-two '
});
uploadObj.appendTo('#uploader');
expect(uploadObj.uploadWrapper.classList.contains('custom-class-one')).toBe(true);
expect(uploadObj.uploadWrapper.classList.contains('custom-class-two')).toBe(true);
});
});
describe('EJ2-31022 - Provide support for enable and disable the drag and drop option in Uploader', function () {
let uploadObj: any;
beforeEach(function () {
L10n.load({
'fr-BE': {
'uploader' : {
'Browse' : 'Feuilleter',
'Clear' : 'clair',
'Upload' : 'télécharger',
'dropFilesHint' : 'ou Déposez les fichiers ici',
'readyToUploadMessage' : 'Prêt à télécharger',
'inProgress' : 'Télécharger en cours',
'uploadFailedMessage' : 'Impossible d`importer le fichier',
'uploadSuccessMessage' : 'Fichiers chargés avec succès',
'invalidMaxFileSize' : 'La taille du fichier est trop grande',
'invalidMinFileSize' : 'La taille du fichier est trop petite',
'invalidFileType' : 'File type is not allowed'
}
}
});
let inputElement: HTMLElement = createElement('input', { id: 'uploader' });
document.body.appendChild(inputElement);
});
afterEach(function () {
if (uploadObj) {
uploadObj.destroy();
document.body.innerHTML = '';
}
});
it('No dropArea value is given while rendering', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop').textContent).toEqual('Or drop files here');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
expect(uploadObj.dropArea).toEqual(uploadObj.uploadWrapper);
});
it('No dropArea value is given while rendering as well as render with localization', function () {
uploadObj = new Uploader({
locale: 'fr-BE',
});
uploadObj.appendTo('#uploader');
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
expect(uploadObj.dropArea).toEqual(uploadObj.uploadWrapper);
});
it('No dropArea value is given while rendering and give localization as dynamic', function () {
uploadObj = new Uploader({
});
uploadObj.appendTo('#uploader');
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
expect(uploadObj.dropArea).toEqual(uploadObj.uploadWrapper);
});
it('dropArea value is given as custom-HTMLElement while rendering', function () {
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj = new Uploader({
dropArea: document.getElementById('dropele')
});
uploadObj.appendTo('#uploader');
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as custom-HTMLElement while rendering as well as render with localization', function () {
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj = new Uploader({
dropArea: document.getElementById('dropele'),
locale : 'fr-BE',
});
uploadObj.appendTo('#uploader');
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as custom-HTMLElement while rendering and enter localization as dynamic', function () {
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj = new Uploader({
dropArea: document.getElementById('dropele'),
});
uploadObj.appendTo('#uploader');
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as null while rendering', function () {
uploadObj = new Uploader({
dropArea : null,
});
uploadObj.appendTo('#uploader');
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.dropZoneElement).toBeUndefined;
});
it('dropArea value is given as null while rendering as well as with localization', function () {
uploadObj = new Uploader({
dropArea : null,
locale : 'fr-BE',
});
uploadObj.appendTo('#uploader');
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.dropZoneElement).toBeUndefined;
});
it('dropArea value is given as null while rendering and enter localization as dynamic', function () {
uploadObj = new Uploader({
dropArea : null,
});
uploadObj.appendTo('#uploader');
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.dropZoneElement).toBeUndefined;
});
it('dropArea value is given as default uploader while rendering', function () {
uploadObj = new Uploader({
dropArea: '.e-upload',
});
uploadObj.appendTo('#uploader');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop').textContent).toEqual('Or drop files here');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as default uploader while rendering as well as with localization', function () {
uploadObj = new Uploader({
dropArea: '.e-upload',
locale: 'fr-BE',
});
uploadObj.appendTo('#uploader');
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as default uploader while rendering and enter localization as dynamic', function () {
uploadObj = new Uploader({
dropArea: '.e-upload',
});
uploadObj.appendTo('#uploader');
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.uploadWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as custom-HTMLelement after rendering as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj.dropArea = document.getElementById('dropele');
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as custom-HTMLelement after rendering and give localization also as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
let dropElement: HTMLElement = createElement('div', {id: 'dropele'});
document.body.appendChild(dropElement);
uploadObj.dropArea = document.getElementById('dropele');
uploadObj.locale = 'fr-BE',
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
expect(uploadObj.dropZoneElement.__eventList.events.length).toBe(5);
});
it('dropArea value is given as default uploader as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
uploadObj.dropArea = '.e-upload';
uploadObj.dataBind();
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop').textContent).toEqual('Or drop files here');
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
});
it('dropArea value is given as default uploader as dynamic and also enter localization as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
uploadObj.dropArea = '.e-upload';
uploadObj.locale = 'fr-BE';
uploadObj.dataBind();
let localeText : string = 'ou Déposez les fichiers ici';
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(!isUndefined(uploadObj.dropAreaWrapper.querySelector('.e-file-drop'))).toBe(true);
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop').textContent).toBe(localeText);
expect(!isUndefined(uploadObj.dropZoneElement)).toBe(true);
});
it('dropArea value is given as null after rendering as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
uploadObj.dropArea = null;
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.dropZoneElement).toBeNull;
});
it('dropArea value is given as null after rendering and give localization also as dynamic', function () {
uploadObj = new Uploader({});
uploadObj.appendTo('#uploader');
uploadObj.dropArea = null;
uploadObj.locale = 'fr-BE',
uploadObj.dataBind();
expect(uploadObj.dropAreaWrapper.querySelector('.e-file-drop')).toBeUndefined;
expect(uploadObj.browseButton.innerText).toEqual('Feuilleter');
expect(uploadObj.dropZoneElement).toBeNull;
});
});
}); | the_stack |
import {
expandAtIndex,
expandAtIndexes,
expandByIds,
expandByIdsWithInfo,
collapseAtIndexes,
collapseAtIndex,
sortTreeData,
} from './index';
xdescribe('expandAtIndexes', () => {
it('index', () => {
const dataSource = expandAtIndexes(
[
{ id: 2, nodes: [{ id: 3 }, { id: 4 }] },
{ id: 5, nodes: [{ id: 6, nodes: [{ id: 8 }] }] },
{ id: 7 },
],
[0, 1],
{ generateIdFromPath: true }
);
const level1DataSource = [
{ id: 2, nodes: [{ id: 3 }, { id: 4 }] },
{
id: '2/3',
__nodeProps: { childIndex: 0, parentNodeId: 2, path: '2/3', depth: 1 },
},
{
id: '2/4',
__nodeProps: { childIndex: 1, parentNodeId: 2, path: '2/4', depth: 1 },
},
{ id: 5, nodes: [{ id: 6, nodes: [{ id: 8 }] }] },
{
id: '5/6',
nodes: [{ id: 8 }],
__nodeProps: { childIndex: 0, parentNodeId: 5, path: '5/6', depth: 1 },
},
{ id: 7 },
];
expect(dataSource).toEqual(level1DataSource);
const level2DataSource = expandAtIndexes(level1DataSource, [4], {
generateIdFromPath: true,
});
expect(level2DataSource).toEqual([
{ id: 2, nodes: [{ id: 3 }, { id: 4 }] },
{
id: '2/3',
__nodeProps: { childIndex: 0, parentNodeId: 2, path: '2/3', depth: 1 },
},
{
id: '2/4',
__nodeProps: { childIndex: 1, parentNodeId: 2, path: '2/4', depth: 1 },
},
{ id: 5, nodes: [{ id: 6, nodes: [{ id: 8 }] }] },
{
id: '5/6',
nodes: [{ id: 8 }],
__nodeProps: { childIndex: 0, parentNodeId: 5, path: '5/6', depth: 1 },
},
{
id: '5/6/8',
__nodeProps: {
childIndex: 0,
parentNodeId: '5/6',
path: '5/6/8',
depth: 2,
},
},
{ id: 7 },
]);
});
});
xdescribe('collapseAtIndexes', () => {
it('index', () => {
const dataSource = [
{ id: 2, nodes: [{ id: 3 }, { id: 4 }] },
{ id: 3, __nodeProps: { parentNodeId: 2, path: '2/3' } },
{ id: 4, __nodeProps: { parentNodeId: 2, path: '2/4' } },
{ id: 5, nodes: [{ id: 6 }] },
{ id: 6, __nodeProps: { parentNodeId: 5, path: '5/6' } },
{ id: 7 },
];
const newDataSource = collapseAtIndexes(dataSource, [0, 3], {
generateIdFromPath: false,
});
expect(newDataSource).toEqual([
{ id: 2, nodes: [{ id: 3 }, { id: 4 }] },
{ id: 5, nodes: [{ id: 6 }] },
{ id: 7 },
]);
});
});
xdescribe('expandByIds', () => {
it('index', () => {
// 1
// 2
// 3 - x
// 4
// 5 - x
// 6 - x
// 7
// 8
// 9 - x
// 10
// 11 - x
// 12
const six = { id: 6, nodes: [{ id: 7 }] };
const nine = { id: 9, nodes: [{ id: 10 }] };
const five = { id: 5, nodes: [six, { id: 8 }] };
const three = {
id: 3,
nodes: [{ id: 4 }, five, nine],
};
const dataSource = [
{ id: 1 },
{ id: 2 },
three,
{ id: 11, nodes: [{ id: 12 }] },
];
const { data: expandedSource, idToIndexMap } = expandByIdsWithInfo(
dataSource,
{
11: true,
3: true,
5: true,
9: true,
6: true,
},
{ idToIndexMap: { 1: 0, 2: 1, 3: 2, 11: 3 }, nodeProps: () => undefined }
);
expect(expandedSource).toEqual([
{ id: 1 },
{ id: 2 },
three,
{ id: 4, __nodeProps: undefined },
{ ...five, __nodeProps: undefined },
{ ...six, __nodeProps: undefined },
{ id: 7, __nodeProps: undefined },
{ id: 8, __nodeProps: undefined },
{ ...nine, __nodeProps: undefined },
{ id: 10, __nodeProps: undefined },
{ id: 11, nodes: [{ id: 12 }], __nodeProps: undefined },
{ id: 12, __nodeProps: undefined },
]);
expect(idToIndexMap).toEqual({
1: 0,
2: 1,
3: 2,
4: 3,
5: 4,
6: 5,
7: 6,
8: 7,
9: 8,
10: 9,
11: 10,
12: 11,
});
});
});
xdescribe('expandAtIndex', () => {
it('index', () => {
const dataSource = expandAtIndex(
[{ id: 2 }, { id: 3, nodes: [{ id: 4 }] }, { id: 5 }],
1,
{ generateIdFromPath: true }
);
expect(dataSource).toEqual([
{
id: 2,
},
{ id: 3, nodes: [{ id: 4 }] },
{
id: '3/4',
__nodeProps: { childIndex: 0, depth: 1, parentNodeId: 3, path: '3/4' },
},
{ id: 5 },
]);
});
it('index without generateIdFromPath', () => {
const dataSource = expandAtIndex(
[{ id: 2 }, { id: 3, nodes: [{ id: 4 }] }, { id: 5 }],
1,
{ generateIdFromPath: false }
);
expect(dataSource).toEqual([
{
id: 2,
},
{ id: 3, nodes: [{ id: 4 }] },
{
id: 4,
__nodeProps: { childIndex: 0, parentNodeId: 3, path: '3/4', depth: 1 },
},
{ id: 5 },
]);
});
it('expandAtIndex with non-existent index', () => {
const dataSource = [{ id: 2 }, { id: 3, nodes: [{ id: 4 }] }, { id: 5 }];
expect(expandAtIndex(dataSource, 100)).toBe(dataSource);
});
it('expandAtIndex with existent index with no nodes', () => {
const dataSource = [{ id: 2 }, { id: 3, nodes: [{ id: 4 }] }, { id: 5 }];
expect(expandAtIndex(dataSource, 0)).toBe(dataSource);
});
it('idProperty is generated correctly', () => {
const dataSource = [
{ name: 2 },
{ name: 3, nodes: [{ name: 4 }] },
{ name: 5 },
];
const newDataSource = expandAtIndex(dataSource, 1, {
generateIdFromPath: true,
pathSeparator: '/',
idProperty: 'name',
});
expect(newDataSource).toEqual([
{
name: 2,
},
{ name: 3, nodes: [{ name: 4 }] },
{
name: '3/4',
__nodeProps: { childIndex: 0, parentNodeId: 3, path: '3/4', depth: 1 },
},
{ name: 5 },
]);
});
});
xdescribe('collapseAtIndex', () => {
it('index', () => {
const dataSource = collapseAtIndex(
[
{
name: 2,
},
{ name: 3, id: 3, nodes: [{ name: 4 }, { name: 6 }] },
{ name: '3/4', __nodeProps: { parentNodeId: 3, path: '3/4' } },
{ name: '3/6', __nodeProps: { parentNodeId: 3, path: '3/6' } },
{ name: 5 },
],
1,
{ generateIdFromPath: true }
);
expect(dataSource).toEqual([
{
name: 2,
},
{ name: 3, id: 3, nodes: [{ name: 4 }, { name: 6 }] },
{ name: 5 },
]);
});
it('with no valid index', () => {
const dataSource = [{ name: 3 }];
const newDataSource = collapseAtIndex(dataSource, 2);
expect(newDataSource).toBe(dataSource);
});
});
describe('sorting', () => {
it('sortTreeData shallow sort', () => {
const dataSource = [
{ id: 2, __nodeProps: { path: '2', depth: 0 } },
{
id: '2/3',
name: 'z',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: '2/3/1',
name: 'z',
__nodeProps: { path: '2/3/1', depth: 2 },
},
{
id: '2/3/1/1',
name: 'za',
__nodeProps: { path: '2/3/1/1', depth: 3 },
},
{
id: '2/3/2',
name: 'y',
__nodeProps: { path: '2/3/2', depth: 2 },
},
{
id: '2/4',
name: 'y',
__nodeProps: { path: '2/4', depth: 1 },
},
{
id: '2/4/1',
name: 'z',
__nodeProps: { path: '2/4/1', depth: 2 },
},
{
id: '2/4/2',
name: 'y',
__nodeProps: { path: '2/4/2', depth: 2 },
},
{
id: 5,
__nodeProps: { path: '5', depth: 0 },
},
{
id: '5/6',
name: 'r',
__nodeProps: { path: '5/6', depth: 1 },
},
{
id: '5/6/8',
name: 'a',
__nodeProps: { path: '5/6/8', depth: 2 },
},
{
id: '5/11',
name: 'q',
__nodeProps: { path: '5/11', depth: 1 },
},
{ id: 7, __nodeProps: { path: '7', depth: 0 } },
];
const result = sortTreeData({ name: 'name', dir: 1 }, dataSource, {
depth: 1,
deep: false,
});
expect(result).toEqual([
{ id: 2, __nodeProps: { path: '2', depth: 0 } },
{
id: '2/4',
name: 'y',
__nodeProps: { path: '2/4', depth: 1 },
},
{
id: '2/4/1',
name: 'z',
__nodeProps: { path: '2/4/1', depth: 2 },
},
{
id: '2/4/2',
name: 'y',
__nodeProps: { path: '2/4/2', depth: 2 },
},
{
id: '2/3',
name: 'z',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: '2/3/1',
name: 'z',
__nodeProps: { path: '2/3/1', depth: 2 },
},
{
id: '2/3/1/1',
name: 'za',
__nodeProps: { path: '2/3/1/1', depth: 3 },
},
{
id: '2/3/2',
name: 'y',
__nodeProps: { path: '2/3/2', depth: 2 },
},
{
id: 5,
__nodeProps: { path: '5', depth: 0 },
},
{
id: '5/11',
name: 'q',
__nodeProps: { path: '5/11', depth: 1 },
},
{
id: '5/6',
name: 'r',
__nodeProps: { path: '5/6', depth: 1 },
},
{
id: '5/6/8',
name: 'a',
__nodeProps: { path: '5/6/8', depth: 2 },
},
{ id: 7, __nodeProps: { path: '7', depth: 0 } },
]);
});
it('sortTreeData deep sort', () => {
const dataSource = [
{ id: 2, __nodeProps: { path: '2', depth: 0 } },
{
id: '2/3',
name: 'z',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: '2/3/1',
name: 'z',
__nodeProps: { path: '2/3/1', depth: 2 },
},
{
id: '2/3/1/1',
name: 'za',
__nodeProps: { path: '2/3/1/1', depth: 3 },
},
{
id: '2/3/2',
name: 'y',
__nodeProps: { path: '2/3/2', depth: 2 },
},
{
id: '2/4',
name: 'y',
__nodeProps: { path: '2/4', depth: 1 },
},
{
id: '2/4/1',
name: 'z',
__nodeProps: { path: '2/4/1', depth: 2 },
},
{
id: '2/4/2',
name: 'y',
__nodeProps: { path: '2/4/2', depth: 2 },
},
{
id: 5,
__nodeProps: { path: '5', depth: 0 },
},
{
id: '5/6',
name: 'r',
__nodeProps: { path: '5/6', depth: 1 },
},
{
id: '5/6/8',
name: 'a',
__nodeProps: { path: '5/6/8', depth: 2 },
},
{
id: '5/11',
name: 'q',
__nodeProps: { path: '5/11', depth: 1 },
},
{ id: 7, __nodeProps: { path: '7', depth: 0 } },
];
const result = sortTreeData({ name: 'name', dir: 1 }, dataSource, {
depth: 1,
deep: true,
});
expect(result).toEqual([
{ id: 2, __nodeProps: { path: '2', depth: 0 } },
{
id: '2/4',
name: 'y',
__nodeProps: { path: '2/4', depth: 1 },
},
{
id: '2/4/2',
name: 'y',
__nodeProps: { path: '2/4/2', depth: 2 },
},
{
id: '2/4/1',
name: 'z',
__nodeProps: { path: '2/4/1', depth: 2 },
},
{
id: '2/3',
name: 'z',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: '2/3/2',
name: 'y',
__nodeProps: { path: '2/3/2', depth: 2 },
},
{
id: '2/3/1',
name: 'z',
__nodeProps: { path: '2/3/1', depth: 2 },
},
{
id: '2/3/1/1',
name: 'za',
__nodeProps: { path: '2/3/1/1', depth: 3 },
},
{
id: 5,
__nodeProps: { path: '5', depth: 0 },
},
{
id: '5/11',
name: 'q',
__nodeProps: { path: '5/11', depth: 1 },
},
{
id: '5/6',
name: 'r',
__nodeProps: { path: '5/6', depth: 1 },
},
{
id: '5/6/8',
name: 'a',
__nodeProps: { path: '5/6/8', depth: 2 },
},
{ id: 7, __nodeProps: { path: '7', depth: 0 } },
]);
});
it('should sort data correctly', () => {
const dataSource = [
{
id: 1,
__nodeProps: { path: '1', depth: 0 },
},
{
id: '1/1',
__nodeProps: { path: '1/1', depth: 1 },
},
{
id: '1/2',
__nodeProps: { path: '1/2', depth: 1 },
},
{
id: '1/3',
__nodeProps: { path: '1/3', depth: 1 },
},
{
id: 2,
__nodeProps: { path: '2', depth: 0 },
},
{
id: '2/1',
__nodeProps: { path: '2/1', depth: 1 },
},
{
id: '2/2',
__nodeProps: { path: '2/2', depth: 1 },
},
{
id: '2/3',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: 3,
__nodeProps: { path: '3', depth: 0 },
},
{
id: '3/1',
__nodeProps: { path: '3/1', depth: 1 },
},
{
id: '3/1/1',
__nodeProps: { path: '3/1/1', depth: 2 },
},
{
id: '3/1/2',
__nodeProps: { path: '3/1/2', depth: 2 },
},
{
id: '3/2',
__nodeProps: { path: '3/2', depth: 1 },
},
];
const result = sortTreeData([{ name: 'id', dir: -1 }], dataSource, {
depth: 0,
deep: true,
});
expect(result).toEqual([
{
id: 3,
__nodeProps: { path: '3', depth: 0 },
},
{
id: '3/2',
__nodeProps: { path: '3/2', depth: 1 },
},
{
id: '3/1',
__nodeProps: { path: '3/1', depth: 1 },
},
{
id: '3/1/2',
__nodeProps: { path: '3/1/2', depth: 2 },
},
{
id: '3/1/1',
__nodeProps: { path: '3/1/1', depth: 2 },
},
{
id: 2,
__nodeProps: { path: '2', depth: 0 },
},
{
id: '2/3',
__nodeProps: { path: '2/3', depth: 1 },
},
{
id: '2/2',
__nodeProps: { path: '2/2', depth: 1 },
},
{
id: '2/1',
__nodeProps: { path: '2/1', depth: 1 },
},
{
id: 1,
__nodeProps: { path: '1', depth: 0 },
},
{
id: '1/3',
__nodeProps: { path: '1/3', depth: 1 },
},
{
id: '1/2',
__nodeProps: { path: '1/2', depth: 1 },
},
{
id: '1/1',
__nodeProps: { path: '1/1', depth: 1 },
},
]);
});
}); | the_stack |
* {@link Laika | `Laika`} is the place where most of the magic happens.
* All the operations are routed through its Apollo Link, and Laika can decide what happens to them along the way.
* By default every connection is passed through and no additional action is taken.
*
* If you're using createGlobalLaikaLink, an instance of Laika is by default installed as `laika` property
* on the global object (most likely `window`), accessible as `window.laika`
* or simply as `laika`.
*
* Key functionality:
*
* - {@link Laika.intercept | `laika.intercept()`}:
*
* If you use `jest`, you can think of laika like the `jest` global,
* where the equivalent of `jest.fn()` is {@link Laika.intercept | `laika.intercept()`}
* - {@link Laika.LogApi | `laika.log`}
*
* The other thing laika is responsible for is logging.
*
* Logging functionality is behind a separate API available under {@link Laika.LogApi | `laika.log`}.
*
* @packageDocumentation
* @module Laika
*/
/* eslint-disable no-console */
import noop from 'lodash/noop'
import {
ApolloLink,
FetchResult,
NextLink,
Observable,
Observer,
Operation,
} from '@apollo/client/core'
import type { GenerateCodeOptions } from './codeGenerator'
import { generateCode } from './codeGenerator'
import { LOGGING_DISABLED_MATCHER } from './constants'
import { getLogStyle } from './getLogStyle'
import { hasMutationOperation, hasSubscriptionOperation } from './hasOperation'
import { getEmitValueFn, getMatcherFn } from './linkUtils'
import type {
Behavior,
EventFilterFn,
FetchResultSubscriptionObserver,
InterceptorFn,
ManInTheMiddleFn,
Matcher,
MatcherFn,
OnSubscribe,
OnSubscribeCallback,
PassthroughDisableFn,
PassthroughEnableFn,
RecordingElement,
Result,
ResultOrFn,
SubscribeMeta,
Subscription,
Variables,
} from './typedefs'
const CONSOLE_PADDING = 20
const CONSOLE_SUFFIX_PADDING = 60
const CONSOLE_INTERCEPT_PADDING = 10
const CONSOLE_TYPE_PADDING = 26
const CONSOLE_TIME_SINCE_PADDING = 5
const ONE_SECOND_IN_MS = 1_000
/**
* Class responsible for managing interceptions.
* By default a singleton is installed on `globalThis` (usually `window`) under `laika`.
*
* Read more in the {@link Laika | module page} or scroll down to see it's functionality.
*
* @example
* ```js
* laika.log.startLogging();
* ```
*/
export class Laika {
private readonly referenceName: string
constructor({
referenceName = 'laika',
}: {
referenceName?: string
} = {}) {
this.referenceName = referenceName
}
/**
* Provides functionality to intercept, and optionally mock or modify each operation's subscription.
* The API returned is heavily inspired on jest's mocking functionality (`jest.fn()`)
* and is described in length here: {@link InterceptApi}.
*
* Every interceptor you create should be as specific as needed in a given session.
* At the very least, ensure the order of creating interceptors is from most specific, to least specific.
*
* This is because any operations that are executed by your client will end up
* being intercepted by the **first** interceptor that matches
* the constraints of the {@link Matcher}.
*
* See [*Pitfalls*](pitfalls.md) for more information.
*
* @param matcher [[include:matcher.md]]
* @param connectFutureLinksOrMitmFn If true, future links will still be called (e.g. reach the backend) and return responses. If set to a function, can serve for man-in-the-middle tinkering with the result.
* @param keepNonSubscriptionConnectionsOpen If true, queries and mutations will behave a little like subscriptions, in that you will be able to fire updates even after the initial response. Experimental.
* @example
* ```js
* const getActiveUsersInterceptor = laika.intercept({
* clientName: 'users',
* operationName: 'getActiveUsers',
* });
* ```
*/
intercept(
matcher?: Matcher | undefined,
connectFutureLinksOrMitmFn:
| (ManInTheMiddleFn | boolean)
| undefined = false,
keepNonSubscriptionConnectionsOpen = false,
): InterceptApi {
const matcherFn: MatcherFn = getMatcherFn(matcher)
const resultFnLimitedSet: Set<{
resultOrFn: ResultOrFn
matcher: MatcherFn
repeatTimes?: number
}> = new Set()
const resultFnPersistentSet: Set<{
resultOrFn: ResultOrFn
matcher: MatcherFn
repeatTimes?: number
}> = new Set()
const onSubscribeCallbacks: Set<OnSubscribeCallback> = new Set()
let passthrough = connectFutureLinksOrMitmFn
// we will still allow passthrough for normal requests (not subscriptions)
// if a given request was not mocked, even when passthrough itself is falsy
// this variable here tightens the pipe and stops the show completely:
let passthroughFallbackAllowed = true
const passthroughEnablers: Set<PassthroughEnableFn> = new Set()
const passthroughDisablers: Set<PassthroughDisableFn> = new Set()
const observerToOperationMap: Map<
FetchResultSubscriptionObserver,
Operation
> = new Map()
const calledWithVariables: Variables[] = []
const onSubscribe: OnSubscribe = ({
operation,
observer,
enablePassthrough,
disablePassthrough,
}) => {
observerToOperationMap.set(observer, operation)
passthroughEnablers.add(enablePassthrough)
passthroughDisablers.add(disablePassthrough)
calledWithVariables.push(operation.variables)
const cleanupFns: ((() => void) | void)[] = [...onSubscribeCallbacks]
.map((callback) =>
callback({
operation,
observer,
removeCallback: () => onSubscribeCallbacks.delete(callback),
}),
)
.filter(Boolean)
// sets initial passthrough state for this observer only (forwarding server responses):
if (passthrough) {
enablePassthrough(
typeof passthrough === 'function' ? passthrough : undefined,
)
} else {
// likely no-op:
disablePassthrough()
}
let mockedResult: Result | undefined
for (const resultGroup of [
...resultFnLimitedSet,
...resultFnPersistentSet,
]) {
const { resultOrFn: thisResultOrFn, matcher } = resultGroup
// eslint-disable-next-line no-continue
if (!matcher(operation)) continue
mockedResult =
typeof thisResultOrFn === 'function'
? thisResultOrFn(operation)
: thisResultOrFn
if (typeof resultGroup.repeatTimes === 'number') {
if (resultGroup.repeatTimes <= 1) {
resultFnLimitedSet.delete(resultGroup)
} else {
resultGroup.repeatTimes--
}
}
break
}
const queryIncludesSubscription = hasSubscriptionOperation(operation)
if (mockedResult) {
const emitValue = getEmitValueFn(mockedResult)
emitValue(operation, observer)
if (
!queryIncludesSubscription &&
!observer.closed &&
!keepNonSubscriptionConnectionsOpen
) {
observer.complete()
}
} else if (
!passthrough &&
!queryIncludesSubscription &&
passthroughFallbackAllowed
) {
// we want to pass through a single request, but nothing beyond that
enablePassthrough(
({ disablePassthrough, forward }) =>
new Observable((observer) => {
// this is the equivalent of take(1), which zen-observable does not offer:
const innerSubscription = forward(operation).subscribe({
next: (remoteResult) => {
observer.next(remoteResult)
observer.complete()
innerSubscription.unsubscribe()
disablePassthrough()
},
complete: () => {
if (!observer.complete) observer.complete()
},
error: (remoteError) => {
observer.error(remoteError)
},
})
}),
)
}
return () => {
// we're unsubscribed, i.e. a component with useQuery was unmounted
observerToOperationMap.delete(observer)
passthroughEnablers.delete(enablePassthrough)
passthroughDisablers.delete(disablePassthrough)
cleanupFns.forEach((fn) => {
if (typeof fn === 'function') fn()
})
}
}
const behavior: Behavior = {
matcher: matcherFn,
onSubscribe,
}
const ensureBehaviorRegistered = () => {
// any queries made from now on will be matched against this behavior:
this.behaviors.add(behavior)
// but there might be currently subscribed operations, we want to take over those too:
this.unmatchedOperationOptions.forEach((subscribeMeta) => {
if (!matcherFn(subscribeMeta.operation)) return
this.unmatchedOperationOptions.delete(subscribeMeta)
const cleanup = onSubscribe(subscribeMeta)
this.cleanupFnPerSubscribeMeta.set(subscribeMeta, cleanup)
})
}
ensureBehaviorRegistered()
const enablePassthroughInAllObservers: PassthroughEnableFn = (mitm) => {
if (!passthroughFallbackAllowed) return false
passthrough = mitm ?? true
const successList = [...passthroughEnablers].map((enablePassthrough) =>
enablePassthrough(mitm),
)
return successList.some(Boolean)
}
const disablePassthroughInAllObservers: PassthroughDisableFn = () => {
passthrough = false
const successList = [...passthroughDisablers].map((disablePassthrough) =>
disablePassthrough(),
)
return successList.some(Boolean)
}
// format of result should be the same as 'result' described here https://www.apollographql.com/docs/react/development-testing/testing/#defining-mocked-responses
/**
* See documentation of each function in {@link InterceptApi}
*/
const interceptApi: InterceptApi = {
get calls() {
return [...calledWithVariables]
},
mockResult(resultOrFn: ResultOrFn, matcher?: Matcher | undefined) {
ensureBehaviorRegistered()
disablePassthroughInAllObservers()
const matcherFn = getMatcherFn(matcher)
resultFnPersistentSet.add({ resultOrFn, matcher: matcherFn })
return interceptApi
},
mockResultOnce(resultOrFn: ResultOrFn, matcher?: Matcher | undefined) {
ensureBehaviorRegistered()
disablePassthroughInAllObservers()
const matcherFn = getMatcherFn(matcher)
resultFnLimitedSet.add({
resultOrFn,
matcher: matcherFn,
repeatTimes: 1,
})
return interceptApi
},
waitForActiveSubscription() {
ensureBehaviorRegistered()
if (observerToOperationMap.size > 0) return undefined
return interceptApi.waitForNextSubscription().then(noop)
},
async waitForNextSubscription() {
ensureBehaviorRegistered()
return new Promise((resolve) => {
interceptApi.onSubscribe(({ removeCallback, ...data }) => {
removeCallback()
resolve(data)
})
})
},
fireSubscriptionUpdate(resultOrFn: ResultOrFn, fireMatcher?: Matcher) {
ensureBehaviorRegistered()
if (observerToOperationMap.size === 0) {
const operationName =
(typeof matcher === 'object' && matcher.operationName) ||
(typeof fireMatcher === 'object' && fireMatcher.operationName)
throw new Error(
`Cannot fire a subscription update, as there is nothing listening to ${
operationName ? `'${operationName}'.` : 'this Apollo operation.'
}`,
)
}
observerToOperationMap.forEach((operation, observer) => {
const result =
typeof resultOrFn === 'function'
? resultOrFn(operation)
: resultOrFn
const emitValue = getEmitValueFn(result, getMatcherFn(fireMatcher))
emitValue(operation, observer)
})
return interceptApi
},
onSubscribe(callback: OnSubscribeCallback) {
ensureBehaviorRegistered()
onSubscribeCallbacks.add(callback)
return () => {
onSubscribeCallbacks.delete(callback)
}
},
disableNetworkFallback() {
ensureBehaviorRegistered()
passthroughFallbackAllowed = false
},
allowNetworkFallback() {
passthroughFallbackAllowed = true
},
mockReset() {
resultFnLimitedSet.clear()
resultFnPersistentSet.clear()
onSubscribeCallbacks.clear()
calledWithVariables.length = 0
passthroughFallbackAllowed = true
passthrough = connectFutureLinksOrMitmFn
if (passthrough) {
enablePassthroughInAllObservers(
typeof passthrough === 'function' ? passthrough : undefined,
)
}
ensureBehaviorRegistered()
return interceptApi
},
mockRestore: () => {
interceptApi.mockReset()
enablePassthroughInAllObservers()
this.behaviors.delete(behavior)
},
}
return interceptApi
}
/**
* Modify backend (or mocked) responses before they reach subscribers.
*
* @param matcher [[include:matcher.md]]
* @param mapFn Mapping function to alter the responses.
*/
modifyRemote(
matcher: Matcher | undefined,
mapFn: (result: FetchResult, operation: Operation) => FetchResult,
) {
const interceptor = this.intercept(matcher, ({ forward, operation }) =>
forward(operation).map((result) => mapFn(result, operation)),
)
return {
restore: interceptor.mockRestore,
}
}
// logging API - for documentation see end of file
/**
* A set of functions that controls logging and recording of all (or selected) operations.
*
* Read more on the {@link Laika.LogApi | LogApi} page.
*
* @example
* ```js
* laika.log.startLogging();
* ```
*/
log: LogApi = {
startLogging: (matcher?: Matcher) => {
this.loggingMatcher = getMatcherFn(matcher)
},
stopLogging: () => {
this.loggingMatcher = LOGGING_DISABLED_MATCHER
},
startRecording: (startingActionName?: string, matcher?: Matcher) => {
this.log.startLogging(matcher)
this.isRecording = true
if (startingActionName) {
this.log.markAction(startingActionName)
} else {
console.log(
`It is recommended to name your actions before you take them during the recording by calling: ${this.referenceName}.log.markAction('opening the ticket')`,
)
}
},
stopRecording: () => {
this.isRecording = false
},
resetRecording: () => {
this.recording.length = 0
},
markAction: (actionName: string) => {
this.actionName = actionName
if (this.isRecording) {
const now = Date.now()
if (!this.firstCaptureTimestamp) this.firstCaptureTimestamp = now
this.recording.push({
type: 'marker',
timeDelta: now - this.firstCaptureTimestamp,
action: actionName,
})
} else {
throw new Error(
`Sorry, you're not recording yet. log.startRecording() first :)`,
)
}
},
generateMockCode: (
eventFilter?: EventFilterFn,
options?: GenerateCodeOptions,
) =>
generateCode(
{
recording: this.recording,
referenceName: this.referenceName,
},
eventFilter,
options,
),
}
/**
* Use this function to create an Apollo Link that uses this Laika instance.
* Useful in unit tests.
* @param onRequest
*/
createLink(onRequest?: (operation: Operation, forward: NextLink) => void) {
return new ApolloLink((operation, forward) => {
if (!forward) {
throw new Error('LaikaLink cannot be used as a terminating link!')
}
onRequest?.(operation, forward)
return this.interceptor(operation, forward)
})
}
// private APIs below
/**
* @internal
* */
interceptor: InterceptorFn = (operation, forward) =>
new Observable<FetchResult>((observer) => {
// we're subscribed, e.g. a component with useQuery was mounted or a refetch was requested
operation.setContext({
subscribeTime: Date.now(),
interceptMode: 'unset',
})
let active = true
let passthroughSubscription: Subscription | undefined
let lastMitm: ManInTheMiddleFn | undefined
const disablePassthrough = () => {
let isSuccess = false
if (passthroughSubscription && !passthroughSubscription.closed) {
passthroughSubscription.unsubscribe()
isSuccess = true
}
passthroughSubscription = undefined
lastMitm = undefined
operation.setContext({ interceptMode: 'mock' })
return isSuccess
}
// currently mounted components would not work until they're remounted
// hence the need for passthrough
const enablePassthrough = (mitm?: ManInTheMiddleFn | undefined) => {
if (observer.closed || !active) {
// no body is listening anymore, we can only clean-up:
disablePassthrough()
return false
}
if (passthroughSubscription) {
if (mitm === lastMitm) {
// no change needed, we're already subscribed to the right thing!
return true
}
// we need to re-subscribe because the sniffer has changed
// could be mitigated with a switchMap from rxjs, but we don't have rxjs 🤷♂️
disablePassthrough()
}
// we 'unmock', i.e. we want to (re-)establish connectivity:
const forward$ = mitm
? mitm({
operation,
forward,
observer,
enablePassthrough,
disablePassthrough,
})
: forward(operation)
operation.setContext({ interceptMode: mitm ? 'mitm' : 'passthrough' })
passthroughSubscription = forward$.subscribe(observer)
lastMitm = mitm
return true
}
let cleanupFn: () => void = noop
const subscribeMeta = {
operation,
observer,
forward,
enablePassthrough,
disablePassthrough,
}
const interceptionBehavior = [...this.behaviors].find(({ matcher }) =>
matcher(operation),
)
if (interceptionBehavior) {
cleanupFn = interceptionBehavior.onSubscribe(subscribeMeta)
} else {
this.unmatchedOperationOptions.add(subscribeMeta)
// until mocking starts, we want to forward everything from the backend as is:
enablePassthrough()
cleanupFn = () => {
this.unmatchedOperationOptions.delete(subscribeMeta)
const cleanup = this.cleanupFnPerSubscribeMeta.get(subscribeMeta)
if (cleanup) cleanup()
}
}
const logUnsubscribe = this.logSubscribe(subscribeMeta)
return () => {
logUnsubscribe()
cleanupFn()
disablePassthrough()
active = false
operation.setContext({ interceptMode: 'disposed' })
// TODO: does it make sense to complete the observer here? `if (!o.closed) o.complete()`
}
}).map(this.getLogFunction({ operation, forward }))
// interceptor-related properties:
private readonly behaviors: Set<Behavior> = new Set()
private readonly unmatchedOperationOptions: Set<SubscribeMeta> = new Set()
private readonly cleanupFnPerSubscribeMeta: WeakMap<
SubscribeMeta,
() => void
> = new WeakMap()
// logging functionality:
/**
* @param input
*/
private getLogFunction({
operation,
}: {
operation: Operation
forward: NextLink
}): (result: FetchResult) => FetchResult {
return (result) => {
if (!this.loggingMatcher(operation)) return result
const hasMutation = hasMutationOperation(operation)
const type = hasSubscriptionOperation(operation)
? 'push'
: hasMutation
? 'response:mutation'
: 'response:query'
const {
clientName: unsafeClientName,
feature: unsafeFeature,
subscribeTime,
interceptMode: unsafeInterceptMode,
} = operation.getContext()
const clientName = unsafeClientName ? String(unsafeClientName) : 'client'
const feature = unsafeFeature ? String(unsafeFeature) : undefined
const interceptMode = String(unsafeInterceptMode)
const { operationName } = operation
const now = Date.now()
if (this.isRecording) {
if (!this.firstCaptureTimestamp) this.firstCaptureTimestamp = now
this.recording.push({
clientName,
timeDelta: now - this.firstCaptureTimestamp,
operationName: operation.operationName,
variables: operation.variables,
feature,
type,
result,
action: this.actionName,
})
}
const timeSinceSubscribe = subscribeTime
? `${((now - subscribeTime) / ONE_SECOND_IN_MS).toFixed(1)}s`
: '?s'
const suffixText = `${operationName}${feature ? ` (${feature})` : ''}`
console.log(
`${
this.isRecording ? '🔴 REC:GQL' : '🔵 LOG:GQL'
} %c${clientName.padStart(CONSOLE_PADDING, ' ')}: ${type.padEnd(
CONSOLE_PADDING,
' ',
)} ${timeSinceSubscribe.padStart(
CONSOLE_TIME_SINCE_PADDING,
' ',
)} ${interceptMode.padEnd(
CONSOLE_INTERCEPT_PADDING,
' ',
)} ${suffixText.padEnd(CONSOLE_SUFFIX_PADDING, ' ')}\t%o`,
getLogStyle(operationName),
{ operation, result },
)
return result
}
}
/**
* @param data
*/
private logSubscribe({ operation }: SubscribeMeta): () => void {
if (!this.loggingMatcher(operation)) return noop
const hasMutation = hasMutationOperation(operation)
const type = hasSubscriptionOperation(operation)
? 'subscription'
: hasMutation
? 'mutation'
: 'query'
const {
clientName: unsafeClientName,
feature: unsafeFeature,
interceptMode: unsafeInterceptMode,
} = operation.getContext()
const clientName = String(unsafeClientName)
const feature = String(unsafeFeature)
const interceptMode = String(unsafeInterceptMode)
const { operationName } = operation
if (type !== 'subscription') {
// less noisy console
return noop
}
const suffixText = `${operationName}${feature ? ` (${feature})` : ''}`
const mainText = `${clientName.padStart(
CONSOLE_PADDING,
' ',
)}: ${type.padEnd(CONSOLE_TYPE_PADDING, ' ')} ${interceptMode.padEnd(
CONSOLE_INTERCEPT_PADDING,
' ',
)} ${suffixText.padEnd(CONSOLE_SUFFIX_PADDING, ' ')}`
console.log(`🚀 SUB:GQL %c${mainText}\t%o`, getLogStyle(operationName), {
operation,
})
return () => {
console.log(`🏁 END:GQL %c${mainText}\t%o`, getLogStyle(operationName), {
operation,
})
}
}
// logging-related properties:
private loggingMatcher: MatcherFn = LOGGING_DISABLED_MATCHER
private firstCaptureTimestamp: number | undefined
private recording: RecordingElement[] = []
private actionName = 'first action'
private isRecording = false
}
export declare abstract class LogApi {
/** @ignore */
constructor()
/**
* Starts logging every matching operation and subscription to the console.
* If you did not provide a matcher, it will log everything.
* You will see queries, mutations, and subscription pushes along with their data.
*
* 
*/
startLogging(matcher?: Matcher | undefined): void
/**
* Stops logging to the console.
*/
stopLogging(): void
/**
* Starts the recording process. Every result will be saved until you run `log.stopRecording()`.
*
* 
*
* @param startingActionName Name what you are about to do. For example "opening a new ticket".
* @param matcher A matcher object or function to record only the events that you are interested in, for example `{operationName: 'getColors', clientName: 'backend1'}` will record only `'getColors'` operations.
*/
startRecording(
startingActionName?: string | undefined,
matcher?: Matcher | undefined,
): void
/**
* Pauses recording without clearing what was recorded so far.
*/
stopRecording(): void
/**
* Resets the recording in preparation of another one.
*/
resetRecording(): void
/**
* Use this function to mark a new action if recording a sequence of events.
*
* These will show up when you generate mock code as comments,
* so you can more easily orient yourself in it.
*
* @param actionName Describe what action you will be performing, e.g. 'opening the ticket'
* @example
* ```js
* log.markAction('opening the ticket');
* // click around the site
* log.markAction('changing the assignee');
* ```
*/
markAction(actionName: string): void
/**
* Returns a code snippet that will help you reproduce your recording without hitting actual backends.
* @param eventFilter Optionally provide a function that will only keep the events you are interested in.
* @param options Optionally provide code generation options to customize the output.
*/
generateMockCode(
eventFilter?: EventFilterFn,
options?: GenerateCodeOptions,
): string
}
/**
* This is the mocking API that is returned after running {@link Laika.intercept | `intercept()`} on the {@link Laika | Laika}.
*
* The API is chainable, with the exception of `mockRestore()`.
*
* Inspired by `jest.fn()`.
*/
export declare abstract class InterceptApi {
/** @ignore */
constructor()
/**
* An array containing the `variables` from subsequent operations that passed through this intercept.
*
* Similar to `jest.fn().mock.calls`.
*/
readonly calls: readonly Variables[]
/**
* Sets the mock data that will be used as a default response to intercepted queries and mutations.
* If used for subscriptions, will push data immediately.
*
* Similar to `jest.fn().mockReturnValue(...)`.
*
* @param resultOrFn [[include:result-or-fn.md]]
* @param matcher [[include:mock-matcher.md]]
* @example
* Always respond with the mock to all queries/mutations intercepted
* ```js
* const intercept = laika.intercept({operationName: 'getUsers'});
* intercept.mockResult(
* {result: {data: {users: [{id: 1, name: 'Mouse'}, {id: 2, name: 'Bamboo'}]}}},
* );
* ```
* @example
* Respond with an error, but only when the operations's variables contain `{userGroup: 'elephants'}`
* ```js
* const intercept = laika.intercept({operationName: 'getUsers'});
* intercept.mockResult(
* {error: new Error(`oops, server blew up from all the elephants stomping!`)},
* {variables: {userGroup: 'elephants'}}
* );
* ```
* @example
* Respond with a customized error based on the variables:
* ```js
* const intercept = laika.intercept({operationName: 'getUsers'});
* intercept.mockResult(
* ({variables}) => ({error: new Error(`oops, server blew up from all the ${variables.userGroup} stomping!`)})
* );
* ```
*/
mockResult(
resultOrFn: ResultOrFn,
matcher?: Matcher | undefined,
): InterceptApi
/**
* Sets the mock data that will be used as the *next* response to matching intercepted queries/mutations.
* If used for subscription operations, will immediately push provided data to the next matching request.
* Works the same as {@link InterceptApi.mockResult | `mockResult`},
* except that as soon as a matching result is found in the queue of mocks, it will not be sent again.
*
* Can be run multiple times and will send responses in order in which `mockResultOnce` was called.
*
* @param resultOrFn [[include:result-or-fn.md]]
* @param matcher [[include:mock-matcher.md]]
* @example
* Respond with the mock to the first intercepted operation with the name `getUsers`,
* then with a different mock the second time that operation is intercepted.
* ```js
* const intercept = laika.intercept({operationName: 'getUsers'});
* intercept
* .mockResultOnce(
* {result: {data: {users: [{id: 1, name: 'Mouse'}, {id: 2, name: 'Bamboo'}]}}},
* );
* .mockResultOnce(
* {result: {data: {users: [{id: 9, name: 'Ox'}, {id: 10, name: 'Fox'}]}}},
* );
* ```
*/
mockResultOnce(
resultOrFn: ResultOrFn,
matcher?: Matcher | undefined,
): InterceptApi
/**
* In case of GraphQL subscriptions, will return synchronously if at least
* one intercepted subscription is already active.
* In other cases returns a `Promise` and behaves the same way as {@link InterceptApi.waitForNextSubscription | `waitForNextSubscription()`}.
*/
waitForActiveSubscription(): Promise<void> | undefined
/**
* Returns a Promise that will resolve when the *next* operation is run.
* This translates to whenever a query/mutation is run, or whenever the *next* subscription is made.
*/
waitForNextSubscription(): Promise<{
operation: Operation
observer: Observer<FetchResult>
}>
/**
* Push data to an already active `subscription`-type operation.
* Will throw if there are no subscribers (e.g. active `useQuery` hooks).
*
* Works similarly to {@link InterceptApi.mockResult | `mockResult(...)`}, but the listener
* is being fed the new data upon execution.
*
* Combine with {@link InterceptApi.waitForActiveSubscription | `waitForActiveSubscription()`}
* to ensure a subscription is active before calling.
*
* @param resultOrFn [[include:result-or-fn.md]]
* @param fireMatcher [[include:mock-matcher.md]]
* @example
* Push new information to a live feed:
* ```js
* const intercept = laika.intercept({operationName: 'getActiveUsersCount'});
* await intercept.waitForActiveSubscription();
* intercept.fireSubscriptionUpdate(
* {result: {data: {count: 10}}},
* );
* // e.g. assert the count displayed on the page is in fact 10
* intercept.fireSubscriptionUpdate(
* {result: {data: {count: 0}}},
* );
* // e.g. assert the page shows "there are no active users currently on the page"
* ```
*/
fireSubscriptionUpdate(
resultOrFn: ResultOrFn,
fireMatcher?: Matcher,
): InterceptApi
/**
* Add a callback that will fire every time a component connects to the query (i.e. mounts).
* You may return a clean-up function which will be run when the query disconnects.
*/
onSubscribe(callback: OnSubscribeCallback): (() => void) | void
/**
* If you invoke this and do not setup any mocked results, your intercepted queries will not respond,
* i.e. hang in a "loading" state, until you fire the data event manually
* (e.g. in a custom callback defined in {@link InterceptApi.onSubscribe `onSubscribe(callback)`}.
*
* Does not affect `subscription` operations which will not reach the backend regardless of this setting (unless the `connectFutureLinksOrMitmFn` argument was set).
*
* Opposite of {@link InterceptApi.allowNetworkFallback `allowNetworkFallback()`}.
*/
disableNetworkFallback(): void
/**
* This restores the default behavior: both queries and mutations
* will be passed to future links (e.g. your backend) and back to the components.
*
* Does not affect `subscription` operations which will not reach the backend regardless of this setting (unless the `connectFutureLinksOrMitmFn` argument was set).
*
* Opposite of {@link InterceptApi.disableNetworkFallback `disableNetworkFallback()`}.
*/
allowNetworkFallback(): void
/**
* Resets the mock configuration to its initial state and reenables the intercept if disabled by {@link InterceptApi.mockRestore `mockRestore()`}.
*/
mockReset(): InterceptApi
/**
* Removes the intercept completely and re-establishes connectivity in current and _future_ intercepted operations.
* Note the word _future_. Any connections that were established prior to running this command,
* will not automatically switch over to other mocks. This will mostly affect subscriptions.
* Ideally, keep a reference to the original intercept throughout the duration of your session
* and simply `intercept.reset()` if you need to restore connectivity or setup a different scenario.
*/
mockRestore(): void
} | the_stack |
import { ISPLists, ISPListItems, ISPListItem } from './ISPList';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { ISimpleCarouselWebPartProps } from './ISimpleCarouselWebPartProps';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import MockHttpClient from './MockHttpClient';
/**
* @interface
* Service interface definition
*/
export interface ISPPicturesListService {
/**
* @function
* Gets the list of picture libs in the current SharePoint site
*/
getPictureLibs(): Promise<ISPLists>;
/**
* @function
* Gets the pictures from a SharePoint list
*/
getPictures(libId: string): Promise<ISPListItems>;
}
/**
* @class
* Service implementation to get list & list items from current SharePoint site
*/
export class SPPicturesListService implements ISPPicturesListService {
private context: IWebPartContext;
private props: ISimpleCarouselWebPartProps;
/**
* @function
* Service constructor
*/
constructor(_props: ISimpleCarouselWebPartProps, pageContext: IWebPartContext){
this.props = _props;
this.context = pageContext;
}
/**
* @function
* Gets the list of picture libs in the current SharePoint site
*/
public getPictureLibs(): Promise<ISPLists> {
if (Environment.type === EnvironmentType.Local) {
//If the running environment is local, load the data from the mock
return this.getPictureLibsFromMock();
}
else {
//If the running environment is SharePoint, request the lists REST service
//Gets only the list with BaseTemplate = 109 (picture libs)
return this.context.spHttpClient.get(
`${this.context.pageContext.web.absoluteUrl}/_api/lists?$select=Title,id,BaseTemplate&$filter=BaseTemplate%20eq%20109`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
});
}
}
/**
* @function
* Returns 3 fake SharePoint lists for the Mock mode
*/
private getPictureLibsFromMock(): Promise<ISPLists> {
return MockHttpClient.getLists(this.context.pageContext.web.absoluteUrl).then(() => {
const listData: ISPLists = {
value:
[
{ Title: 'Mock List One', Id: '1', BaseTemplate: '109' },
{ Title: 'Mock List Two', Id: '2', BaseTemplate: '109' },
{ Title: 'Mock List Three', Id: '3', BaseTemplate: '109' }
]
};
return listData;
}) as Promise<ISPLists>;
}
/**
* @function
* Gets the pictures from a SharePoint list
*/
public getPictures(queryUrl: string): Promise<ISPListItems> {
if (Environment.type === EnvironmentType.Local) {
//If the running environment is local, load the data from the mock
return this.getPicturesFromMock('1');
}
else {
//Request the SharePoint web service
return this.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
return response.json().then((responseFormated: any) => {
var formatedResponse: ISPListItems = { value: []};
//Fetchs the Json response to construct the final items list
responseFormated.value.map((object: any, i: number) => {
//Tests if the result is a file and not a folder
if (object['FileSystemObjectType'] == '0') {
var spListItem: ISPListItem = {
'ID': object["ID"],
'Title': object['Title'],
'Description': object['Description'],
'File': {
'Name': object['File']['Name'],
'ServerRelativeUrl': object['File']['ServerRelativeUrl']
}
};
//Creates the thumbnail item url from the Picture path
spListItem.File.ThumbnailServerUrl = this.getThumbnailUrl(spListItem.File.ServerRelativeUrl, spListItem.File.Name);
formatedResponse.value.push(spListItem);
}
});
return formatedResponse;
});
}) as Promise<ISPListItems>;
}
}
/**
* @function
* Gets the thumbnail picture url from the Picture name.
* In SharePoint pictures libs, the thumbnail url is formated as for example '/_t/10_jpg.jpg'
*/
private getThumbnailUrl(pictureUrl: string, pictureName: string): string {
if (pictureUrl == null || pictureUrl == '')
return '';
var thumbUrl: string = '';
thumbUrl = pictureUrl.replace(pictureName, '');
thumbUrl += "_t/";
thumbUrl += pictureName.replace(".", "_");
thumbUrl += ".jpg";
return thumbUrl;
}
/**
* @function
* Gets the pictures list from the mock. This function will return a
* different list of pics for the lib 1 & 2, and an empty list for the third.
*/
private getPicturesFromMock(libId: string): Promise<ISPListItems> {
return MockHttpClient.getListsItems(this.context.pageContext.web.absoluteUrl).then(() => {
var listData: ISPListItems = { value: []};
if (libId == '1') {
listData = {
value:
[
{
"ID": "1", "Title": "Barton Dam, Ann Arbor, Michigan", "Description": "",
"File":
{
"Name": "01.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/01.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/01.jpg"
}
},
{
"ID": "2", "Title": "Building Atlanta, Georgia", "Description": "",
"File":
{
"Name": "02.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/02.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/02.jpg"
}
},
{
"ID": "3", "Title": "Nice day for a swim", "Description": "",
"File":
{
"Name": "03.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/03.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/03.jpg"
}
},
{
"ID": "4", "Title": "The plants that never die", "Description": "",
"File":
{
"Name": "04.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/04.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/04.jpg"
}
},
{
"ID": "5", "Title": "Downtown Atlanta, Georgia", "Description": "",
"File":
{
"Name": "05.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/05.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/05.jpg"
}
},
{
"ID": "6", "Title": "Atlanta traffic", "Description": "",
"File":
{
"Name": "06.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/06.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/06.jpg"
}
},
{
"ID": "7", "Title": "A pathetic dog", "Description": "",
"File":
{
"Name": "07.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/07.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/07.jpg"
}
},
{
"ID": "8", "Title": "Two happy dogs", "Description": "",
"File":
{
"Name": "08.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/08.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/08.jpg"
}
},
{
"ID": "9", "Title": "Antigua, Guatemala", "Description": "",
"File":
{
"Name": "09.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/09.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/09.jpg"
}
},
{
"ID": "10", "Title": "Iximche, Guatemala", "Description": "",
"File":
{
"Name": "10.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/10.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/10.jpg"
}
}
]
};
}
else if (libId == '2') {
listData = {
value:
[
{
"ID": "11", "Title": "Barton Dam, Ann Arbor, Michigan", "Description": "",
"File":
{
"Name": "11.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/11.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/11.jpg"
}
},
{
"ID": "12", "Title": "Building Atlanta, Georgia", "Description": "",
"File":
{
"Name": "12.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/12.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/12.jpg"
}
},
{
"ID": "13", "Title": "Nice day for a swim", "Description": "",
"File":
{
"Name": "13.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/13.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/13.jpg"
}
},
{
"ID": "14", "Title": "The plants that never die", "Description": "",
"File":
{
"Name": "14.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/14.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/14.jpg"
}
},
{
"ID": "15", "Title": "Downtown Atlanta, Georgia", "Description": "",
"File":
{
"Name": "15.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/15.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/15.jpg"
}
},
{
"ID": "16", "Title": "Atlanta traffic", "Description": "",
"File":
{
"Name": "16.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/16.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/16.jpg"
}
},
{
"ID": "17", "Title": "A pathetic dog", "Description": "",
"File":
{
"Name": "17.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/17.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/17.jpg"
}
},
{
"ID": "18", "Title": "Two happy dogs", "Description": "",
"File":
{
"Name": "18.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/18.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/18.jpg"
}
},
{
"ID": "19", "Title": "Antigua, Guatemala", "Description": "",
"File":
{
"Name": "19.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/19.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/19.jpg"
}
},
{
"ID": "20", "Title": "Iximche, Guatemala", "Description": "",
"File":
{
"Name": "20.jpg",
"ServerRelativeUrl": "../src/webparts/photopile/images/fullsize/20.jpg",
"ThumbnailServerUrl": "../src/webparts/photopile/images/thumbs/20.jpg"
}
}
]
};
}
return listData;
}) as Promise<ISPListItems>;
}
} | the_stack |
/// <reference types="node" />
declare class Request {
private configure;
constructor(configure: {
host: string;
apiKey?: string | undefined;
accessToken?: string | undefined;
timeout?: number | undefined;
});
get<T>(path: string, params?: any): Promise<T>;
post<T>(path: string, params?: any): Promise<T>;
put<T>(path: string, params: any): Promise<T>;
patch<T>(path: string, params: any): Promise<T>;
delete<T>(path: string, params?: any): Promise<T>;
request(options: {
method: string;
path: string;
params?: Params | FormData | undefined;
}): Promise<Response>;
checkStatus(response: Response): Promise<Response>;
parseJSON<T>(response: Response): Promise<T>;
private toFormData(params);
private toQueryString(params);
webAppBaseURL: string;
restBaseURL: string;
}
type Params = {
[index: string]: number | string | number[] | string[];
};
export class Backlog extends Request {
constructor(configure: {
host: string;
apiKey?: string | undefined;
accessToken?: string | undefined;
timeout?: number | undefined;
});
getSpace(): Promise<any>;
getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise<any>;
getSpaceNotification(): Promise<any>;
putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise<any>;
getSpaceDiskUsage(): Promise<any>;
getSpaceIcon(): Promise<Entity.File.FileData>;
postSpaceAttachment(form: FormData): Promise<Response>;
getUsers(): Promise<any>;
getUser(userId: number): Promise<any>;
postUser(params: Option.User.PostUserParams): Promise<any>;
patchUser(userId: number, params: Option.User.PatchUserParams): Promise<any>;
deleteUser(userId: number): Promise<any>;
getMyself(): Promise<any>;
getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise<any>;
getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise<any>;
getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise<any>;
getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getUserIcon(userId: number): Promise<Entity.File.FileData>;
getGroups(params: Option.Group.GetGroupsParams): Promise<any>;
postGroups(params: Option.Group.PostGroupsParams): Promise<any>;
getGroup(groupId: number): Promise<any>;
patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise<any>;
deleteGroup(groupId: number): Promise<any>;
getStatuses(): Promise<any>;
getResolutions(): Promise<any>;
getPriorities(): Promise<any>;
postProject(params: Option.Project.PostProjectParams): Promise<any>;
getProjects(params?: Option.Project.GetProjectsParams): Promise<any>;
getProject(projectIdOrKey: string): Promise<any>;
patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise<any>;
deleteProject(projectIdOrKey: string): Promise<any>;
getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise<any>;
getProjectUsers(projectIdOrKey: string): Promise<any>;
deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise<any>;
postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise<any>;
getProjectAdministrators(projectIdOrKey: string): Promise<any>;
deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise<any>;
getIssueTypes(projectIdOrKey: string): Promise<any>;
postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise<any>;
patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise<any>;
deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise<any>;
getCategories(projectIdOrKey: string): Promise<any>;
postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise<any>;
patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise<any>;
deleteCategories(projectIdOrKey: string, id: number): Promise<any>;
getVersions(projectIdOrKey: string): Promise<any>;
postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise<any>;
patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise<any>;
deleteVersions(projectIdOrKey: string, id: number): Promise<any>;
getCustomFields(projectIdOrKey: string): Promise<any>;
postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise<any>;
patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise<any>;
deleteCustomField(projectIdOrKey: string, id: number): Promise<any>;
postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise<any>;
deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise<any>;
getProjectsDiskUsage(projectIdOrKey: string): Promise<any>;
getWebhooks(projectIdOrKey: string): Promise<any>;
postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise<any>;
getWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise<any>;
deleteWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
postIssue(params: Option.Issue.PostIssueParams): Promise<any>;
patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise<any>;
getIssues(params?: Option.Issue.GetIssuesParams): Promise<any>;
getIssue(issueIdOrKey: string): Promise<any>;
getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise<any>;
deleteIssuesCount(issueIdOrKey: string): Promise<any>;
getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise<any>;
postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise<any>;
getIssueCommentsCount(issueIdOrKey: string): Promise<any>;
getIssueComment(issueIdOrKey: string, commentId: number): Promise<any>;
patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise<any>;
getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise<any>;
postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise<any>;
getIssueAttachments(issueIdOrKey: string): Promise<any>;
deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise<any>;
getIssueSharedFiles(issueIdOrKey: string): Promise<any>;
linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise<any>;
unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise<any>;
getWikis(projectIdOrKey: number): Promise<any>;
getWikisCount(projectIdOrKey: number): Promise<any>;
getWikisTags(projectIdOrKey: number): Promise<any>;
postWiki(params: Option.Wiki.PostWikiParams): Promise<any>;
getWiki(wikiId: number): Promise<any>;
patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise<any>;
deleteWiki(wikiId: number, mailNotify: boolean): Promise<any>;
getWikisAttachments(wikiId: number): Promise<any>;
postWikisAttachments(wikiId: number, attachmentId: number[]): Promise<any>;
deleteWikisAttachments(wikiId: number, attachmentId: number): Promise<any>;
getWikisSharedFiles(wikiId: number): Promise<any>;
linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise<any>;
unlinkWikisSharedFiles(wikiId: number, id: number): Promise<any>;
getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise<any>;
getWikisStars(wikiId: number): Promise<any>;
postStar(params: Option.Project.PostStarParams): Promise<any>;
getNotifications(params: Option.Notification.GetNotificationsParams): Promise<any>;
getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise<any>;
resetNotificationsMarkAsRead(): Promise<any>;
markAsReadNotification(id: number): Promise<any>;
getGitRepositories(projectIdOrKey: string): Promise<any>;
getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise<any>;
getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise<any>;
getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise<any>;
getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise<any>;
postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise<any>;
getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise<any>;
getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<any>;
getProjectIcon(projectIdOrKey: string): Promise<Entity.File.FileData>;
getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise<Entity.File.FileData>;
getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise<Entity.File.FileData>;
getWikiAttachment(wikiId: number, attachmentId: number): Promise<Entity.File.FileData>;
getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<Entity.File.FileData>;
private download(path);
private upload(path, params);
private parseFileData(response);
}
export class OAuth2 {
private credentials;
private timeout;
constructor(credentials: Option.OAuth2.Credentials, timeout?: number);
getAuthorizationURL(options: {
host: string;
redirectUri?: string | undefined;
state?: string | undefined;
}): string;
getAccessToken(options: {
host: string;
code: string;
redirectUri?: string | undefined;
}): Promise<Entity.OAuth2.AccessToken>;
refreshAccessToken(options: {
host: string;
refreshToken: string;
}): Promise<Entity.OAuth2.AccessToken>;
}
import { PassThrough } from 'stream';
export namespace Entity {
export namespace File {
export type FileData = NodeFileData | BrowserFileData;
export interface NodeFileData {
body: PassThrough;
url: string;
filename: string;
}
export interface BrowserFileData {
body: any;
url: string;
blob?: (() => Promise<Blob>) | undefined;
}
}
export namespace OAuth2 {
export interface AccessToken {
access_token: string;
token_type: string;
expires_in: number;
refresh_token: string;
}
}
}
export namespace Option {
export type Order = "asc" | "desc";
export enum ActivityType {
Undefined = -1,
IssueCreated = 1,
IssueUpdated = 2,
IssueCommented = 3,
IssueDeleted = 4,
WikiCreated = 5,
WikiUpdated = 6,
WikiDeleted = 7,
FileAdded = 8,
FileUpdated = 9,
FileDeleted = 10,
SvnCommitted = 11,
GitPushed = 12,
GitRepositoryCreated = 13,
IssueMultiUpdated = 14,
ProjectUserAdded = 15,
ProjectUserRemoved = 16,
NotifyAdded = 17,
PullRequestAdded = 18,
PullRequestUpdated = 19,
PullRequestCommented = 20,
PullRequestMerged = 21,
}
export namespace Notification {
export interface GetNotificationsParams {
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface GetNotificationsCountParams {
alreadyRead: boolean;
resourceAlreadyRead: boolean;
}
}
export namespace Space {
export interface GetActivitiesParams {
activityTypeId?: ActivityType[] | undefined;
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface PutSpaceNotificationParams {
content: string;
}
}
export namespace User {
export interface PostUserParams {
userId: string;
password: string;
name: string;
mailAddress: string;
roleType: RoleType;
}
export interface PatchUserParams {
password?: string | undefined;
name?: string | undefined;
mailAddress?: string | undefined;
roleType?: RoleType | undefined;
}
export enum RoleType {
Admin = 1,
User = 2,
Reporter = 3,
Viewer = 4,
GuestReporter = 5,
GuestViewer = 6,
}
export interface GetUserActivitiesParams {
activityTypeId?: ActivityType[] | undefined;
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface GetUserStarsParams {
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface GetUserStarsCountParams {
since?: string | undefined;
until?: string | undefined;
}
export interface GetRecentlyViewedParams {
order?: Order | undefined;
offset?: number | undefined;
count?: number | undefined;
}
}
export namespace Group {
export interface GetGroupsParams {
order?: Order | undefined;
offset?: number | undefined;
count?: number | undefined;
}
export interface PostGroupsParams {
name: string;
members?: string[] | undefined;
}
export interface PatchGroupParams {
name?: string | undefined;
members?: string[] | undefined;
}
}
export namespace Project {
export type TextFormattingRule = "backlog" | "markdown";
export interface PostProjectParams {
name: string;
key: string;
chartEnabled: boolean;
projectLeaderCanEditProjectLeader?: boolean | undefined;
subtaskingEnabled: boolean;
textFormattingRule: TextFormattingRule;
}
export interface PatchProjectParams {
name?: string | undefined;
key?: string | undefined;
chartEnabled?: boolean | undefined;
subtaskingEnabled?: boolean | undefined;
projectLeaderCanEditProjectLeader?: boolean | undefined;
textFormattingRule?: TextFormattingRule | undefined;
archived?: boolean | undefined;
}
export interface GetProjectsParams {
archived?: boolean | undefined;
all?: boolean | undefined;
}
export interface DeleteProjectUsersParams {
userId: number;
}
export interface PostProjectAdministrators {
userId: number;
}
export interface DeleteProjectAdministrators {
userId: number;
}
export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665";
export interface PostIssueTypeParams {
name: string;
color: IssueTypeColor;
}
export interface PatchIssueTypeParams {
name?: string | undefined;
color?: IssueTypeColor | undefined;
}
export interface DeleteIssueTypeParams {
substituteIssueTypeId: number;
}
export interface PostCategoriesParams {
name: string;
}
export interface PatchCategoriesParams {
name: string;
}
export interface PostVersionsParams {
name: string;
description: string;
startDate: string;
releaseDueDate: string;
}
export interface PatchVersionsParams {
name: string;
description?: string | undefined;
startDate?: string | undefined;
releaseDueDate?: string | undefined;
archived?: boolean | undefined;
}
export interface PostCustomFieldParams {
typeId: FieldType;
name: string;
applicableIssueTypes?: number[] | undefined;
description?: string | undefined;
required?: boolean | undefined;
}
export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams {
min?: number | undefined;
max?: number | undefined;
initialValue?: number | undefined;
unit?: string | undefined;
}
export interface PostCustomFieldWithDateParams extends PostCustomFieldParams {
min?: string | undefined;
max?: string | undefined;
initialValueType?: number | undefined;
initialDate?: string | undefined;
initialShift?: number | undefined;
}
export interface PostCustomFieldWithListParams extends PostCustomFieldParams {
items?: string[] | undefined;
allowInput?: boolean | undefined;
allowAddItem?: boolean | undefined;
}
export interface PatchCustomFieldParams {
name?: string | undefined;
applicableIssueTypes?: number[] | undefined;
description?: string | undefined;
required?: boolean | undefined;
}
export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams {
min?: number | undefined;
max?: number | undefined;
initialValue?: number | undefined;
unit?: string | undefined;
}
export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams {
min?: string | undefined;
max?: string | undefined;
initialValueType?: number | undefined;
initialDate?: string | undefined;
initialShift?: number | undefined;
}
export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams {
items?: string[] | undefined;
allowInput?: boolean | undefined;
allowAddItem?: boolean | undefined;
}
export interface PostCustomFieldItemParams {
name: string;
}
export interface PatchCustomFieldItemParams {
name: string;
}
export interface GetSharedFilesParams {
order?: Order | undefined;
offset?: number | undefined;
count?: number | undefined;
}
export interface PostWebhookParams {
name?: string | undefined;
description?: string | undefined;
hookUrl?: string | undefined;
allEvent?: boolean | undefined;
activityTypeIds?: number[] | undefined;
}
export interface PatchWebhookParams {
name?: string | undefined;
description?: string | undefined;
hookUrl?: string | undefined;
allEvent?: boolean | undefined;
activityTypeIds?: number[] | undefined;
}
export enum FieldType {
Text = 1,
TextArea = 2,
Numeric = 3,
Date = 4,
SingleList = 5,
MultipleList = 6,
CheckBox = 7,
Radio = 8,
}
export interface PostStarParams {
issueId?: number | undefined;
commentId?: number | undefined;
wikiId?: number | undefined;
pullRequestId?: number | undefined;
pullRequestCommentId?: number | undefined;
}
}
export namespace Issue {
export interface PostIssueParams {
projectId: number;
summary: string;
priorityId: number;
issueTypeId: number;
parentIssueId?: number | undefined;
description?: string | undefined;
startDate?: string | undefined;
dueDate?: string | undefined;
estimatedHours?: number | undefined;
actualHours?: number | undefined;
categoryId?: number[] | undefined;
versionId?: number[] | undefined;
milestoneId?: number[] | undefined;
assigneeId?: number | undefined;
notifiedUserId?: number[] | undefined;
attachmentId?: number[] | undefined;
[customField_: string]: any;
}
export interface PatchIssueParams {
summary?: string | undefined;
parentIssueId?: number | undefined;
description?: string | undefined;
statusId?: number | undefined;
resolutionId?: number | undefined;
startDate?: string | undefined;
dueDate?: string | undefined;
estimatedHours?: number | undefined;
actualHours?: number | undefined;
issueTypeId?: number | undefined;
categoryId?: number[] | undefined;
versionId?: number[] | undefined;
milestoneId?: number[] | undefined;
priorityId?: number | undefined;
assigneeId?: number | undefined;
notifiedUserId?: number[] | undefined;
attachmentId?: number[] | undefined;
comment?: string | undefined;
[customField_: string]: any;
}
export interface GetIssuesParams {
projectId?: number[] | undefined;
issueTypeId?: number[] | undefined;
categoryId?: number[] | undefined;
versionId?: number[] | undefined;
milestoneId?: number[] | undefined;
statusId?: number[] | undefined;
priorityId?: number[] | undefined;
assigneeId?: number[] | undefined;
createdUserId?: number[] | undefined;
resolutionId?: number[] | undefined;
parentChild?: ParentChildType | undefined;
attachment?: boolean | undefined;
sharedFile?: boolean | undefined;
sort?: SortKey | undefined;
order?: Order | undefined;
offset?: number | undefined;
count?: number | undefined;
createdSince?: string | undefined;
createdUntil?: string | undefined;
updatedSince?: string | undefined;
updatedUntil?: string | undefined;
startDateSince?: string | undefined;
startDateUntil?: string | undefined;
dueDateSince?: string | undefined;
dueDateUntil?: string | undefined;
id?: number[] | undefined;
parentIssueId?: number[] | undefined;
keyword: string;
[customField_: string]: any;
}
export enum ParentChildType {
All = 0,
NotChild = 1,
Child = 2,
NotChildNotParent = 3,
Parent = 4,
}
export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue";
export interface GetIssueCommentsParams {
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface PostIssueCommentsParams {
content: string;
notifiedUserId?: number[] | undefined;
attachmentId?: number[] | undefined;
}
export interface PatchIssueCommentParams {
content: string;
}
export interface IssueCommentNotifications {
notifiedUserId: number[];
}
export interface LinkIssueSharedFilesParams {
fileId: number[];
}
}
export namespace PullRequest {
export interface GetPullRequestsParams {
statusId?: number[] | undefined;
assigneeId?: number[] | undefined;
issueId?: number[] | undefined;
createdUserId?: number[] | undefined;
offset?: number | undefined;
count?: number | undefined;
}
export interface PostPullRequestParams {
summary: string;
description: string;
base: string;
branch: string;
issueId?: number | undefined;
assigneeId?: number | undefined;
notifiedUserId?: number[] | undefined;
attachmentId?: number[] | undefined;
}
export interface PatchPullRequestParams {
summary?: string | undefined;
description?: string | undefined;
issueId?: number | undefined;
assigneeId?: number | undefined;
notifiedUserId?: number[] | undefined;
comment?: string[] | undefined;
}
export interface GetPullRequestCommentsParams {
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
export interface PostPullRequestCommentsParams {
content: string;
notifiedUserId?: number[] | undefined;
}
export interface PatchPullRequestCommentsParams {
content: string;
}
}
export namespace Wiki {
export interface PostWikiParams {
projectId: number;
name: string;
content: string;
mailNotify?: boolean | undefined;
}
export interface PatchWikiParams {
name?: string | undefined;
content?: string | undefined;
mailNotify?: boolean | undefined;
}
export interface GetWikisHistoryParams {
minId?: number | undefined;
maxId?: number | undefined;
count?: number | undefined;
order?: Order | undefined;
}
}
export namespace OAuth2 {
export interface Credentials {
clientId: string;
clientSecret: string;
}
}
}
export namespace Error {
export class BacklogError extends global.Error {
private _name;
private _url;
private _status;
private _body;
private _response;
constructor(name: BacklogErrorNameType, response: Response, body?: {
errors: BacklogErrorMessage[];
});
name: BacklogErrorNameType;
url: string;
status: number;
body: {
errors: BacklogErrorMessage[];
};
response: Response;
}
export class BacklogApiError extends BacklogError {
constructor(response: Response, body?: {
errors: BacklogErrorMessage[];
});
}
export class BacklogAuthError extends BacklogError {
constructor(response: Response, body?: {
errors: BacklogErrorMessage[];
});
}
export class UnexpectedError extends BacklogError {
constructor(response: Response);
}
export interface BacklogErrorMessage {
message: string;
code: number;
errorInfo: string;
moreInfo: string;
}
export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError';
} | the_stack |
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import IHttpClient from '../IHttpClient';
import { inject, injectable } from 'inversify';
import { IAPIConfiguration } from '../IAPIConfiguration';
import { Headers } from '../Headers';
import HttpResponse from '../HttpResponse';
import { ApiResponse } from '../model/apiResponse';
import { Pet } from '../model/pet';
import { COLLECTION_FORMATS } from '../variables';
@injectable()
export class PetService {
private basePath: string = 'http://petstore.swagger.io/v2';
constructor(@inject('IApiHttpClient') private httpClient: IHttpClient,
@inject('IAPIConfiguration') private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, observe?: 'body', headers?: Headers): Observable<any>;
public addPet(body: Pet, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public addPet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (body === null || body === undefined){
throw new Error('Required parameter body was null or undefined when calling addPet.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/pet`, body , headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <any>(httpResponse.response))
);
}
return response;
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, observe?: 'body', headers?: Headers): Observable<any>;
public deletePet(petId: number, apiKey?: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public deletePet(petId: number, apiKey?: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (petId === null || petId === undefined){
throw new Error('Required parameter petId was null or undefined when calling deletePet.');
}
if (apiKey) {
headers['api_key'] = String(apiKey);
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <any>(httpResponse.response))
);
}
return response;
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', headers?: Headers): Observable<Array<Pet>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', headers?: Headers): Observable<HttpResponse<Array<Pet>>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (status === null || status === undefined){
throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.');
}
let queryParameters: string[] = [];
if (status) {
queryParameters.push('status='+encodeURIComponent(status.join(COLLECTION_FORMATS['csv'])));
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml, application/json';
const response: Observable<HttpResponse<Array<Pet>>> = this.httpClient.get(`${this.basePath}/pet/findByStatus?${queryParameters.join('&')}`, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <Array<Pet>>(httpResponse.response))
);
}
return response;
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, observe?: 'body', headers?: Headers): Observable<Array<Pet>>;
public findPetsByTags(tags: Array<string>, observe?: 'response', headers?: Headers): Observable<HttpResponse<Array<Pet>>>;
public findPetsByTags(tags: Array<string>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (tags === null || tags === undefined){
throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.');
}
let queryParameters: string[] = [];
if (tags) {
queryParameters.push('tags='+encodeURIComponent(tags.join(COLLECTION_FORMATS['csv'])));
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml, application/json';
const response: Observable<HttpResponse<Array<Pet>>> = this.httpClient.get(`${this.basePath}/pet/findByTags?${queryParameters.join('&')}`, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <Array<Pet>>(httpResponse.response))
);
}
return response;
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
*/
public getPetById(petId: number, observe?: 'body', headers?: Headers): Observable<Pet>;
public getPetById(petId: number, observe?: 'response', headers?: Headers): Observable<HttpResponse<Pet>>;
public getPetById(petId: number, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (petId === null || petId === undefined){
throw new Error('Required parameter petId was null or undefined when calling getPetById.');
}
// authentication (api_key) required
if (this.APIConfiguration.apiKeys && this.APIConfiguration.apiKeys['api_key']) {
headers['api_key'] = this.APIConfiguration.apiKeys['api_key'];
}
headers['Accept'] = 'application/xml, application/json';
const response: Observable<HttpResponse<Pet>> = this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <Pet>(httpResponse.response))
);
}
return response;
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, observe?: 'body', headers?: Headers): Observable<any>;
public updatePet(body: Pet, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public updatePet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (body === null || body === undefined){
throw new Error('Required parameter body was null or undefined when calling updatePet.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.put(`${this.basePath}/pet`, body , headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <any>(httpResponse.response))
);
}
return response;
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', headers?: Headers): Observable<any>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (petId === null || petId === undefined){
throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
let formData: FormData = new FormData();
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
if (name !== undefined) {
formData.append('name', <any>name);
}
if (status !== undefined) {
formData.append('status', <any>status);
}
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, formData, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <any>(httpResponse.response))
);
}
return response;
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', headers?: Headers): Observable<ApiResponse>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', headers?: Headers): Observable<HttpResponse<ApiResponse>>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (petId === null || petId === undefined){
throw new Error('Required parameter petId was null or undefined when calling uploadFile.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
let formData: FormData = new FormData();
headers['Content-Type'] = 'multipart/form-data';
if (additionalMetadata !== undefined) {
formData.append('additionalMetadata', <any>additionalMetadata);
}
if (file !== undefined) {
formData.append('file', <any>file);
}
const response: Observable<HttpResponse<ApiResponse>> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, formData, headers);
if (observe === 'body') {
return response.pipe(
map((httpResponse: HttpResponse) => <ApiResponse>(httpResponse.response))
);
}
return response;
}
} | the_stack |
import { spawn, ChildProcess, execSync } from "child_process";
import path from "path";
import vscode from "vscode";
import { attach, NeovimClient } from "neovim";
// eslint-disable-next-line import/no-extraneous-dependencies
import { createLogger, transports as loggerTransports } from "winston";
import { HighlightConfiguration } from "./highlight_provider";
import { CommandsController } from "./commands_controller";
import { ModeManager } from "./mode_manager";
import { BufferManager } from "./buffer_manager";
import { TypingManager } from "./typing_manager";
import { CursorManager } from "./cursor_manager";
import { Logger, LogLevel } from "./logger";
import { DocumentChangeManager } from "./document_change_manager";
import {
NeovimCommandProcessable,
NeovimExtensionRequestProcessable,
NeovimRangeCommandProcessable,
NeovimRedrawProcessable,
} from "./neovim_events_processable";
import { CommandLineManager } from "./command_line_manager";
import { StatusLineManager } from "./status_line_manager";
import { HighlightManager } from "./highlight_manager";
import { CustomCommandsManager } from "./custom_commands_manager";
import { findLastEvent } from "./utils";
import { MutlilineMessagesManager } from "./multiline_messages_manager";
interface RequestResponse {
send(resp: unknown, isError?: boolean): void;
}
export interface ControllerSettings {
neovimPath: string;
extensionPath: string;
highlightsConfiguration: HighlightConfiguration;
mouseSelection: boolean;
useWsl: boolean;
customInitFile: string;
neovimViewportWidth: number;
neovimViewportHeight: number;
textDecorationsAtTop: boolean;
revealCursorScrollLine: boolean;
logConf: {
level: "none" | "error" | "warn" | "debug";
logPath: string;
outputToConsole: boolean;
};
}
const LOG_PREFIX = "MainController";
export class MainController implements vscode.Disposable {
// to not deal with screenrow positioning, we set height to high value and scrolloff to value / 2. so screenrow will be always constant
// big scrolloff is needed to make sure that editor visible space will be always within virtual vim boundaries, regardless of current
// cursor positioning
private NEOVIM_WIN_HEIGHT = 201;
private NEOVIM_WIN_WIDTH = 1000;
private nvimProc: ChildProcess;
private client: NeovimClient;
private disposables: vscode.Disposable[] = [];
/**
* Neovim API states that multiple redraw batches could be sent following flush() after last batch
* Save current batch into temp variable
*/
private currentRedrawBatch: [string, ...unknown[]][] = [];
private logger!: Logger;
private settings: ControllerSettings;
private modeManager!: ModeManager;
private bufferManager!: BufferManager;
private changeManager!: DocumentChangeManager;
private typingManager!: TypingManager;
private cursorManager!: CursorManager;
private commandsController!: CommandsController;
private commandLineManager!: CommandLineManager;
private statusLineManager!: StatusLineManager;
private highlightManager!: HighlightManager;
private customCommandsManager!: CustomCommandsManager;
private multilineMessagesManager!: MutlilineMessagesManager;
public constructor(settings: ControllerSettings) {
this.settings = settings;
this.NEOVIM_WIN_HEIGHT = settings.neovimViewportHeight;
this.NEOVIM_WIN_WIDTH = settings.neovimViewportWidth;
if (!settings.neovimPath) {
throw new Error("Neovim path is not defined");
}
this.logger = new Logger(
LogLevel[settings.logConf.level],
settings.logConf.logPath,
settings.logConf.outputToConsole,
);
this.disposables.push(this.logger);
let extensionPath = settings.extensionPath;
if (settings.useWsl) {
// execSync returns a newline character at the end
extensionPath = execSync(`C:\\Windows\\system32\\wsl.exe wslpath '${extensionPath}'`).toString().trim();
}
// These paths get called inside WSL, they must be POSIX paths (forward slashes)
const neovimSupportScriptPath = path.posix.join(extensionPath, "vim", "vscode-neovim.vim");
const neovimOptionScriptPath = path.posix.join(extensionPath, "vim", "vscode-options.vim");
const workspaceFolder = vscode.workspace.workspaceFolders;
const cwd = workspaceFolder && workspaceFolder.length ? workspaceFolder[0].uri.fsPath : "~";
const args = [
"-N",
"--embed",
// load options after user config
"-c",
`source ${neovimOptionScriptPath}`,
// load support script before user config (to allow to rebind keybindings/commands)
"--cmd",
`source ${neovimSupportScriptPath}`,
"-c",
`cd ${cwd}`,
];
if (settings.useWsl) {
args.unshift(settings.neovimPath);
}
if (parseInt(process.env.NEOVIM_DEBUG || "", 10) === 1) {
args.push(
"-u",
"NONE",
"--listen",
`${process.env.NEOVIM_DEBUG_HOST || "127.0.0.1"}:${process.env.NEOVIM_DEBUG_PORT || 4000}`,
);
}
if (settings.customInitFile) {
args.push("-u", settings.customInitFile);
}
this.logger.debug(
`${LOG_PREFIX}: Spawning nvim, path: ${settings.neovimPath}, useWsl: ${
settings.useWsl
}, args: ${JSON.stringify(args)}`,
);
this.nvimProc = spawn(settings.useWsl ? "C:\\Windows\\system32\\wsl.exe" : settings.neovimPath, args, {});
this.nvimProc.on("close", (code) => {
this.logger.error(`${LOG_PREFIX}: Neovim exited with code: ${code}`);
});
this.nvimProc.on("error", (err) => {
this.logger.error(`${LOG_PREFIX}: Neovim spawn error: ${err.message}`);
});
this.logger.debug(`${LOG_PREFIX}: Attaching to neovim`);
this.client = attach({
proc: this.nvimProc,
options: {
logger: createLogger({
transports: [new loggerTransports.Console()],
level: "error",
exitOnError: false,
}),
},
});
}
public async init(): Promise<void> {
this.logger.debug(`${LOG_PREFIX}: Init`);
this.logger.debug(`${LOG_PREFIX}: Attaching to neovim notifications`);
this.client.on("disconnect", () => {
this.logger.error(`${LOG_PREFIX}: Neovim was disconnected`);
});
this.client.on("notification", this.onNeovimNotification);
this.client.on("request", this.handleCustomRequest);
await this.client.setClientInfo("vscode-neovim", { major: 0, minor: 1, patch: 0 }, "embedder", {}, {});
await this.checkNeovimVersion();
const channel = await this.client.channelId;
await this.client.setVar("vscode_channel", channel);
this.commandsController = new CommandsController(this.client, this.settings.revealCursorScrollLine);
this.disposables.push(this.commandsController);
this.modeManager = new ModeManager(this.logger, this.client);
this.disposables.push(this.modeManager);
this.bufferManager = new BufferManager(this.logger, this.client, {
neovimViewportHeight: 201,
neovimViewportWidth: 1000,
});
this.disposables.push(this.bufferManager);
this.highlightManager = new HighlightManager(this.logger, this.bufferManager, {
highlight: this.settings.highlightsConfiguration,
viewportHeight: this.settings.neovimViewportHeight,
textDecorationsAtTop: this.settings.textDecorationsAtTop,
});
this.disposables.push(this.highlightManager);
this.changeManager = new DocumentChangeManager(this.logger, this.client, this.bufferManager, this.modeManager);
this.disposables.push(this.changeManager);
this.cursorManager = new CursorManager(
this.logger,
this.client,
this.modeManager,
this.bufferManager,
this.changeManager,
{
mouseSelectionEnabled: this.settings.mouseSelection,
},
);
this.disposables.push(this.cursorManager);
this.typingManager = new TypingManager(this.logger, this.client, this.modeManager, this.changeManager);
this.disposables.push(this.typingManager);
this.commandLineManager = new CommandLineManager(this.logger, this.client);
this.disposables.push(this.commandLineManager);
this.statusLineManager = new StatusLineManager(this.logger, this.client);
this.disposables.push(this.statusLineManager);
this.customCommandsManager = new CustomCommandsManager(this.logger);
this.disposables.push(this.customCommandsManager);
this.multilineMessagesManager = new MutlilineMessagesManager(this.logger);
this.disposables.push(this.multilineMessagesManager);
this.logger.debug(`${LOG_PREFIX}: UIAttach`);
// !Attach after setup of notifications, otherwise we can get blocking call and stuck
await this.client.uiAttach(this.NEOVIM_WIN_WIDTH, this.NEOVIM_WIN_HEIGHT, {
rgb: true,
// override: true,
ext_cmdline: true,
ext_linegrid: true,
ext_hlstate: true,
ext_messages: true,
ext_multigrid: true,
ext_popupmenu: true,
ext_tabline: true,
ext_wildmenu: true,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
await this.bufferManager.forceResync();
await vscode.commands.executeCommand("setContext", "neovim.init", true);
this.logger.debug(`${LOG_PREFIX}: Init completed`);
}
public dispose(): void {
for (const d of this.disposables) {
d.dispose();
}
this.client.quit();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private onNeovimNotification = (method: string, events: [string, ...any[]]): void => {
// order matters here, modeManager should be processed first
const redrawManagers: NeovimRedrawProcessable[] = [
this.modeManager,
this.bufferManager,
this.cursorManager,
this.commandLineManager,
this.statusLineManager,
this.highlightManager,
this.multilineMessagesManager,
];
const extensionCommandManagers: NeovimExtensionRequestProcessable[] = [
this.modeManager,
this.changeManager,
this.commandsController,
this.bufferManager,
this.highlightManager,
this.cursorManager,
];
const vscodeComandManagers: NeovimCommandProcessable[] = [this.customCommandsManager];
const vscodeRangeCommandManagers: NeovimRangeCommandProcessable[] = [this.cursorManager];
if (method === "vscode-command") {
const [vscodeCommand, commandArgs] = events as [string, unknown[]];
vscodeComandManagers.forEach(async (m) => {
try {
await m.handleVSCodeCommand(
vscodeCommand,
Array.isArray(commandArgs) ? commandArgs : [commandArgs],
);
} catch (e) {
this.logger.error(
`${vscodeCommand} failed, args: ${JSON.stringify(commandArgs)} error: ${(e as Error).message}`,
);
}
});
return;
}
if (method === "vscode-range-command") {
const [vscodeCommand, line1, line2, pos1, pos2, leaveSelection, args] = events;
vscodeRangeCommandManagers.forEach((m) => {
try {
m.handleVSCodeRangeCommand(
vscodeCommand,
line1,
line2,
pos1,
pos2,
!!leaveSelection,
Array.isArray(args) ? args : [args],
);
} catch (e) {
this.logger.error(
`${vscodeCommand} failed, range: [${line1}, ${line2}, ${pos1}, ${pos2}] args: ${JSON.stringify(
args,
)} error: ${(e as Error).message}`,
);
}
});
return;
}
if (method === "vscode-neovim") {
const [command, args] = events;
extensionCommandManagers.forEach((m) => {
try {
m.handleExtensionRequest(command, args);
} catch (e) {
this.logger.error(
`${command} failed, args: ${JSON.stringify(args)} error: ${(e as Error).message}`,
);
}
});
return;
}
if (method !== "redraw") {
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const redrawEvents = events as [string, ...any[]][];
const hasFlush = findLastEvent("flush", events);
if (hasFlush) {
const batch = [...this.currentRedrawBatch.splice(0), ...redrawEvents];
redrawManagers.forEach((m) => m.handleRedrawBatch(batch));
} else {
this.currentRedrawBatch.push(...redrawEvents);
}
};
private handleCustomRequest = async (
eventName: string,
eventArgs: [string, ...unknown[]],
response: RequestResponse,
): Promise<void> => {
const extensionCommandManagers: NeovimExtensionRequestProcessable[] = [
this.modeManager,
this.changeManager,
this.commandsController,
this.bufferManager,
this.highlightManager,
this.cursorManager,
];
const vscodeCommandManagers: NeovimCommandProcessable[] = [this.customCommandsManager];
const vscodeRangeCommandManagers: NeovimRangeCommandProcessable[] = [this.cursorManager];
try {
let result: unknown;
if (eventName === "vscode-command") {
const [vscodeCommand, commandArgs] = eventArgs as [string, unknown[]];
const results = await Promise.all(
vscodeCommandManagers.map((m) =>
m.handleVSCodeCommand(vscodeCommand, Array.isArray(commandArgs) ? commandArgs : [commandArgs]),
),
);
// use first non nullable result
result = results.find((r) => r != null);
} else if (eventName === "vscode-range-command") {
const [vscodeCommand, line1, line2, pos1, pos2, leaveSelection, commandArgs] = eventArgs as [
string,
number,
number,
number,
number,
number,
unknown[],
];
const results = await Promise.all(
vscodeRangeCommandManagers.map((m) =>
m.handleVSCodeRangeCommand(
vscodeCommand,
line1,
line2,
pos1,
pos2,
!!leaveSelection,
Array.isArray(commandArgs) ? commandArgs : [commandArgs],
),
),
);
// use first non nullable result
result = results.find((r) => r != null);
} else if (eventName === "vscode-neovim") {
const [command, commandArgs] = eventArgs as [string, unknown[]];
const results = await Promise.all(
extensionCommandManagers.map((m) => m.handleExtensionRequest(command, commandArgs)),
);
// use first non nullable result
result = results.find((r) => r != null);
}
response.send(result || "", false);
} catch (e) {
response.send((e as Error).message, true);
}
};
private async checkNeovimVersion(): Promise<void> {
const [, info] = await this.client.apiInfo;
if (
(info.version.major === 0 && info.version.minor < 5) ||
!info.ui_events.find((e) => e.name === "win_viewport")
) {
vscode.window.showErrorMessage("The extension requires neovim 0.5 nightly or greater");
return;
}
}
} | the_stack |
import Page = require('../../../../base/Page');
import Response = require('../../../../http/response');
import V1 = require('../../V1');
import { SerializableClass } from '../../../../interfaces';
type CustomerProfilesEvaluationsStatus = 'compliant'|'noncompliant';
/**
* Initialize the CustomerProfilesEvaluationsList
*
* @param version - Version of the resource
* @param customerProfileSid - The unique string that identifies the resource
*/
declare function CustomerProfilesEvaluationsList(version: V1, customerProfileSid: string): CustomerProfilesEvaluationsListInstance;
interface CustomerProfilesEvaluationsListInstance {
/**
* @param sid - sid of instance
*/
(sid: string): CustomerProfilesEvaluationsContext;
/**
* create a CustomerProfilesEvaluationsInstance
*
* @param opts - Options for request
* @param callback - Callback to handle processed record
*/
create(opts: CustomerProfilesEvaluationsListInstanceCreateOptions, callback?: (error: Error | null, item: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance>;
/**
* Streams CustomerProfilesEvaluationsInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Function to process each record
*/
each(callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void;
/**
* Streams CustomerProfilesEvaluationsInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Function to process each record
*/
each(opts?: CustomerProfilesEvaluationsListInstanceEachOptions, callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void): void;
/**
* Constructs a customer_profiles_evaluations
*
* @param sid - The unique string that identifies the Evaluation resource
*/
get(sid: string): CustomerProfilesEvaluationsContext;
/**
* Retrieve a single target page of CustomerProfilesEvaluationsInstance records
* from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
getPage(callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>;
/**
* Retrieve a single target page of CustomerProfilesEvaluationsInstance records
* from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param targetUrl - API-generated URL for the requested results page
* @param callback - Callback to handle list of records
*/
getPage(targetUrl?: string, callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>;
/**
* Lists CustomerProfilesEvaluationsInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
list(callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance[]) => any): Promise<CustomerProfilesEvaluationsInstance[]>;
/**
* Lists CustomerProfilesEvaluationsInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
list(opts?: CustomerProfilesEvaluationsListInstanceOptions, callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance[]) => any): Promise<CustomerProfilesEvaluationsInstance[]>;
/**
* Retrieve a single page of CustomerProfilesEvaluationsInstance records from the
* API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param callback - Callback to handle list of records
*/
page(callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>;
/**
* Retrieve a single page of CustomerProfilesEvaluationsInstance records from the
* API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @param opts - Options for request
* @param callback - Callback to handle list of records
*/
page(opts?: CustomerProfilesEvaluationsListInstancePageOptions, callback?: (error: Error | null, items: CustomerProfilesEvaluationsPage) => any): Promise<CustomerProfilesEvaluationsPage>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
/**
* Options to pass to create
*
* @property policySid - The unique string of a policy
*/
interface CustomerProfilesEvaluationsListInstanceCreateOptions {
policySid: string;
}
/**
* Options to pass to each
*
* @property callback -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @property done - Function to be called upon completion of streaming
* @property limit -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
*/
interface CustomerProfilesEvaluationsListInstanceEachOptions {
callback?: (item: CustomerProfilesEvaluationsInstance, done: (err?: Error) => void) => void;
done?: Function;
limit?: number;
pageSize?: number;
}
/**
* Options to pass to list
*
* @property limit -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @property pageSize -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
*/
interface CustomerProfilesEvaluationsListInstanceOptions {
limit?: number;
pageSize?: number;
}
/**
* Options to pass to page
*
* @property pageNumber - Page Number, this value is simply for client state
* @property pageSize - Number of records to return, defaults to 50
* @property pageToken - PageToken provided by the API
*/
interface CustomerProfilesEvaluationsListInstancePageOptions {
pageNumber?: number;
pageSize?: number;
pageToken?: string;
}
interface CustomerProfilesEvaluationsPayload extends CustomerProfilesEvaluationsResource, Page.TwilioResponsePayload {
}
interface CustomerProfilesEvaluationsResource {
account_sid: string;
customer_profile_sid: string;
date_created: Date;
policy_sid: string;
results: object[];
sid: string;
status: CustomerProfilesEvaluationsStatus;
url: string;
}
interface CustomerProfilesEvaluationsSolution {
customerProfileSid?: string;
}
declare class CustomerProfilesEvaluationsContext {
/**
* Initialize the CustomerProfilesEvaluationsContext
*
* @param version - Version of the resource
* @param customerProfileSid - The unique string that identifies the resource
* @param sid - The unique string that identifies the Evaluation resource
*/
constructor(version: V1, customerProfileSid: string, sid: string);
/**
* fetch a CustomerProfilesEvaluationsInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance>;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
declare class CustomerProfilesEvaluationsInstance extends SerializableClass {
/**
* Initialize the CustomerProfilesEvaluationsContext
*
* @param version - Version of the resource
* @param payload - The instance payload
* @param customerProfileSid - The unique string that identifies the resource
* @param sid - The unique string that identifies the Evaluation resource
*/
constructor(version: V1, payload: CustomerProfilesEvaluationsPayload, customerProfileSid: string, sid: string);
private _proxy: CustomerProfilesEvaluationsContext;
accountSid: string;
customerProfileSid: string;
dateCreated: Date;
/**
* fetch a CustomerProfilesEvaluationsInstance
*
* @param callback - Callback to handle processed record
*/
fetch(callback?: (error: Error | null, items: CustomerProfilesEvaluationsInstance) => any): Promise<CustomerProfilesEvaluationsInstance>;
policySid: string;
results: object[];
sid: string;
status: CustomerProfilesEvaluationsStatus;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
url: string;
}
declare class CustomerProfilesEvaluationsPage extends Page<V1, CustomerProfilesEvaluationsPayload, CustomerProfilesEvaluationsResource, CustomerProfilesEvaluationsInstance> {
/**
* Initialize the CustomerProfilesEvaluationsPage
*
* @param version - Version of the resource
* @param response - Response from the API
* @param solution - Path solution
*/
constructor(version: V1, response: Response<string>, solution: CustomerProfilesEvaluationsSolution);
/**
* Build an instance of CustomerProfilesEvaluationsInstance
*
* @param payload - Payload response from the API
*/
getInstance(payload: CustomerProfilesEvaluationsPayload): CustomerProfilesEvaluationsInstance;
/**
* Provide a user-friendly representation
*/
toJSON(): any;
}
export { CustomerProfilesEvaluationsContext, CustomerProfilesEvaluationsInstance, CustomerProfilesEvaluationsList, CustomerProfilesEvaluationsListInstance, CustomerProfilesEvaluationsListInstanceCreateOptions, CustomerProfilesEvaluationsListInstanceEachOptions, CustomerProfilesEvaluationsListInstanceOptions, CustomerProfilesEvaluationsListInstancePageOptions, CustomerProfilesEvaluationsPage, CustomerProfilesEvaluationsPayload, CustomerProfilesEvaluationsResource, CustomerProfilesEvaluationsSolution, CustomerProfilesEvaluationsStatus } | the_stack |
import { Row, RowKey } from '@t/store/data';
import { Store } from '@t/store';
import { OptRow, OptAppendTreeRow, OptMoveRow } from '@t/options';
import { Column, ColumnInfo } from '@t/store/column';
import { ColumnCoords } from '@t/store/columnCoords';
import { Dimension } from '@t/store/dimension';
import { createViewRow } from '../store/data';
import {
getRowHeight,
findIndexByRowKey,
findRowByRowKey,
getLoadingState,
isSorted,
isFiltered,
} from '../query/data';
import { notify, batchObserver, getOriginObject, Observable } from '../helper/observable';
import { getDataManager } from '../instance';
import {
isUpdatableRowAttr,
setLoadingState,
updateRowNumber,
setCheckedAllRows,
uncheck,
} from './data';
import {
getParentRow,
getDescendantRows,
getStartIndexToAppendRow,
traverseAncestorRows,
traverseDescendantRows,
getChildRowKeys,
isLeaf,
isExpanded,
isRootChildRow,
getDepth,
} from '../query/tree';
import { getEventBus } from '../event/eventBus';
import GridEvent from '../event/gridEvent';
import { flattenTreeData, getTreeIndentWidth } from '../store/helper/tree';
import { findProp, findPropIndex, removeArrayItem, some, silentSplice } from '../helper/common';
import { cls, getTextWidth } from '../helper/dom';
import { fillMissingColumnData } from './lazyObservable';
import { getColumnSide } from '../query/column';
import { createFormattedValue } from '../store/helper/data';
import { TREE_CELL_HORIZONTAL_PADDING } from '../helper/constant';
import { setAutoResizingColumnWidths } from './column';
interface TriggerByMovingRow {
movingRow?: boolean;
}
function changeExpandedAttr(row: Row, expanded: boolean) {
const { tree } = row._attributes;
if (tree) {
row._attributes.expanded = expanded;
tree.expanded = expanded;
}
}
function changeHiddenAttr(row: Row, hidden: boolean) {
const { tree } = row._attributes;
if (tree) {
tree.hidden = hidden;
}
}
function expand(store: Store, row: Row, recursive?: boolean) {
const { rowKey } = row;
const eventBus = getEventBus(store.id);
const gridEvent = new GridEvent({ rowKey });
/**
* Occurs when the row having child rows is expanded
* @event Grid#expand
* @type {module:event/gridEvent}
* @property {number|string} rowKey - rowKey of the expanded row
* @property {Grid} instance - Current grid instance
*/
eventBus.trigger('expand', gridEvent);
if (gridEvent.isStopped()) {
return;
}
const { data, rowCoords, dimension, column, id, viewport, columnCoords } = store;
const { heights } = rowCoords;
changeExpandedAttr(row, true);
const childRowKeys = getChildRowKeys(row);
updateTreeColumnWidth(childRowKeys, column, columnCoords, dimension, data.rawData);
childRowKeys.forEach((childRowKey) => {
const childRow = findRowByRowKey(data, column, id, childRowKey);
if (!childRow) {
return;
}
changeHiddenAttr(childRow, false);
if (!isLeaf(childRow) && (isExpanded(childRow) || recursive)) {
expand(store, childRow, recursive);
}
const index = findIndexByRowKey(data, column, id, childRowKey);
heights[index] = getRowHeight(childRow, dimension.rowHeight);
});
if (childRowKeys.length) {
notify(rowCoords, 'heights');
notify(viewport, 'rowRange');
}
}
function updateTreeColumnWidth(
childRowKeys: RowKey[],
column: Column,
columnCoords: ColumnCoords,
dimension: Dimension,
rawData: Row[]
) {
const { visibleColumnsBySideWithRowHeader, treeIcon, allColumnMap, treeIndentWidth } = column;
const treeColumnName = column.treeColumnName!;
const treeColumnSide = getColumnSide(column, treeColumnName);
const treeColumnIndex = findPropIndex(
'name',
treeColumnName,
column.visibleColumnsBySide[treeColumnSide]
);
const columnInfo = visibleColumnsBySideWithRowHeader[treeColumnSide][treeColumnIndex];
// @TODO: auto resizing is operated with 'autoResizing' option
// 'resizable' condition should be deprecated in next version
if (columnInfo.resizable || columnInfo.autoResizing) {
const maxWidth = getChildTreeNodeMaxWidth(
childRowKeys,
rawData,
columnInfo,
treeIndentWidth,
treeIcon
);
const prevWidth =
columnCoords.widths[treeColumnSide][treeColumnIndex] + dimension.cellBorderWidth;
allColumnMap[treeColumnName].baseWidth = Math.max(prevWidth, maxWidth);
allColumnMap[treeColumnName].fixedWidth = true;
}
}
function getChildTreeNodeMaxWidth(
childRowKeys: RowKey[],
rawData: Row[],
column: ColumnInfo,
treeIndentWidth?: number,
useIcon?: boolean
) {
let maxLength = 0;
const bodyArea = document.querySelector(
`.${cls('rside-area')} .${cls('body-container')} .${cls('table')}`
) as HTMLElement;
const getMaxWidth = childRowKeys.reduce(
(acc: () => number, rowKey) => {
const row = findProp('rowKey', rowKey, rawData)!;
const formattedValue = createFormattedValue(row, column);
if (formattedValue.length > maxLength) {
maxLength = formattedValue.length;
acc = () =>
getTextWidth(formattedValue, bodyArea) +
getTreeIndentWidth(getDepth(rawData, row), treeIndentWidth, useIcon) +
TREE_CELL_HORIZONTAL_PADDING;
}
return acc;
},
() => 0
);
return getMaxWidth();
}
function collapse(store: Store, row: Row, recursive?: boolean) {
const { rowKey } = row;
const eventBus = getEventBus(store.id);
const gridEvent = new GridEvent({ rowKey });
/**
* Occurs when the row having child rows is collapsed
* @event Grid#collapse
* @type {module:event/gridEvent}
* @property {number|string} rowKey - rowKey of the collapsed row
* @property {Grid} instance - Current grid instance
*/
eventBus.trigger('collapse', gridEvent);
if (gridEvent.isStopped()) {
return;
}
const { data, rowCoords, column, id } = store;
const { heights } = rowCoords;
changeExpandedAttr(row, false);
const childRowKeys = getChildRowKeys(row);
childRowKeys.forEach((childRowKey) => {
const childRow = findRowByRowKey(data, column, id, childRowKey);
if (!childRow) {
return;
}
changeHiddenAttr(childRow, true);
if (!isLeaf(childRow)) {
if (recursive) {
collapse(store, childRow, recursive);
} else {
getDescendantRows(store, childRowKey).forEach(({ rowKey: descendantRowKey }) => {
const index = findIndexByRowKey(data, column, id, descendantRowKey);
changeHiddenAttr(data.filteredRawData[index], true);
heights[index] = 0;
});
}
}
const index = findIndexByRowKey(data, column, id, childRowKey);
heights[index] = 0;
});
notify(rowCoords, 'heights');
}
function setCheckedState(row: Row, state: boolean) {
if (row && isUpdatableRowAttr('checked', row._attributes.checkDisabled)) {
row._attributes.checked = state;
}
}
function changeAncestorRowsCheckedState(store: Store, rowKey: RowKey) {
const { data, column, id } = store;
const { rawData } = data;
const row = findRowByRowKey(data, column, id, rowKey);
if (row) {
traverseAncestorRows(rawData, row, (parentRow: Row) => {
const childRowKeys = getChildRowKeys(parentRow);
const checkedChildRows = childRowKeys.filter((childRowKey) => {
const childRow = findRowByRowKey(data, column, id, childRowKey);
return !!childRow && childRow._attributes.checked;
});
const checked = childRowKeys.length === checkedChildRows.length;
setCheckedState(parentRow, checked);
});
}
}
function changeDescendantRowsCheckedState(store: Store, rowKey: RowKey, state: boolean) {
const { data, column, id } = store;
const { rawData } = data;
const row = findRowByRowKey(data, column, id, rowKey);
if (row) {
traverseDescendantRows(rawData, row, (childRow: Row) => {
setCheckedState(childRow, state);
});
}
}
function removeChildRowKey(row: Row, rowKey: RowKey) {
const { tree } = row._attributes;
if (tree) {
removeArrayItem(rowKey, tree.childRowKeys);
if (row._children) {
const index = findPropIndex('rowKey', rowKey, row._children);
if (index !== -1) {
row._children.splice(index, 1);
}
}
if (!tree.childRowKeys.length) {
row._leaf = true;
}
notify(tree, 'childRowKeys');
}
}
export function removeExpandedAttr(row: Row) {
const { tree } = row._attributes;
if (tree) {
tree.expanded = false;
}
}
export function expandByRowKey(store: Store, rowKey: RowKey, recursive?: boolean) {
const { data, column, id } = store;
const row = findRowByRowKey(data, column, id, rowKey);
if (row) {
expand(store, row, recursive);
}
}
export function expandAll(store: Store) {
store.data.rawData.forEach((row) => {
if (isRootChildRow(row) && !isLeaf(row)) {
expand(store, row, true);
}
});
}
export function collapseByRowKey(store: Store, rowKey: RowKey, recursive?: boolean) {
const { data, column, id } = store;
const row = findRowByRowKey(data, column, id, rowKey);
if (row) {
collapse(store, row, recursive);
}
}
export function collapseAll(store: Store) {
store.data.rawData.forEach((row) => {
if (isRootChildRow(row) && !isLeaf(row)) {
collapse(store, row, true);
}
});
}
export function changeTreeRowsCheckedState(store: Store, rowKey: RowKey, state: boolean) {
const { treeColumnName, treeCascadingCheckbox } = store.column;
if (treeColumnName && treeCascadingCheckbox) {
changeDescendantRowsCheckedState(store, rowKey, state);
changeAncestorRowsCheckedState(store, rowKey);
}
}
// @TODO: consider tree disabled state with cascading
export function appendTreeRow(
store: Store,
row: OptRow,
options: OptAppendTreeRow & TriggerByMovingRow
) {
const { data, column, rowCoords, dimension, id } = store;
const { rawData, viewData } = data;
const { heights } = rowCoords;
const { parentRowKey, offset, movingRow } = options;
const parentRow = findRowByRowKey(data, column, id, parentRowKey);
const startIdx = getStartIndexToAppendRow(store, parentRow!, offset);
const rawRows = flattenTreeData(id, [row], parentRow!, column, {
keyColumnName: column.keyColumnName,
offset,
});
const modificationType = movingRow ? 'UPDATE' : 'CREATE';
fillMissingColumnData(column, rawRows);
const viewRows = rawRows.map((rawRow) => createViewRow(id, rawRow, rawData, column));
silentSplice(rawData, startIdx, 0, ...rawRows);
silentSplice(viewData, startIdx, 0, ...viewRows);
const rowHeights = rawRows.map((rawRow) => {
changeTreeRowsCheckedState(store, rawRow.rowKey, rawRow._attributes.checked);
getDataManager(id).push(modificationType, rawRow, true);
return getRowHeight(rawRow, dimension.rowHeight);
});
notify(data, 'rawData', 'filteredRawData', 'viewData', 'filteredViewData');
heights.splice(startIdx, 0, ...rowHeights);
postUpdateAfterManipulation(store, startIdx, rawRows);
}
// @TODO: consider tree disabled state with cascading
export function removeTreeRow(store: Store, rowKey: RowKey, movingRow?: boolean) {
const { data, rowCoords, id, column } = store;
const { rawData, viewData } = data;
const { heights } = rowCoords;
const parentRow = getParentRow(store, rowKey);
const modificationType = movingRow ? 'UPDATE' : 'DELETE';
uncheck(store, rowKey);
if (parentRow) {
removeChildRowKey(parentRow, rowKey);
if (!getChildRowKeys(parentRow).length) {
removeExpandedAttr(parentRow);
}
}
const startIdx = findIndexByRowKey(data, column, id, rowKey);
const deleteCount = getDescendantRows(store, rowKey).length + 1;
let removedRows: Row[] = [];
batchObserver(() => {
removedRows = rawData.splice(startIdx, deleteCount);
});
viewData.splice(startIdx, deleteCount);
heights.splice(startIdx, deleteCount);
for (let i = removedRows.length - 1; i >= 0; i -= 1) {
getDataManager(id).push(modificationType, removedRows[i]);
}
postUpdateAfterManipulation(store, startIdx, rawData);
}
function postUpdateAfterManipulation(store: Store, rowIndex: number, rows?: Row[]) {
setLoadingState(store, getLoadingState(store.data.rawData));
updateRowNumber(store, rowIndex);
setCheckedAllRows(store);
setAutoResizingColumnWidths(store, rows);
}
export function moveTreeRow(
store: Store,
rowKey: RowKey,
targetIndex: number,
options: OptMoveRow & { moveToLast?: boolean }
) {
const { data, column, id } = store;
const { rawData } = data;
const targetRow = rawData[targetIndex];
if (!targetRow || isSorted(data) || isFiltered(data)) {
return;
}
const currentIndex = findIndexByRowKey(data, column, id, rowKey, false);
const row = rawData[currentIndex];
if (
currentIndex === -1 ||
currentIndex === targetIndex ||
row._attributes.disabled ||
(targetRow._attributes.disabled && options.appended)
) {
return;
}
const childRows = getDescendantRows(store, rowKey);
const minIndex = Math.min(currentIndex, targetIndex);
const moveToChild = some((childRow) => childRow.rowKey === targetRow.rowKey, childRows);
if (!moveToChild) {
removeTreeRow(store, rowKey, true);
const originRow = getOriginObject(row as Observable<Row>);
getDataManager(id).push('UPDATE', targetRow, true);
getDataManager(id).push('UPDATE', row, true);
if (options.appended) {
appendTreeRow(store, originRow, { parentRowKey: targetRow.rowKey, movingRow: true });
} else {
let { parentRowKey } = targetRow._attributes.tree!;
const parentIndex = findIndexByRowKey(data, column, id, parentRowKey);
let offset = targetIndex > currentIndex ? targetIndex - (childRows.length + 1) : targetIndex;
// calculate the offset based on parent row
if (parentIndex !== -1) {
const parentRow = rawData[parentIndex];
offset = parentRow._attributes.tree!.childRowKeys.indexOf(targetRow.rowKey)!;
}
// to resolve the index for moving last index
if (options.moveToLast) {
parentRowKey = null;
offset = rawData.length;
}
appendTreeRow(store, originRow, { parentRowKey, offset, movingRow: true });
}
postUpdateAfterManipulation(store, minIndex);
}
} | the_stack |
import { GaxiosPromise } from 'gaxios';
import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library';
import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common';
export declare namespace run_v1alpha1 {
interface Options extends GlobalOptions {
version: 'v1alpha1';
}
interface StandardParameters {
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API
* access, quota, and reports. Required unless you provide an OAuth 2.0
* token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be
* any arbitrary string assigned to a user, but should not exceed 40
* characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* Cloud Run API
*
* Deploy and manage user provided container images that scale automatically
* based on HTTP traffic.
*
* @example
* const {google} = require('googleapis');
* const run = google.run('v1alpha1');
*
* @namespace run
* @type {Function}
* @version v1alpha1
* @variation v1alpha1
* @param {object=} options Options for Run
*/
class Run {
context: APIRequestContext;
namespaces: Resource$Namespaces;
projects: Resource$Projects;
constructor(options: GlobalOptions, google?: GoogleConfigurable);
}
/**
* Information for connecting over HTTP(s).
*/
interface Schema$Addressable {
hostname?: string;
}
/**
* Specifies the audit configuration for a service. The configuration
* determines which permission types are logged, and what identities, if any,
* are exempted from logging. An AuditConfig must have one or more
* AuditLogConfigs. If there are AuditConfigs for both `allServices` and a
* specific service, the union of the two AuditConfigs is used for that
* service: the log_types specified in each AuditConfig are enabled, and the
* exempted_members in each AuditLogConfig are exempted. Example Policy with
* multiple AuditConfigs: { "audit_configs": [ {
* "service": "allServices" "audit_log_configs":
* [ { "log_type": "DATA_READ",
* "exempted_members": [ "user:foo@gmail.com" ] }, {
* "log_type": "DATA_WRITE", }, {
* "log_type": "ADMIN_READ", } ] },
* { "service": "fooservice.googleapis.com"
* "audit_log_configs": [ { "log_type":
* "DATA_READ", }, { "log_type":
* "DATA_WRITE", "exempted_members": [
* "user:bar@gmail.com" ] } ] }
* ] } For fooservice, this policy enables DATA_READ, DATA_WRITE and
* ADMIN_READ logging. It also exempts foo@gmail.com from DATA_READ logging,
* and bar@gmail.com from DATA_WRITE logging.
*/
interface Schema$AuditConfig {
/**
* The configuration for logging of each type of permission.
*/
auditLogConfigs?: Schema$AuditLogConfig[];
/**
* Specifies a service that will be enabled for audit logging. For example,
* `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a
* special value that covers all services.
*/
service?: string;
}
/**
* Provides the configuration for logging a type of permissions. Example: {
* "audit_log_configs": [ { "log_type":
* "DATA_READ", "exempted_members": [
* "user:foo@gmail.com" ] }, {
* "log_type": "DATA_WRITE", } ] } This
* enables 'DATA_READ' and 'DATA_WRITE' logging, while
* exempting foo@gmail.com from DATA_READ logging.
*/
interface Schema$AuditLogConfig {
/**
* Specifies the identities that do not cause logging for this type of
* permission. Follows the same format of Binding.members.
*/
exemptedMembers?: string[];
/**
* The log type that this config enables.
*/
logType?: string;
}
/**
* A domain that a user has been authorized to administer. To authorize use of
* a domain, verify ownership via [Webmaster
* Central](https://www.google.com/webmasters/verification/home).
*/
interface Schema$AuthorizedDomain {
/**
* Relative name of the domain authorized for use. Example: `example.com`.
*/
id?: string;
/**
* Read only. Full path to the `AuthorizedDomain` resource in the API.
* Example: `apps/myapp/authorizedDomains/example.com`.
*/
name?: string;
}
/**
* Associates `members` with a `role`.
*/
interface Schema$Binding {
/**
* The condition that is associated with this binding. NOTE: an unsatisfied
* condition will not allow user access via current binding. Different
* bindings, including their conditions, are examined independently.
*/
condition?: Schema$Expr;
/**
* Specifies the identities requesting access for a Cloud Platform resource.
* `members` can have the following values: * `allUsers`: A special
* identifier that represents anyone who is on the internet; with or
* without a Google account. * `allAuthenticatedUsers`: A special
* identifier that represents anyone who is authenticated with a Google
* account or a service account. * `user:{emailid}`: An email address that
* represents a specific Google account. For example, `alice@gmail.com` .
* * `serviceAccount:{emailid}`: An email address that represents a service
* account. For example, `my-other-app@appspot.gserviceaccount.com`. *
* `group:{emailid}`: An email address that represents a Google group. For
* example, `admins@example.com`. * `domain:{domain}`: The G Suite domain
* (primary) that represents all the users of that domain. For example,
* `google.com` or `example.com`.
*/
members?: string[];
/**
* Role that is assigned to `members`. For example, `roles/viewer`,
* `roles/editor`, or `roles/owner`.
*/
role?: string;
}
/**
* Adds and removes POSIX capabilities from running containers.
*/
interface Schema$Capabilities {
/**
* Added capabilities +optional
*/
add?: string[];
/**
* Removed capabilities +optional
*/
drop?: string[];
}
/**
* ConfigMapEnvSource selects a ConfigMap to populate the environment
* variables with. The contents of the target ConfigMap's Data field will
* represent the key-value pairs as environment variables.
*/
interface Schema$ConfigMapEnvSource {
/**
* The ConfigMap to select from.
*/
localObjectReference?: Schema$LocalObjectReference;
/**
* Specify whether the ConfigMap must be defined +optional
*/
optional?: boolean;
}
/**
* Configuration represents the "floating HEAD" of a linear history
* of Revisions, and optionally how the containers those revisions reference
* are built. Users create new Revisions by updating the Configuration's
* spec. The "latest created" revision's name is available under
* status, as is the "latest ready" revision's name. See also:
* https://github.com/knative/serving/blob/master/docs/spec/overview.md#configuration
*/
interface Schema$Configuration {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* The kind of resource, in this case always "Configuration".
*/
kind?: string;
/**
* Metadata associated with this Configuration, including name, namespace,
* labels, and annotations.
*/
metadata?: Schema$ObjectMeta;
/**
* Spec holds the desired state of the Configuration (from the client).
*/
spec?: Schema$ConfigurationSpec;
/**
* Status communicates the observed state of the Configuration (from the
* controller).
*/
status?: Schema$ConfigurationStatus;
}
/**
* ConfigurationCondition defines a readiness condition for a Configuration.
*/
interface Schema$ConfigurationCondition {
/**
* Last time the condition transitioned from one status to another.
* +optional
*/
lastTransitionTime?: string;
/**
* Human-readable message indicating details about last transition.
* +optional
*/
message?: string;
/**
* One-word CamelCase reason for the condition's last transition.
* +optional
*/
reason?: string;
/**
* Status of the condition, one of True, False, Unknown.
*/
status?: string;
/**
* ConfigurationConditionType is used to communicate the status of the
* reconciliation process. See also:
* https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting
* Types include:"Ready"
*/
type?: string;
}
/**
* ConfigurationSpec holds the desired state of the Configuration (from the
* client).
*/
interface Schema$ConfigurationSpec {
/**
* Deprecated and not currently populated by Cloud Run. See
* metadata.generation instead, which is the sequence number containing the
* latest generation of the desired state. Read-only.
*/
generation?: number;
/**
* RevisionTemplate holds the latest specification for the Revision to be
* stamped out. The template references the container image, and may also
* include labels and annotations that should be attached to the Revision.
* To correlate a Revision, and/or to force a Revision to be created when
* the spec doesn't otherwise change, a nonce label may be provided in
* the template metadata. For more details, see:
* https://github.com/knative/serving/blob/master/docs/client-conventions.md#associate-modifications-with-revisions
* Cloud Run does not currently support referencing a build that is
* responsible for materializing the container image from source.
*/
revisionTemplate?: Schema$RevisionTemplate;
}
/**
* ConfigurationStatus communicates the observed state of the Configuration
* (from the controller).
*/
interface Schema$ConfigurationStatus {
/**
* Conditions communicates information about ongoing/complete reconciliation
* processes that bring the "spec" inline with the observed state
* of the world.
*/
conditions?: Schema$ConfigurationCondition[];
/**
* LatestCreatedRevisionName is the last revision that was created from this
* Configuration. It might not be ready yet, for that use
* LatestReadyRevisionName.
*/
latestCreatedRevisionName?: string;
/**
* LatestReadyRevisionName holds the name of the latest Revision stamped out
* from this Configuration that has had its "Ready" condition
* become "True".
*/
latestReadyRevisionName?: string;
/**
* ObservedGeneration is the 'Generation' of the Configuration that
* was last processed by the controller. The observed generation is updated
* even if the controller failed to process the spec and create the
* Revision. Clients polling for completed reconciliation should poll until
* observedGeneration = metadata.generation, and the Ready condition's
* status is True or False.
*/
observedGeneration?: number;
}
/**
* A single application container. This specifies both the container to run,
* the command to run in the container and the arguments to supply to it. Note
* that additional arguments may be supplied by the system to the container at
* runtime.
*/
interface Schema$Container {
/**
* Arguments to the entrypoint. The docker image's CMD is used if this
* is not provided. Variable references $(VAR_NAME) are expanded using the
* container's environment. If a variable cannot be resolved, the
* reference in the input string will be unchanged. The $(VAR_NAME) syntax
* can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references
* will never be expanded, regardless of whether the variable exists or not.
* Cannot be updated. More info:
* https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
* +optional
*/
args?: string[];
/**
* Entrypoint array. Not executed within a shell. The docker image's
* ENTRYPOINT is used if this is not provided. Variable references
* $(VAR_NAME) are expanded using the container's environment. If a
* variable cannot be resolved, the reference in the input string will be
* unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie:
* $$(VAR_NAME). Escaped references will never be expanded, regardless of
* whether the variable exists or not. Cannot be updated. More info:
* https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell
* +optional
*/
command?: string[];
/**
* List of environment variables to set in the container. Cannot be updated.
* +optional
*/
env?: Schema$EnvVar[];
/**
* List of sources to populate environment variables in the container. The
* keys defined within a source must be a C_IDENTIFIER. All invalid keys
* will be reported as an event when the container is starting. When a key
* exists in multiple sources, the value associated with the last source
* will take precedence. Values defined by an Env with a duplicate key will
* take precedence. Cannot be updated. +optional
*/
envFrom?: Schema$EnvFromSource[];
/**
* Docker image name. More info:
* https://kubernetes.io/docs/concepts/containers/images
*/
image?: string;
/**
* Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always
* if :latest tag is specified, or IfNotPresent otherwise. Cannot be
* updated. More info:
* https://kubernetes.io/docs/concepts/containers/images#updating-images
* +optional
*/
imagePullPolicy?: string;
/**
* Actions that the management system should take in response to container
* lifecycle events. Cannot be updated. +optional
*/
lifecycle?: Schema$Lifecycle;
/**
* Periodic probe of container liveness. Container will be restarted if the
* probe fails. Cannot be updated. More info:
* https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* +optional
*/
livenessProbe?: Schema$Probe;
/**
* Name of the container specified as a DNS_LABEL. Each container must have
* a unique name (DNS_LABEL). Cannot be updated.
*/
name?: string;
/**
* List of ports to expose from the container. Exposing a port here gives
* the system additional information about the network connections a
* container uses, but is primarily informational. Not specifying a port
* here DOES NOT prevent that port from being exposed. Any port which is
* listening on the default "0.0.0.0" address inside a container
* will be accessible from the network. Cannot be updated. +optional
*/
ports?: Schema$ContainerPort[];
/**
* Periodic probe of container service readiness. Container will be removed
* from service endpoints if the probe fails. Cannot be updated. More info:
* https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* +optional
*/
readinessProbe?: Schema$Probe;
/**
* Compute Resources required by this container. Cannot be updated. More
* info:
* https://kubernetes.io/docs/concepts/storage/persistent-volumes#resources
* +optional
*/
resources?: Schema$ResourceRequirements;
/**
* Security options the pod should run with. More info:
* https://kubernetes.io/docs/concepts/policy/security-context/ More info:
* https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
* +optional
*/
securityContext?: Schema$SecurityContext;
/**
* Whether this container should allocate a buffer for stdin in the
* container runtime. If this is not set, reads from stdin in the container
* will always result in EOF. Default is false. +optional
*/
stdin?: boolean;
/**
* Whether the container runtime should close the stdin channel after it has
* been opened by a single attach. When stdin is true the stdin stream will
* remain open across multiple attach sessions. If stdinOnce is set to true,
* stdin is opened on container start, is empty until the first client
* attaches to stdin, and then remains open and accepts data until the
* client disconnects, at which time stdin is closed and remains closed
* until the container is restarted. If this flag is false, a container
* processes that reads from stdin will never receive an EOF. Default is
* false +optional
*/
stdinOnce?: boolean;
/**
* Optional: Path at which the file to which the container's termination
* message will be written is mounted into the container's filesystem.
* Message written is intended to be brief final status, such as an
* assertion failure message. Will be truncated by the node if greater than
* 4096 bytes. The total message length across all containers will be
* limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.
* +optional
*/
terminationMessagePath?: string;
/**
* Indicate how the termination message should be populated. File will use
* the contents of terminationMessagePath to populate the container status
* message on both success and failure. FallbackToLogsOnError will use the
* last chunk of container log output if the termination message file is
* empty and the container exited with an error. The log output is limited
* to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot
* be updated. +optional
*/
terminationMessagePolicy?: string;
/**
* Whether this container should allocate a TTY for itself, also requires
* 'stdin' to be true. Default is false. +optional
*/
tty?: boolean;
/**
* volumeDevices is the list of block devices to be used by the container.
* This is an alpha feature and may change in the future. +optional
*/
volumeDevices?: Schema$VolumeDevice[];
/**
* Pod volumes to mount into the container's filesystem. Cannot be
* updated. +optional
*/
volumeMounts?: Schema$VolumeMount[];
/**
* Container's working directory. If not specified, the container
* runtime's default will be used, which might be configured in the
* container image. Cannot be updated. +optional
*/
workingDir?: string;
}
/**
* ContainerPort represents a network port in a single container.
*/
interface Schema$ContainerPort {
/**
* Number of port to expose on the pod's IP address. This must be a
* valid port number, 0 < x < 65536.
*/
containerPort?: number;
/**
* What host IP to bind the external port to. +optional
*/
hostIP?: string;
/**
* Number of port to expose on the host. If specified, this must be a valid
* port number, 0 < x < 65536. If HostNetwork is specified, this must
* match ContainerPort. Most containers do not need this. +optional
*/
hostPort?: number;
/**
* If specified, this must be an IANA_SVC_NAME and unique within the pod.
* Each named port in a pod must have a unique name. Name for the port that
* can be referred to by services. +optional
*/
name?: string;
/**
* Protocol for port. Must be UDP or TCP. Defaults to "TCP".
* +optional
*/
protocol?: string;
}
/**
* Resource to hold the state and status of a user's domain mapping.
*/
interface Schema$DomainMapping {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* The kind of resource, in this case "DomainMapping".
*/
kind?: string;
/**
* Metadata associated with this BuildTemplate.
*/
metadata?: Schema$ObjectMeta;
/**
* The spec for this DomainMapping.
*/
spec?: Schema$DomainMappingSpec;
/**
* The current status of the DomainMapping.
*/
status?: Schema$DomainMappingStatus;
}
/**
* DomainMappingCondition contains state information for a DomainMapping.
*/
interface Schema$DomainMappingCondition {
/**
* Human readable message indicating details about the current status.
* +optional
*/
message?: string;
/**
* One-word CamelCase reason for the condition's current status.
* +optional
*/
reason?: string;
/**
* Status of the condition, one of True, False, Unknown.
*/
status?: string;
/**
* Type of domain mapping condition.
*/
type?: string;
}
/**
* The desired state of the Domain Mapping.
*/
interface Schema$DomainMappingSpec {
/**
* The mode of the certificate.
*/
certificateMode?: string;
/**
* If set, the mapping will override any mapping set before this spec was
* set. It is recommended that the user leaves this empty to receive an
* error warning about a potential conflict and only set it once the
* respective UI has given such a warning.
*/
forceOverride?: boolean;
/**
* The name of the Knative Route that this DomainMapping applies to. The
* route must exist.
*/
routeName?: string;
}
/**
* The current state of the Domain Mapping.
*/
interface Schema$DomainMappingStatus {
/**
* Array of observed DomainMappingConditions, indicating the current state
* of the DomainMapping.
*/
conditions?: Schema$DomainMappingCondition[];
/**
* The name of the route that the mapping currently points to.
*/
mappedRouteName?: string;
/**
* ObservedGeneration is the 'Generation' of the DomainMapping that
* was last processed by the controller. Clients polling for completed
* reconciliation should poll until observedGeneration = metadata.generation
* and the Ready condition's status is True or False.
*/
observedGeneration?: number;
/**
* The resource records required to configure this domain mapping. These
* records must be added to the domain's DNS configuration in order to
* serve the application via this domain mapping.
*/
resourceRecords?: Schema$ResourceRecord[];
}
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance: service Foo { rpc
* Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON
* representation for `Empty` is empty JSON object `{}`.
*/
interface Schema$Empty {
}
/**
* EnvFromSource represents the source of a set of ConfigMaps
*/
interface Schema$EnvFromSource {
/**
* The ConfigMap to select from +optional
*/
configMapRef?: Schema$ConfigMapEnvSource;
/**
* An optional identifier to prepend to each key in the ConfigMap. Must be a
* C_IDENTIFIER. +optional
*/
prefix?: string;
/**
* The Secret to select from +optional
*/
secretRef?: Schema$SecretEnvSource;
}
/**
* EnvVar represents an environment variable present in a Container.
*/
interface Schema$EnvVar {
/**
* Name of the environment variable. Must be a C_IDENTIFIER.
*/
name?: string;
/**
* Variable references $(VAR_NAME) are expanded using the previous defined
* environment variables in the container and any route environment
* variables. If a variable cannot be resolved, the reference in the input
* string will be unchanged. The $(VAR_NAME) syntax can be escaped with a
* double $$, ie: $$(VAR_NAME). Escaped references will never be expanded,
* regardless of whether the variable exists or not. Defaults to
* "". +optional
*/
value?: string;
}
/**
* ExecAction describes a "run in container" action.
*/
interface Schema$ExecAction {
/**
* Command is the command line to execute inside the container, the working
* directory for the command is root ('/') in the container's
* filesystem. The command is simply exec'd, it is not run inside a
* shell, so traditional shell instructions ('|', etc) won't
* work. To use a shell, you need to explicitly call out to that shell. Exit
* status of 0 is treated as live/healthy and non-zero is unhealthy.
* +optional
*/
command?: string;
}
/**
* Represents an expression text. Example: title: "User account
* presence" description: "Determines whether the request has a
* user account" expression: "size(request.user) > 0"
*/
interface Schema$Expr {
/**
* An optional description of the expression. This is a longer text which
* describes the expression, e.g. when hovered over it in a UI.
*/
description?: string;
/**
* Textual representation of an expression in Common Expression Language
* syntax. The application context of the containing message determines
* which well-known feature set of CEL is supported.
*/
expression?: string;
/**
* An optional string indicating the location of the expression for error
* reporting, e.g. a file name and a position in the file.
*/
location?: string;
/**
* An optional title for the expression, i.e. a short string describing its
* purpose. This can be used e.g. in UIs which allow to enter the
* expression.
*/
title?: string;
}
/**
* Handler defines a specific action that should be taken
*/
interface Schema$Handler {
/**
* One and only one of the following should be specified. Exec specifies the
* action to take. +optional
*/
exec?: Schema$ExecAction;
/**
* HTTPGet specifies the http request to perform. +optional
*/
httpGet?: Schema$HTTPGetAction;
/**
* TCPSocket specifies an action involving a TCP port. TCP hooks not yet
* supported
*/
tcpSocket?: Schema$TCPSocketAction;
}
/**
* HTTPGetAction describes an action based on HTTP Get requests.
*/
interface Schema$HTTPGetAction {
/**
* Host name to connect to, defaults to the pod IP. You probably want to set
* "Host" in httpHeaders instead. +optional
*/
host?: string;
/**
* Custom headers to set in the request. HTTP allows repeated headers.
* +optional
*/
httpHeaders?: Schema$HTTPHeader[];
/**
* Path to access on the HTTP server. +optional
*/
path?: string;
/**
* Name or number of the port to access on the container. Number must be in
* the range 1 to 65535. Name must be an IANA_SVC_NAME.
*/
port?: Schema$IntOrString;
/**
* Scheme to use for connecting to the host. Defaults to HTTP. +optional
*/
scheme?: string;
}
/**
* HTTPHeader describes a custom header to be used in HTTP probes
*/
interface Schema$HTTPHeader {
/**
* The header field name
*/
name?: string;
/**
* The header field value
*/
value?: string;
}
/**
* Initializer is information about an initializer that has not yet completed.
*/
interface Schema$Initializer {
/**
* name of the process that is responsible for initializing this object.
*/
name?: string;
}
/**
* Initializers tracks the progress of initialization.
*/
interface Schema$Initializers {
/**
* Pending is a list of initializers that must execute in order before this
* object is visible. When the last pending initializer is removed, and no
* failing result is set, the initializers struct will be set to nil and the
* object is considered as initialized and visible to all clients.
* +patchMergeKey=name +patchStrategy=merge
*/
pending?: Schema$Initializer[];
}
/**
* IntOrString is a type that can hold an int32 or a string. When used in
* JSON or YAML marshalling and unmarshalling, it produces or consumes the
* inner type. This allows you to have, for example, a JSON field that can
* accept a name or number.
*/
interface Schema$IntOrString {
/**
* The int value.
*/
intVal?: number;
/**
* The string value.
*/
strVal?: string;
/**
* The type of the value.
*/
type?: string;
}
/**
* Lifecycle describes actions that the management system should take in
* response to container lifecycle events. For the PostStart and PreStop
* lifecycle handlers, management of the container blocks until the action is
* complete, unless the container process fails, in which case the handler is
* aborted.
*/
interface Schema$Lifecycle {
/**
* PostStart is called immediately after a container is created. If the
* handler fails, the container is terminated and restarted according to its
* restart policy. Other management of the container blocks until the hook
* completes. More info:
* https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
* +optional
*/
postStart?: Schema$Handler;
/**
* PreStop is called immediately before a container is terminated. The
* container is terminated after the handler completes. The reason for
* termination is passed to the handler. Regardless of the outcome of the
* handler, the container is eventually terminated. Other management of the
* container blocks until the hook completes. More info:
* https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks
* +optional
*/
preStop?: Schema$Handler;
}
/**
* A list of Authorized Domains.
*/
interface Schema$ListAuthorizedDomainsResponse {
/**
* The authorized domains belonging to the user.
*/
domains?: Schema$AuthorizedDomain[];
/**
* Continuation token for fetching the next page of results.
*/
nextPageToken?: string;
}
/**
* ListConfigurationsResponse is a list of Configuration resources.
*/
interface Schema$ListConfigurationsResponse {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* List of Configurations.
*/
items?: Schema$Configuration[];
/**
* The kind of this resource, in this case "ConfigurationList".
*/
kind?: string;
/**
* Metadata associated with this Configuration list.
*/
metadata?: Schema$ListMeta;
/**
* Locations that could not be reached.
*/
unreachable?: string[];
}
/**
* ListDomainMappingsResponse is a list of DomainMapping resources.
*/
interface Schema$ListDomainMappingsResponse {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* List of DomainMappings.
*/
items?: Schema$DomainMapping[];
/**
* The kind of this resource, in this case "DomainMappingList".
*/
kind?: string;
/**
* Metadata associated with this DomainMapping list.
*/
metadata?: Schema$ListMeta;
}
/**
* The response message for Locations.ListLocations.
*/
interface Schema$ListLocationsResponse {
/**
* A list of locations that matches the specified filter in the request.
*/
locations?: Schema$Location[];
/**
* The standard List next-page token.
*/
nextPageToken?: string;
}
/**
* ListMeta describes metadata that synthetic resources must have, including
* lists and various status objects. A resource may have only one of
* {ObjectMeta, ListMeta}.
*/
interface Schema$ListMeta {
/**
* continue may be set if the user set a limit on the number of items
* returned, and indicates that the server has more data available. The
* value is opaque and may be used to issue another request to the endpoint
* that served this list to retrieve the next set of available objects.
* Continuing a list may not be possible if the server configuration has
* changed or more than a few minutes have passed. The resourceVersion field
* returned when using this continue value will be identical to the value in
* the first response.
*/
continue?: string;
/**
* String that identifies the server's internal version of this object
* that can be used by clients to determine when objects have changed. Value
* must be treated as opaque by clients and passed unmodified back to the
* server. Populated by the system. Read-only. More info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
* +optional
*/
resourceVersion?: string;
/**
* SelfLink is a URL representing this object. Populated by the system.
* Read-only. +optional
*/
selfLink?: string;
}
/**
* ListRevisionsResponse is a list of Revision resources.
*/
interface Schema$ListRevisionsResponse {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* List of Revisions.
*/
items?: Schema$Revision[];
/**
* The kind of this resource, in this case "RevisionList".
*/
kind?: string;
/**
* Metadata associated with this revision list.
*/
metadata?: Schema$ListMeta;
/**
* Locations that could not be reached.
*/
unreachable?: string[];
}
/**
* ListRoutesResponse is a list of Route resources.
*/
interface Schema$ListRoutesResponse {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* List of Routes.
*/
items?: Schema$Route[];
/**
* The kind of this resource, in this case always "RouteList".
*/
kind?: string;
/**
* Metadata associated with this Route list.
*/
metadata?: Schema$ListMeta;
/**
* Locations that could not be reached.
*/
unreachable?: string[];
}
/**
* A list of Service resources.
*/
interface Schema$ListServicesResponse {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* List of Services.
*/
items?: Schema$Service[];
/**
* The kind of this resource, in this case "ServiceList".
*/
kind?: string;
/**
* Metadata associated with this Service list.
*/
metadata?: Schema$ListMeta;
/**
* Locations that could not be reached.
*/
unreachable?: string[];
}
/**
* LocalObjectReference contains enough information to let you locate the
* referenced object inside the same namespace.
*/
interface Schema$LocalObjectReference {
/**
* Name of the referent. More info:
* https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
*/
name?: string;
}
/**
* A resource that represents Google Cloud Platform location.
*/
interface Schema$Location {
/**
* The friendly name for this location, typically a nearby city name. For
* example, "Tokyo".
*/
displayName?: string;
/**
* Cross-service attributes for the location. For example
* {"cloud.googleapis.com/region": "us-east1"}
*/
labels?: {
[key: string]: string;
};
/**
* The canonical id for this location. For example: `"us-east1"`.
*/
locationId?: string;
/**
* Service-specific metadata. For example the available capacity at the
* given location.
*/
metadata?: {
[key: string]: any;
};
/**
* Resource name for the location, which may vary between implementations.
* For example: `"projects/example-project/locations/us-east1"`
*/
name?: string;
}
/**
* ObjectMeta is metadata that all persisted resources must have, which
* includes all objects users must create.
*/
interface Schema$ObjectMeta {
/**
* Annotations is an unstructured key value map stored with a resource that
* may be set by external tools to store and retrieve arbitrary metadata.
* They are not queryable and should be preserved when modifying objects.
* More info: http://kubernetes.io/docs/user-guide/annotations +optional
*/
annotations?: {
[key: string]: string;
};
/**
* Not currently supported by Cloud Run. The name of the cluster which the
* object belongs to. This is used to distinguish resources with same name
* and namespace in different clusters. This field is not set anywhere right
* now and apiserver is going to ignore it if set in create or update
* request. +optional
*/
clusterName?: string;
/**
* CreationTimestamp is a timestamp representing the server time when this
* object was created. It is not guaranteed to be set in happens-before
* order across separate operations. Clients may not set this value. It is
* represented in RFC3339 form and is in UTC. Populated by the system.
* Read-only. Null for lists. More info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
* +optional
*/
creationTimestamp?: string;
/**
* Not currently supported by Cloud Run. Number of seconds allowed for this
* object to gracefully terminate before it will be removed from the system.
* Only set when deletionTimestamp is also set. May only be shortened.
* Read-only. +optional
*/
deletionGracePeriodSeconds?: number;
/**
* DeletionTimestamp is RFC 3339 date and time at which this resource will
* be deleted. This field is set by the server when a graceful deletion is
* requested by the user, and is not directly settable by a client. The
* resource is expected to be deleted (no longer visible from resource
* lists, and not reachable by name) after the time in this field, once the
* finalizers list is empty. As long as the finalizers list contains items,
* deletion is blocked. Once the deletionTimestamp is set, this value may
* not be unset or be set further into the future, although it may be
* shortened or the resource may be deleted prior to this time. For example,
* a user may request that a pod is deleted in 30 seconds. The Kubelet will
* react by sending a graceful termination signal to the containers in the
* pod. After that 30 seconds, the Kubelet will send a hard termination
* signal (SIGKILL) to the container and after cleanup, remove the pod from
* the API. In the presence of network partitions, this object may still
* exist after this timestamp, until an administrator or automated process
* can determine the resource is fully terminated. If not set, graceful
* deletion of the object has not been requested. Populated by the system
* when a graceful deletion is requested. Read-only. More info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
* +optional
*/
deletionTimestamp?: string;
/**
* Not currently supported by Cloud Run. Must be empty before the object is
* deleted from the registry. Each entry is an identifier for the
* responsible component that will remove the entry from the list. If the
* deletionTimestamp of the object is non-nil, entries in this list can only
* be removed. +optional +patchStrategy=merge
*/
finalizers?: string[];
/**
* Not currently supported by Cloud Run. GenerateName is an optional
* prefix, used by the server, to generate a unique name ONLY IF the Name
* field has not been provided. If this field is used, the name returned to
* the client will be different than the name passed. This value will also
* be combined with a unique suffix. The provided value has the same
* validation rules as the Name field, and may be truncated by the length of
* the suffix required to make the value unique on the server. If this
* field is specified and the generated name exists, the server will NOT
* return a 409 - instead, it will either return 201 Created or 500 with
* Reason ServerTimeout indicating a unique name could not be found in the
* time allotted, and the client should retry (optionally after the time
* indicated in the Retry-After header). Applied only if Name is not
* specified. More info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency
* +optional string generateName = 2;
*/
generateName?: string;
/**
* A sequence number representing a specific generation of the desired
* state. Populated by the system. Read-only. +optional
*/
generation?: number;
/**
* Not currently supported by Cloud Run. An initializer is a controller
* which enforces some system invariant at object creation time. This field
* is a list of initializers that have not yet acted on this object. If nil
* or empty, this object has been completely initialized. Otherwise, the
* object is considered uninitialized and is hidden (in list/watch and get
* calls) from clients that haven't explicitly asked to observe
* uninitialized objects. When an object is created, the system will
* populate this list with the current set of initializers. Only privileged
* users may set or modify this list. Once it is empty, it may not be
* modified further by any user.
*/
initializers?: Schema$Initializers;
/**
* Map of string keys and values that can be used to organize and categorize
* (scope and select) objects. May match selectors of replication
* controllers and routes. More info:
* http://kubernetes.io/docs/user-guide/labels +optional
*/
labels?: {
[key: string]: string;
};
/**
* Name must be unique within a namespace, within a Cloud Run region. Is
* required when creating resources, although some resources may allow a
* client to request the generation of an appropriate name automatically.
* Name is primarily intended for creation idempotence and configuration
* definition. Cannot be updated. More info:
* http://kubernetes.io/docs/user-guide/identifiers#names +optional
*/
name?: string;
/**
* Namespace defines the space within each name must be unique, within a
* Cloud Run region. In Cloud Run the namespace must be equal to either the
* project ID or project number.
*/
namespace?: string;
/**
* List of objects that own this object. If ALL objects in the list have
* been deleted, this object will be garbage collected. +optional
*/
ownerReferences?: Schema$OwnerReference[];
/**
* An opaque value that represents the internal version of this object that
* can be used by clients to determine when objects have changed. May be
* used for optimistic concurrency, change detection, and the watch
* operation on a resource or set of resources. Clients must treat these
* values as opaque and passed unmodified back to the server. They may only
* be valid for a particular resource or set of resources. Populated by the
* system. Read-only. Value must be treated as opaque by clients and . More
* info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
* +optional
*/
resourceVersion?: string;
/**
* SelfLink is a URL representing this object. Populated by the system.
* Read-only. +optional string selfLink = 4;
*/
selfLink?: string;
/**
* UID is the unique in time and space value for this object. It is
* typically generated by the server on successful creation of a resource
* and is not allowed to change on PUT operations. Populated by the system.
* Read-only. More info:
* http://kubernetes.io/docs/user-guide/identifiers#uids +optional
*/
uid?: string;
}
/**
* OwnerReference contains enough information to let you identify an owning
* object. Currently, an owning object must be in the same namespace, so there
* is no namespace field.
*/
interface Schema$OwnerReference {
/**
* API version of the referent.
*/
apiVersion?: string;
/**
* If true, AND if the owner has the "foregroundDeletion"
* finalizer, then the owner cannot be deleted from the key-value store
* until this reference is removed. Defaults to false. To set this field, a
* user needs "delete" permission of the owner, otherwise 422
* (Unprocessable Entity) will be returned. +optional
*/
blockOwnerDeletion?: boolean;
/**
* If true, this reference points to the managing controller. +optional
*/
controller?: boolean;
/**
* Kind of the referent. More info:
* https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
*/
kind?: string;
/**
* Name of the referent. More info:
* http://kubernetes.io/docs/user-guide/identifiers#names
*/
name?: string;
/**
* UID of the referent. More info:
* http://kubernetes.io/docs/user-guide/identifiers#uids
*/
uid?: string;
}
/**
* Defines an Identity and Access Management (IAM) policy. It is used to
* specify access control policies for Cloud Platform resources. A `Policy`
* consists of a list of `bindings`. A `binding` binds a list of `members` to
* a `role`, where the members can be user accounts, Google groups, Google
* domains, and service accounts. A `role` is a named list of permissions
* defined by IAM. **JSON Example** { "bindings": [ {
* "role": "roles/owner", "members": [
* "user:mike@example.com", "group:admins@example.com",
* "domain:google.com",
* "serviceAccount:my-other-app@appspot.gserviceaccount.com" ] }, {
* "role": "roles/viewer", "members":
* ["user:sean@example.com"] } ] } **YAML
* Example** bindings: - members: - user:mike@example.com -
* group:admins@example.com - domain:google.com -
* serviceAccount:my-other-app@appspot.gserviceaccount.com role:
* roles/owner - members: - user:sean@example.com role:
* roles/viewer For a description of IAM and its features, see the [IAM
* developer's guide](https://cloud.google.com/iam/docs).
*/
interface Schema$Policy {
/**
* Specifies cloud audit logging configuration for this policy.
*/
auditConfigs?: Schema$AuditConfig[];
/**
* Associates a list of `members` to a `role`. `bindings` with no members
* will result in an error.
*/
bindings?: Schema$Binding[];
/**
* `etag` is used for optimistic concurrency control as a way to help
* prevent simultaneous updates of a policy from overwriting each other. It
* is strongly suggested that systems make use of the `etag` in the
* read-modify-write cycle to perform policy updates in order to avoid race
* conditions: An `etag` is returned in the response to `getIamPolicy`, and
* systems are expected to put that etag in the request to `setIamPolicy` to
* ensure that their change will be applied to the same version of the
* policy. If no `etag` is provided in the call to `setIamPolicy`, then the
* existing policy is overwritten blindly.
*/
etag?: string;
/**
* Deprecated.
*/
version?: number;
}
/**
* Probe describes a health check to be performed against a container to
* determine whether it is alive or ready to receive traffic.
*/
interface Schema$Probe {
/**
* Minimum consecutive failures for the probe to be considered failed after
* having succeeded. Defaults to 3. Minimum value is 1. +optional
*/
failureThreshold?: number;
/**
* The action taken to determine the health of a container
*/
handler?: Schema$Handler;
/**
* Number of seconds after the container has started before liveness probes
* are initiated. More info:
* https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* +optional
*/
initialDelaySeconds?: number;
/**
* How often (in seconds) to perform the probe. Default to 10 seconds.
* Minimum value is 1. +optional
*/
periodSeconds?: number;
/**
* Minimum consecutive successes for the probe to be considered successful
* after having failed. Defaults to 1. Must be 1 for liveness. Minimum value
* is 1. +optional
*/
successThreshold?: number;
/**
* Number of seconds after which the probe times out. Defaults to 1 second.
* Minimum value is 1. More info:
* https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes
* +optional
*/
timeoutSeconds?: number;
}
/**
* The view model of a single quantity, e.g. "800 MiB". Corresponds
* to
* https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/generated.proto
*/
interface Schema$Quantity {
/**
* Stringified version of the quantity, e.g., "800 MiB".
*/
string?: string;
}
/**
* A DNS resource record.
*/
interface Schema$ResourceRecord {
/**
* Relative name of the object affected by this record. Only applicable for
* `CNAME` records. Example: 'www'.
*/
name?: string;
/**
* Data for this record. Values vary by record type, as defined in RFC 1035
* (section 5) and RFC 1034 (section 3.6.1).
*/
rrdata?: string;
/**
* Resource record type. Example: `AAAA`.
*/
type?: string;
}
/**
* ResourceRequirements describes the compute resource requirements.
*/
interface Schema$ResourceRequirements {
/**
* Limits describes the maximum amount of compute resources allowed. The
* values of the map is string form of the 'quantity' k8s type:
* https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go
*/
limits?: {
[key: string]: string;
};
/**
* Limits describes the maximum amount of compute resources allowed. This is
* a temporary field created to migrate away from the map<string,
* Quantity> limits field. This is done to become compliant with k8s
* style API. This field is deprecated in favor of limits field.
*/
limitsInMap?: {
[key: string]: Schema$Quantity;
};
/**
* Requests describes the minimum amount of compute resources required. If
* Requests is omitted for a container, it defaults to Limits if that is
* explicitly specified, otherwise to an implementation-defined value. The
* values of the map is string form of the 'quantity' k8s type:
* https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go
*/
requests?: {
[key: string]: string;
};
/**
* Requests describes the minimum amount of compute resources required. If
* Requests is omitted for a container, it defaults to Limits if that is
* explicitly specified, otherwise to an implementation-defined value. This
* is a temporary field created to migrate away from the map<string,
* Quantity> requests field. This is done to become compliant with k8s
* style API. This field is deprecated in favor of requests field.
*/
requestsInMap?: {
[key: string]: Schema$Quantity;
};
}
/**
* Revision is an immutable snapshot of code and configuration. A revision
* references a container image. Revisions are created by updates to a
* Configuration. Cloud Run does not currently support referencing a build
* that is responsible for materializing the container image from source. See
* also:
* https://github.com/knative/serving/blob/master/docs/spec/overview.md#revision
*/
interface Schema$Revision {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* The kind of this resource, in this case "Revision".
*/
kind?: string;
/**
* Metadata associated with this Revision, including name, namespace,
* labels, and annotations.
*/
metadata?: Schema$ObjectMeta;
/**
* Spec holds the desired state of the Revision (from the client).
*/
spec?: Schema$RevisionSpec;
/**
* Status communicates the observed state of the Revision (from the
* controller).
*/
status?: Schema$RevisionStatus;
}
/**
* RevisionCondition defines a readiness condition for a Revision.
*/
interface Schema$RevisionCondition {
/**
* Last time the condition transitioned from one status to another.
* +optional
*/
lastTransitionTime?: string;
/**
* Human readable message indicating details about the current status.
* +optional
*/
message?: string;
/**
* One-word CamelCase reason for the condition's last transition.
* +optional
*/
reason?: string;
/**
* Status of the condition, one of True, False, Unknown.
*/
status?: string;
/**
* RevisionConditionType is used to communicate the status of the
* reconciliation process. See also:
* https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting
* Types include: * "Ready": True when the Revision is ready. *
* "ResourcesAvailable": True when underlying resources have been
* provisioned. * "ContainerHealthy": True when the Revision
* readiness check completes. * "Active": True when the Revision
* may receive traffic.
*/
type?: string;
}
/**
* RevisionSpec holds the desired state of the Revision (from the client).
*/
interface Schema$RevisionSpec {
/**
* ConcurrencyModel specifies the desired concurrency model (Single or
* Multi) for the Revision. Defaults to Multi. Deprecated in favor of
* ContainerConcurrency. +optional
*/
concurrencyModel?: string;
/**
* Container defines the unit of execution for this Revision. In the context
* of a Revision, we disallow a number of the fields of this Container,
* including: name, ports, and volumeMounts. The runtime contract is
* documented here:
* https://github.com/knative/serving/blob/master/docs/runtime-contract.md
*/
container?: Schema$Container;
/**
* ContainerConcurrency specifies the maximum allowed in-flight (concurrent)
* requests per container of the Revision. Values are: - `0` thread-safe,
* the system should manage the max concurrency. This is the default
* value. - `1` not-thread-safe. Single concurrency - `2-N` thread-safe, max
* concurrency of N
*/
containerConcurrency?: number;
/**
* Deprecated and not currently populated by Cloud Run. See
* metadata.generation instead, which is the sequence number containing the
* latest generation of the desired state. Read-only.
*/
generation?: number;
/**
* Not currently used by Cloud Run.
*/
serviceAccountName?: string;
/**
* ServingState holds a value describing the state the resources are in for
* this Revision. Users must not specify this when creating a revision. It
* is expected that the system will manipulate this based on routability and
* load. Populated by the system. Read-only.
*/
servingState?: string;
/**
* TimeoutSeconds holds the max duration the instance is allowed for
* responding to a request. Not currently used by Cloud Run.
*/
timeoutSeconds?: number;
}
/**
* RevisionStatus communicates the observed state of the Revision (from the
* controller).
*/
interface Schema$RevisionStatus {
/**
* Conditions communicates information about ongoing/complete reconciliation
* processes that bring the "spec" inline with the observed state
* of the world. As a Revision is being prepared, it will incrementally
* update conditions "ResourcesAvailable",
* "ContainerHealthy", and "Active", which contribute to
* the overall "Ready" condition.
*/
conditions?: Schema$RevisionCondition[];
/**
* ImageDigest holds the resolved digest for the image specified within
* .Spec.Container.Image. The digest is resolved during the creation of
* Revision. This field holds the digest value regardless of whether a tag
* or digest was originally specified in the Container object.
*/
imageDigest?: string;
/**
* Specifies the generated logging url for this particular revision based on
* the revision url template specified in the controller's config.
* +optional
*/
logUrl?: string;
/**
* ObservedGeneration is the 'Generation' of the Revision that was
* last processed by the controller. Clients polling for completed
* reconciliation should poll until observedGeneration =
* metadata.generation, and the Ready condition's status is True or
* False.
*/
observedGeneration?: number;
/**
* Not currently used by Cloud Run.
*/
serviceName?: string;
}
/**
* RevisionTemplateSpec describes the data a revision should have when created
* from a template. Based on:
* https://github.com/kubernetes/api/blob/e771f807/core/v1/types.go#L3179-L3190
*/
interface Schema$RevisionTemplate {
/**
* Optional metadata for this Revision, including labels and annotations.
* Name will be generated by the Configuration.
*/
metadata?: Schema$ObjectMeta;
/**
* RevisionSpec holds the desired state of the Revision (from the client).
*/
spec?: Schema$RevisionSpec;
}
/**
* Route is responsible for configuring ingress over a collection of
* Revisions. Some of the Revisions a Route distributes traffic over may be
* specified by referencing the Configuration responsible for creating them;
* in these cases the Route is additionally responsible for monitoring the
* Configuration for "latest ready" revision changes, and smoothly
* rolling out latest revisions. See also:
* https://github.com/knative/serving/blob/master/docs/spec/overview.md#route
* Cloud Run currently supports referencing a single Configuration to
* automatically deploy the "latest ready" Revision from that
* Configuration.
*/
interface Schema$Route {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* The kind of this resource, in this case always "Route".
*/
kind?: string;
/**
* Metadata associated with this Route, including name, namespace, labels,
* and annotations.
*/
metadata?: Schema$ObjectMeta;
/**
* Spec holds the desired state of the Route (from the client).
*/
spec?: Schema$RouteSpec;
/**
* Status communicates the observed state of the Route (from the
* controller).
*/
status?: Schema$RouteStatus;
}
/**
* RouteCondition defines a readiness condition for a Route.
*/
interface Schema$RouteCondition {
/**
* Last time the condition transitioned from one status to another.
* +optional
*/
lastTransitionTime?: string;
/**
* Human-readable message indicating details about last transition.
* +optional
*/
message?: string;
/**
* One-word CamelCase reason for the condition's last transition.
* +optional
*/
reason?: string;
/**
* Status of the condition, one of "True", "False",
* "Unknown".
*/
status?: string;
/**
* RouteConditionType is used to communicate the status of the
* reconciliation process. See also:
* https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting
* Types include: "Ready".
*/
type?: string;
}
/**
* RouteSpec holds the desired state of the Route (from the client).
*/
interface Schema$RouteSpec {
/**
* Deprecated and not currently populated by Cloud Run. See
* metadata.generation instead, which is the sequence number containing the
* latest generation of the desired state. Read-only.
*/
generation?: number;
/**
* Traffic specifies how to distribute traffic over a collection of Knative
* Revisions and Configurations. Cloud Run currently supports a single
* configurationName.
*/
traffic?: Schema$TrafficTarget[];
}
/**
* RouteStatus communicates the observed state of the Route (from the
* controller).
*/
interface Schema$RouteStatus {
/**
* Similar to domain, information on where the service is available on HTTP.
*/
address?: Schema$Addressable;
/**
* Conditions communicates information about ongoing/complete reconciliation
* processes that bring the "spec" inline with the observed state
* of the world.
*/
conditions?: Schema$RouteCondition[];
/**
* Domain holds the top-level domain that will distribute traffic over the
* provided targets. It generally has the form
* https://{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app
*/
domain?: string;
/**
* For Cloud Run, identifical to domain.
*/
domainInternal?: string;
/**
* ObservedGeneration is the 'Generation' of the Route that was last
* processed by the controller. Clients polling for completed
* reconciliation should poll until observedGeneration = metadata.generation
* and the Ready condition's status is True or False. Note that
* providing a trafficTarget that only has a configurationName will result
* in a Route that does not increment either its metadata.generation or its
* observedGeneration, as new "latest ready" revisions from the
* Configuration are processed without an update to the Route's spec.
*/
observedGeneration?: number;
/**
* Traffic holds the configured traffic distribution. These entries will
* always contain RevisionName references. When ConfigurationName appears in
* the spec, this will hold the LatestReadyRevisionName that we last
* observed.
*/
traffic?: Schema$TrafficTarget[];
}
/**
* SecretEnvSource selects a Secret to populate the environment variables
* with. The contents of the target Secret's Data field will represent
* the key-value pairs as environment variables.
*/
interface Schema$SecretEnvSource {
/**
* The Secret to select from.
*/
localObjectReference?: Schema$LocalObjectReference;
/**
* Specify whether the Secret must be defined +optional
*/
optional?: boolean;
}
/**
* SecurityContext holds security configuration that will be applied to a
* container. Some fields are present in both SecurityContext and
* PodSecurityContext. When both are set, the values in SecurityContext take
* precedence.
*/
interface Schema$SecurityContext {
/**
* AllowPrivilegeEscalation controls whether a process can gain more
* privileges than its parent process. This bool directly controls if the
* no_new_privs flag will be set on the container process.
* AllowPrivilegeEscalation is true always when the container is: 1) run as
* Privileged 2) has CAP_SYS_ADMIN +optional
*/
allowPrivilegeEscalation?: boolean;
/**
* The capabilities to add/drop when running containers. Defaults to the
* default set of capabilities granted by the container runtime. +optional
*/
capabilities?: Schema$Capabilities;
/**
* Run container in privileged mode. Processes in privileged containers are
* essentially equivalent to root on the host. Defaults to false. +optional
*/
privileged?: boolean;
/**
* Whether this container has a read-only root filesystem. Default is false.
* +optional
*/
readOnlyRootFilesystem?: boolean;
/**
* The GID to run the entrypoint of the container process. Uses runtime
* default if unset. May also be set in PodSecurityContext. If set in both
* SecurityContext and PodSecurityContext, the value specified in
* SecurityContext takes precedence. +optional
*/
runAsGroup?: string;
/**
* Indicates that the container must run as a non-root user. If true, the
* Kubelet will validate the image at runtime to ensure that it does not run
* as UID 0 (root) and fail to start the container if it does. If unset or
* false, no such validation will be performed. May also be set in
* PodSecurityContext. If set in both SecurityContext and
* PodSecurityContext, the value specified in SecurityContext takes
* precedence. +optional
*/
runAsNonRoot?: boolean;
/**
* The UID to run the entrypoint of the container process. Defaults to user
* specified in image metadata if unspecified. May also be set in
* PodSecurityContext. If set in both SecurityContext and
* PodSecurityContext, the value specified in SecurityContext takes
* precedence. +optional
*/
runAsUser?: string;
/**
* The SELinux context to be applied to the container. If unspecified, the
* container runtime will allocate a random SELinux context for each
* container. May also be set in PodSecurityContext. If set in both
* SecurityContext and PodSecurityContext, the value specified in
* SecurityContext takes precedence. +optional
*/
seLinuxOptions?: Schema$SELinuxOptions;
}
/**
* SELinuxOptions are the labels to be applied to the container
*/
interface Schema$SELinuxOptions {
/**
* Level is SELinux level label that applies to the container. +optional
*/
level?: string;
/**
* Role is a SELinux role label that applies to the container. +optional
*/
role?: string;
/**
* Type is a SELinux type label that applies to the container. +optional
*/
type?: string;
/**
* User is a SELinux user label that applies to the container. +optional
*/
user?: string;
}
/**
* Service acts as a top-level container that manages a set of Routes and
* Configurations which implement a network service. Service exists to provide
* a singular abstraction which can be access controlled, reasoned about, and
* which encapsulates software lifecycle decisions such as rollout policy and
* team resource ownership. Service acts only as an orchestrator of the
* underlying Routes and Configurations (much as a kubernetes Deployment
* orchestrates ReplicaSets). The Service's controller will track the
* statuses of its owned Configuration and Route, reflecting their statuses
* and conditions as its own. See also:
* https://github.com/knative/serving/blob/master/docs/spec/overview.md#service
*/
interface Schema$Service {
/**
* The API version for this call such as "v1alpha1".
*/
apiVersion?: string;
/**
* The kind of resource, in this case "Service".
*/
kind?: string;
/**
* Metadata associated with this Service, including name, namespace, labels,
* and annotations.
*/
metadata?: Schema$ObjectMeta;
/**
* Spec holds the desired state of the Service (from the client).
*/
spec?: Schema$ServiceSpec;
/**
* Status communicates the observed state of the Service (from the
* controller).
*/
status?: Schema$ServiceStatus;
}
/**
* ServiceCondition defines a readiness condition for a Service.
*/
interface Schema$ServiceCondition {
/**
* Last time the condition transitioned from one status to another.
* +optional
*/
lastTransitionTime?: string;
/**
* Human-readable message indicating details about last transition.
* +optional
*/
message?: string;
/**
* One-word CamelCase reason for the condition's last transition.
* +optional
*/
reason?: string;
/**
* Status of the condition, one of True, False, Unknown.
*/
status?: string;
/**
* ServiceConditionType is used to communicate the status of the
* reconciliation process. See also:
* https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting
* Types include: "Ready", "ConfigurationsReady", and
* "RoutesReady". "Ready" will be true when the
* underlying Route and Configuration are ready.
*/
type?: string;
}
/**
* ServiceSpec holds the desired state of the Route (from the client), which
* is used to manipulate the underlying Route and Configuration(s).
*/
interface Schema$ServiceSpec {
/**
* Deprecated and not currently populated by Cloud Run. See
* metadata.generation instead, which is the sequence number containing the
* latest generation of the desired state. Read-only.
*/
generation?: number;
/**
* Manual contains the options for configuring a manual service. See
* ServiceSpec for more details. Not currently supported by Cloud Run.
*/
manual?: Schema$ServiceSpecManualType;
/**
* Pins this service to a specific revision name. The revision must be owned
* by the configuration provided. Deprecated and not supported by Cloud
* Run. +optional
*/
pinned?: Schema$ServiceSpecPinnedType;
/**
* Release enables gradual promotion of new revisions by allowing traffic to
* be split between two revisions. This type replaces the deprecated Pinned
* type. Not currently supported by Cloud Run.
*/
release?: Schema$ServiceSpecReleaseType;
/**
* RunLatest defines a simple Service. It will automatically configure a
* route that keeps the latest ready revision from the supplied
* configuration running. +optional
*/
runLatest?: Schema$ServiceSpecRunLatest;
}
/**
* ServiceSpecManualType contains the options for configuring a manual
* service. See ServiceSpec for more details. Not currently supported by
* Cloud Run.
*/
interface Schema$ServiceSpecManualType {
}
/**
* ServiceSpecPinnedType Pins this service to a specific revision name. The
* revision must be owned by the configuration provided. Deprecated and not
* supported by Cloud Run.
*/
interface Schema$ServiceSpecPinnedType {
/**
* The configuration for this service.
*/
configuration?: Schema$ConfigurationSpec;
/**
* The revision name to pin this service to until changed to a different
* service type.
*/
revisionName?: string;
}
/**
* ServiceSpecReleaseType contains the options for slowly releasing revisions.
* See ServiceSpec for more details. Not currently supported by Cloud Run.
*/
interface Schema$ServiceSpecReleaseType {
/**
* The configuration for this service. All revisions from this service must
* come from a single configuration.
*/
configuration?: Schema$ConfigurationSpec;
/**
* Revisions is an ordered list of 1 or 2 revisions. The first is the
* current revision, and the second is the candidate revision. If a single
* revision is provided, traffic will be pinned at that revision.
* "@latest" is a shortcut for usage that refers to the latest
* created revision by the configuration.
*/
revisions?: string[];
/**
* RolloutPercent is the percent of traffic that should be sent to the
* candidate revision, i.e. the 2nd revision in the revisions list. Valid
* values are between 0 and 99 inclusive.
*/
rolloutPercent?: number;
}
/**
* ServiceSpecRunLatest contains the options for always having a route to the
* latest configuration. See ServiceSpec for more details.
*/
interface Schema$ServiceSpecRunLatest {
/**
* The configuration for this service.
*/
configuration?: Schema$ConfigurationSpec;
}
/**
* The current state of the Service. Output only.
*/
interface Schema$ServiceStatus {
/**
* From RouteStatus. Similar to domain, information on where the service is
* available on HTTP.
*/
address?: Schema$Addressable;
/**
* Conditions communicates information about ongoing/complete reconciliation
* processes that bring the "spec" inline with the observed state
* of the world.
*/
conditions?: Schema$ServiceCondition[];
/**
* From RouteStatus. Domain holds the top-level domain that will distribute
* traffic over the provided targets. It generally has the form
* https://{route-hash}-{project-hash}-{cluster-level-suffix}.a.run.app
*/
domain?: string;
/**
* From ConfigurationStatus. LatestCreatedRevisionName is the last revision
* that was created from this Service's Configuration. It might not be
* ready yet, for that use LatestReadyRevisionName.
*/
latestCreatedRevisionName?: string;
/**
* From ConfigurationStatus. LatestReadyRevisionName holds the name of the
* latest Revision stamped out from this Service's Configuration that
* has had its "Ready" condition become "True".
*/
latestReadyRevisionName?: string;
/**
* ObservedGeneration is the 'Generation' of the Route that was last
* processed by the controller. Clients polling for completed
* reconciliation should poll until observedGeneration = metadata.generation
* and the Ready condition's status is True or False.
*/
observedGeneration?: number;
/**
* From RouteStatus. Traffic holds the configured traffic distribution.
* These entries will always contain RevisionName references. When
* ConfigurationName appears in the spec, this will hold the
* LatestReadyRevisionName that we last observed.
*/
traffic?: Schema$TrafficTarget[];
}
/**
* Request message for `SetIamPolicy` method.
*/
interface Schema$SetIamPolicyRequest {
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size
* of the policy is limited to a few 10s of KB. An empty policy is a valid
* policy but certain Cloud Platform services (such as Projects) might
* reject them.
*/
policy?: Schema$Policy;
/**
* OPTIONAL: A FieldMask specifying which fields of the policy to modify.
* Only the fields in the mask will be modified. If no mask is provided, the
* following default mask is used: paths: "bindings, etag" This
* field is only used by Cloud IAM.
*/
updateMask?: string;
}
/**
* TCPSocketAction describes an action based on opening a socket
*/
interface Schema$TCPSocketAction {
/**
* Optional: Host name to connect to, defaults to the pod IP. +optional
*/
host?: string;
/**
* Number or name of the port to access on the container. Number must be in
* the range 1 to 65535. Name must be an IANA_SVC_NAME.
*/
port?: Schema$IntOrString;
}
/**
* Request message for `TestIamPermissions` method.
*/
interface Schema$TestIamPermissionsRequest {
/**
* The set of permissions to check for the `resource`. Permissions with
* wildcards (such as '*' or 'storage.*') are not allowed.
* For more information see [IAM
* Overview](https://cloud.google.com/iam/docs/overview#permissions).
*/
permissions?: string[];
}
/**
* Response message for `TestIamPermissions` method.
*/
interface Schema$TestIamPermissionsResponse {
/**
* A subset of `TestPermissionsRequest.permissions` that the caller is
* allowed.
*/
permissions?: string[];
}
/**
* TrafficTarget holds a single entry of the routing table for a Route.
*/
interface Schema$TrafficTarget {
/**
* ConfigurationName of a configuration to whose latest revision we will
* send this portion of traffic. When the
* "status.latestReadyRevisionName" of the referenced
* configuration changes, we will automatically migrate traffic from the
* prior "latest ready" revision to the new one. This field is
* never set in Route's status, only its spec. This is mutually
* exclusive with RevisionName. Cloud Run currently supports a single
* ConfigurationName.
*/
configurationName?: string;
/**
* Name is optionally used to expose a dedicated hostname for referencing
* this target exclusively. Not currently supported by Cloud Run. +optional
*/
name?: string;
/**
* Percent specifies percent of the traffic to this Revision or
* Configuration. This defaults to zero if unspecified. Cloud Run currently
* requires 100 percent for a single ConfigurationName TrafficTarget entry.
*/
percent?: number;
/**
* RevisionName of a specific revision to which to send this portion of
* traffic. This is mutually exclusive with ConfigurationName. Providing
* RevisionName in spec is not currently supported by Cloud Run.
*/
revisionName?: string;
}
/**
* volumeDevice describes a mapping of a raw block device within a container.
*/
interface Schema$VolumeDevice {
/**
* devicePath is the path inside of the container that the device will be
* mapped to.
*/
devicePath?: string;
/**
* name must match the name of a persistentVolumeClaim in the pod
*/
name?: string;
}
/**
* VolumeMount describes a mounting of a Volume within a container.
*/
interface Schema$VolumeMount {
/**
* Path within the container at which the volume should be mounted. Must
* not contain ':'.
*/
mountPath?: string;
/**
* mountPropagation determines how mounts are propagated from the host to
* container and the other way around. When not set,
* MountPropagationHostToContainer is used. This field is beta in 1.10.
* +optional
*/
mountPropagation?: string;
/**
* This must match the Name of a Volume.
*/
name?: string;
/**
* Mounted read-only if true, read-write otherwise (false or unspecified).
* Defaults to false. +optional
*/
readOnly?: boolean;
/**
* Path within the volume from which the container's volume should be
* mounted. Defaults to "" (volume's root). +optional
*/
subPath?: string;
}
class Resource$Namespaces {
context: APIRequestContext;
authorizeddomains: Resource$Namespaces$Authorizeddomains;
configurations: Resource$Namespaces$Configurations;
domainmappings: Resource$Namespaces$Domainmappings;
revisions: Resource$Namespaces$Revisions;
routes: Resource$Namespaces$Routes;
services: Resource$Namespaces$Services;
constructor(context: APIRequestContext);
}
class Resource$Namespaces$Authorizeddomains {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.authorizeddomains.list
* @desc RPC to list authorized domains.
* @alias run.namespaces.authorizeddomains.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {integer=} params.pageSize Maximum results to return per page.
* @param {string=} params.pageToken Continuation token for fetching the next page of results.
* @param {string} params.parent Name of the parent Application resource. Example: `apps/myapp`.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Authorizeddomains$List, options?: MethodOptions): GaxiosPromise<Schema$ListAuthorizedDomainsResponse>;
list(params: Params$Resource$Namespaces$Authorizeddomains$List, options: MethodOptions | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
list(params: Params$Resource$Namespaces$Authorizeddomains$List, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
}
interface Params$Resource$Namespaces$Authorizeddomains$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Maximum results to return per page.
*/
pageSize?: number;
/**
* Continuation token for fetching the next page of results.
*/
pageToken?: string;
/**
* Name of the parent Application resource. Example: `apps/myapp`.
*/
parent?: string;
}
class Resource$Namespaces$Configurations {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.configurations.get
* @desc Rpc to get information about a configuration.
* @alias run.namespaces.configurations.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the configuration being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Namespaces$Configurations$Get, options?: MethodOptions): GaxiosPromise<Schema$Configuration>;
get(params: Params$Resource$Namespaces$Configurations$Get, options: MethodOptions | BodyResponseCallback<Schema$Configuration>, callback: BodyResponseCallback<Schema$Configuration>): void;
get(params: Params$Resource$Namespaces$Configurations$Get, callback: BodyResponseCallback<Schema$Configuration>): void;
get(callback: BodyResponseCallback<Schema$Configuration>): void;
/**
* run.namespaces.configurations.list
* @desc Rpc to list configurations.
* @alias run.namespaces.configurations.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the configurations should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Configurations$List, options?: MethodOptions): GaxiosPromise<Schema$ListConfigurationsResponse>;
list(params: Params$Resource$Namespaces$Configurations$List, options: MethodOptions | BodyResponseCallback<Schema$ListConfigurationsResponse>, callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
list(params: Params$Resource$Namespaces$Configurations$List, callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
}
interface Params$Resource$Namespaces$Configurations$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the configuration being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Namespaces$Configurations$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the configurations should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Namespaces$Domainmappings {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.domainmappings.create
* @desc Creates a new domain mapping.
* @alias run.namespaces.domainmappings.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.parent The project ID or project number in which this domain mapping should be created.
* @param {().DomainMapping} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Namespaces$Domainmappings$Create, options?: MethodOptions): GaxiosPromise<Schema$DomainMapping>;
create(params: Params$Resource$Namespaces$Domainmappings$Create, options: MethodOptions | BodyResponseCallback<Schema$DomainMapping>, callback: BodyResponseCallback<Schema$DomainMapping>): void;
create(params: Params$Resource$Namespaces$Domainmappings$Create, callback: BodyResponseCallback<Schema$DomainMapping>): void;
create(callback: BodyResponseCallback<Schema$DomainMapping>): void;
/**
* run.namespaces.domainmappings.delete
* @desc Rpc to delete a domain mapping.
* @alias run.namespaces.domainmappings.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the domain mapping being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Namespaces$Domainmappings$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Namespaces$Domainmappings$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Namespaces$Domainmappings$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.namespaces.domainmappings.get
* @desc Rpc to get information about a domain mapping.
* @alias run.namespaces.domainmappings.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the domain mapping being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Namespaces$Domainmappings$Get, options?: MethodOptions): GaxiosPromise<Schema$DomainMapping>;
get(params: Params$Resource$Namespaces$Domainmappings$Get, options: MethodOptions | BodyResponseCallback<Schema$DomainMapping>, callback: BodyResponseCallback<Schema$DomainMapping>): void;
get(params: Params$Resource$Namespaces$Domainmappings$Get, callback: BodyResponseCallback<Schema$DomainMapping>): void;
get(callback: BodyResponseCallback<Schema$DomainMapping>): void;
/**
* run.namespaces.domainmappings.list
* @desc Rpc to list domain mappings.
* @alias run.namespaces.domainmappings.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the domain mappings should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Domainmappings$List, options?: MethodOptions): GaxiosPromise<Schema$ListDomainMappingsResponse>;
list(params: Params$Resource$Namespaces$Domainmappings$List, options: MethodOptions | BodyResponseCallback<Schema$ListDomainMappingsResponse>, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
list(params: Params$Resource$Namespaces$Domainmappings$List, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
}
interface Params$Resource$Namespaces$Domainmappings$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The project ID or project number in which this domain mapping should be
* created.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$DomainMapping;
}
interface Params$Resource$Namespaces$Domainmappings$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the domain mapping being deleted. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Namespaces$Domainmappings$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the domain mapping being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Namespaces$Domainmappings$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the domain mappings should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Namespaces$Revisions {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.revisions.delete
* @desc Rpc to delete a revision.
* @alias run.namespaces.revisions.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the revision being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Namespaces$Revisions$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Namespaces$Revisions$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Namespaces$Revisions$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.namespaces.revisions.get
* @desc Rpc to get information about a revision.
* @alias run.namespaces.revisions.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the revision being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Namespaces$Revisions$Get, options?: MethodOptions): GaxiosPromise<Schema$Revision>;
get(params: Params$Resource$Namespaces$Revisions$Get, options: MethodOptions | BodyResponseCallback<Schema$Revision>, callback: BodyResponseCallback<Schema$Revision>): void;
get(params: Params$Resource$Namespaces$Revisions$Get, callback: BodyResponseCallback<Schema$Revision>): void;
get(callback: BodyResponseCallback<Schema$Revision>): void;
/**
* run.namespaces.revisions.list
* @desc Rpc to list revisions.
* @alias run.namespaces.revisions.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the revisions should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Revisions$List, options?: MethodOptions): GaxiosPromise<Schema$ListRevisionsResponse>;
list(params: Params$Resource$Namespaces$Revisions$List, options: MethodOptions | BodyResponseCallback<Schema$ListRevisionsResponse>, callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
list(params: Params$Resource$Namespaces$Revisions$List, callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
}
interface Params$Resource$Namespaces$Revisions$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the revision being deleted. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Namespaces$Revisions$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the revision being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Namespaces$Revisions$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the revisions should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Namespaces$Routes {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.routes.get
* @desc Rpc to get information about a route.
* @alias run.namespaces.routes.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the route being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Namespaces$Routes$Get, options?: MethodOptions): GaxiosPromise<Schema$Route>;
get(params: Params$Resource$Namespaces$Routes$Get, options: MethodOptions | BodyResponseCallback<Schema$Route>, callback: BodyResponseCallback<Schema$Route>): void;
get(params: Params$Resource$Namespaces$Routes$Get, callback: BodyResponseCallback<Schema$Route>): void;
get(callback: BodyResponseCallback<Schema$Route>): void;
/**
* run.namespaces.routes.list
* @desc Rpc to list routes.
* @alias run.namespaces.routes.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the routes should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Routes$List, options?: MethodOptions): GaxiosPromise<Schema$ListRoutesResponse>;
list(params: Params$Resource$Namespaces$Routes$List, options: MethodOptions | BodyResponseCallback<Schema$ListRoutesResponse>, callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
list(params: Params$Resource$Namespaces$Routes$List, callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
list(callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
}
interface Params$Resource$Namespaces$Routes$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the route being retrieved. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
}
interface Params$Resource$Namespaces$Routes$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the routes should be listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Namespaces$Services {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.namespaces.services.create
* @desc Rpc to create a service.
* @alias run.namespaces.services.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.parent The project ID or project number in which this service should be created.
* @param {().Service} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Namespaces$Services$Create, options?: MethodOptions): GaxiosPromise<Schema$Service>;
create(params: Params$Resource$Namespaces$Services$Create, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
create(params: Params$Resource$Namespaces$Services$Create, callback: BodyResponseCallback<Schema$Service>): void;
create(callback: BodyResponseCallback<Schema$Service>): void;
/**
* run.namespaces.services.delete
* @desc Rpc to delete a service. This will cause the Service to stop
* serving traffic and will delete the child entities like Routes,
* Configurations and Revisions.
* @alias run.namespaces.services.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the service being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Namespaces$Services$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Namespaces$Services$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Namespaces$Services$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.namespaces.services.get
* @desc Rpc to get information about a service.
* @alias run.namespaces.services.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the service being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Namespaces$Services$Get, options?: MethodOptions): GaxiosPromise<Schema$Service>;
get(params: Params$Resource$Namespaces$Services$Get, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
get(params: Params$Resource$Namespaces$Services$Get, callback: BodyResponseCallback<Schema$Service>): void;
get(callback: BodyResponseCallback<Schema$Service>): void;
/**
* run.namespaces.services.list
* @desc Rpc to list services.
* @alias run.namespaces.services.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the services should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Namespaces$Services$List, options?: MethodOptions): GaxiosPromise<Schema$ListServicesResponse>;
list(params: Params$Resource$Namespaces$Services$List, options: MethodOptions | BodyResponseCallback<Schema$ListServicesResponse>, callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
list(params: Params$Resource$Namespaces$Services$List, callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
list(callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
/**
* run.namespaces.services.replaceService
* @desc Rpc to replace a service. Only the spec and metadata labels and
* annotations are modifiable. After the Update request, Cloud Run will work
* to make the 'status' match the requested 'spec'. May provide
* metadata.resourceVersion to enforce update from last read for optimistic
* concurrency control.
* @alias run.namespaces.services.replaceService
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the service being replaced. If needed, replace {namespace_id} with the project ID.
* @param {().Service} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
replaceService(params?: Params$Resource$Namespaces$Services$Replaceservice, options?: MethodOptions): GaxiosPromise<Schema$Service>;
replaceService(params: Params$Resource$Namespaces$Services$Replaceservice, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
replaceService(params: Params$Resource$Namespaces$Services$Replaceservice, callback: BodyResponseCallback<Schema$Service>): void;
replaceService(callback: BodyResponseCallback<Schema$Service>): void;
}
interface Params$Resource$Namespaces$Services$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The project ID or project number in which this service should be created.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$Service;
}
interface Params$Resource$Namespaces$Services$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the service being deleted. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Namespaces$Services$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the service being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Namespaces$Services$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the services should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
interface Params$Resource$Namespaces$Services$Replaceservice extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the service being replaced. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Request body metadata
*/
requestBody?: Schema$Service;
}
class Resource$Projects {
context: APIRequestContext;
locations: Resource$Projects$Locations;
constructor(context: APIRequestContext);
}
class Resource$Projects$Locations {
context: APIRequestContext;
authorizeddomains: Resource$Projects$Locations$Authorizeddomains;
configurations: Resource$Projects$Locations$Configurations;
domainmappings: Resource$Projects$Locations$Domainmappings;
revisions: Resource$Projects$Locations$Revisions;
routes: Resource$Projects$Locations$Routes;
services: Resource$Projects$Locations$Services;
constructor(context: APIRequestContext);
/**
* run.projects.locations.list
* @desc Lists information about the supported locations for this service.
* @alias run.projects.locations.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.filter The standard list filter.
* @param {string} params.name The resource that owns the locations collection, if applicable.
* @param {integer=} params.pageSize The standard list page size.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$List, options?: MethodOptions): GaxiosPromise<Schema$ListLocationsResponse>;
list(params: Params$Resource$Projects$Locations$List, options: MethodOptions | BodyResponseCallback<Schema$ListLocationsResponse>, callback: BodyResponseCallback<Schema$ListLocationsResponse>): void;
list(params: Params$Resource$Projects$Locations$List, callback: BodyResponseCallback<Schema$ListLocationsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListLocationsResponse>): void;
}
interface Params$Resource$Projects$Locations$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The standard list filter.
*/
filter?: string;
/**
* The resource that owns the locations collection, if applicable.
*/
name?: string;
/**
* The standard list page size.
*/
pageSize?: number;
/**
* The standard list page token.
*/
pageToken?: string;
}
class Resource$Projects$Locations$Authorizeddomains {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.authorizeddomains.list
* @desc RPC to list authorized domains.
* @alias run.projects.locations.authorizeddomains.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {integer=} params.pageSize Maximum results to return per page.
* @param {string=} params.pageToken Continuation token for fetching the next page of results.
* @param {string} params.parent Name of the parent Application resource. Example: `apps/myapp`.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Authorizeddomains$List, options?: MethodOptions): GaxiosPromise<Schema$ListAuthorizedDomainsResponse>;
list(params: Params$Resource$Projects$Locations$Authorizeddomains$List, options: MethodOptions | BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
list(params: Params$Resource$Projects$Locations$Authorizeddomains$List, callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListAuthorizedDomainsResponse>): void;
}
interface Params$Resource$Projects$Locations$Authorizeddomains$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Maximum results to return per page.
*/
pageSize?: number;
/**
* Continuation token for fetching the next page of results.
*/
pageToken?: string;
/**
* Name of the parent Application resource. Example: `apps/myapp`.
*/
parent?: string;
}
class Resource$Projects$Locations$Configurations {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.configurations.get
* @desc Rpc to get information about a configuration.
* @alias run.projects.locations.configurations.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the configuration being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Projects$Locations$Configurations$Get, options?: MethodOptions): GaxiosPromise<Schema$Configuration>;
get(params: Params$Resource$Projects$Locations$Configurations$Get, options: MethodOptions | BodyResponseCallback<Schema$Configuration>, callback: BodyResponseCallback<Schema$Configuration>): void;
get(params: Params$Resource$Projects$Locations$Configurations$Get, callback: BodyResponseCallback<Schema$Configuration>): void;
get(callback: BodyResponseCallback<Schema$Configuration>): void;
/**
* run.projects.locations.configurations.list
* @desc Rpc to list configurations.
* @alias run.projects.locations.configurations.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the configurations should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Configurations$List, options?: MethodOptions): GaxiosPromise<Schema$ListConfigurationsResponse>;
list(params: Params$Resource$Projects$Locations$Configurations$List, options: MethodOptions | BodyResponseCallback<Schema$ListConfigurationsResponse>, callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
list(params: Params$Resource$Projects$Locations$Configurations$List, callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListConfigurationsResponse>): void;
}
interface Params$Resource$Projects$Locations$Configurations$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the configuration being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Projects$Locations$Configurations$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the configurations should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Projects$Locations$Domainmappings {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.domainmappings.create
* @desc Creates a new domain mapping.
* @alias run.projects.locations.domainmappings.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.parent The project ID or project number in which this domain mapping should be created.
* @param {().DomainMapping} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Projects$Locations$Domainmappings$Create, options?: MethodOptions): GaxiosPromise<Schema$DomainMapping>;
create(params: Params$Resource$Projects$Locations$Domainmappings$Create, options: MethodOptions | BodyResponseCallback<Schema$DomainMapping>, callback: BodyResponseCallback<Schema$DomainMapping>): void;
create(params: Params$Resource$Projects$Locations$Domainmappings$Create, callback: BodyResponseCallback<Schema$DomainMapping>): void;
create(callback: BodyResponseCallback<Schema$DomainMapping>): void;
/**
* run.projects.locations.domainmappings.delete
* @desc Rpc to delete a domain mapping.
* @alias run.projects.locations.domainmappings.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the domain mapping being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Projects$Locations$Domainmappings$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Projects$Locations$Domainmappings$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Projects$Locations$Domainmappings$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.projects.locations.domainmappings.get
* @desc Rpc to get information about a domain mapping.
* @alias run.projects.locations.domainmappings.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the domain mapping being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Projects$Locations$Domainmappings$Get, options?: MethodOptions): GaxiosPromise<Schema$DomainMapping>;
get(params: Params$Resource$Projects$Locations$Domainmappings$Get, options: MethodOptions | BodyResponseCallback<Schema$DomainMapping>, callback: BodyResponseCallback<Schema$DomainMapping>): void;
get(params: Params$Resource$Projects$Locations$Domainmappings$Get, callback: BodyResponseCallback<Schema$DomainMapping>): void;
get(callback: BodyResponseCallback<Schema$DomainMapping>): void;
/**
* run.projects.locations.domainmappings.list
* @desc Rpc to list domain mappings.
* @alias run.projects.locations.domainmappings.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the domain mappings should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Domainmappings$List, options?: MethodOptions): GaxiosPromise<Schema$ListDomainMappingsResponse>;
list(params: Params$Resource$Projects$Locations$Domainmappings$List, options: MethodOptions | BodyResponseCallback<Schema$ListDomainMappingsResponse>, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
list(params: Params$Resource$Projects$Locations$Domainmappings$List, callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListDomainMappingsResponse>): void;
}
interface Params$Resource$Projects$Locations$Domainmappings$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The project ID or project number in which this domain mapping should be
* created.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$DomainMapping;
}
interface Params$Resource$Projects$Locations$Domainmappings$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the domain mapping being deleted. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Projects$Locations$Domainmappings$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the domain mapping being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Projects$Locations$Domainmappings$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the domain mappings should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Projects$Locations$Revisions {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.revisions.delete
* @desc Rpc to delete a revision.
* @alias run.projects.locations.revisions.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the revision being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Projects$Locations$Revisions$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Projects$Locations$Revisions$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Projects$Locations$Revisions$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.projects.locations.revisions.get
* @desc Rpc to get information about a revision.
* @alias run.projects.locations.revisions.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the revision being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Projects$Locations$Revisions$Get, options?: MethodOptions): GaxiosPromise<Schema$Revision>;
get(params: Params$Resource$Projects$Locations$Revisions$Get, options: MethodOptions | BodyResponseCallback<Schema$Revision>, callback: BodyResponseCallback<Schema$Revision>): void;
get(params: Params$Resource$Projects$Locations$Revisions$Get, callback: BodyResponseCallback<Schema$Revision>): void;
get(callback: BodyResponseCallback<Schema$Revision>): void;
/**
* run.projects.locations.revisions.list
* @desc Rpc to list revisions.
* @alias run.projects.locations.revisions.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the revisions should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Revisions$List, options?: MethodOptions): GaxiosPromise<Schema$ListRevisionsResponse>;
list(params: Params$Resource$Projects$Locations$Revisions$List, options: MethodOptions | BodyResponseCallback<Schema$ListRevisionsResponse>, callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
list(params: Params$Resource$Projects$Locations$Revisions$List, callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
list(callback: BodyResponseCallback<Schema$ListRevisionsResponse>): void;
}
interface Params$Resource$Projects$Locations$Revisions$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the revision being deleted. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Projects$Locations$Revisions$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the revision being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Projects$Locations$Revisions$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the revisions should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Projects$Locations$Routes {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.routes.get
* @desc Rpc to get information about a route.
* @alias run.projects.locations.routes.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the route being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Projects$Locations$Routes$Get, options?: MethodOptions): GaxiosPromise<Schema$Route>;
get(params: Params$Resource$Projects$Locations$Routes$Get, options: MethodOptions | BodyResponseCallback<Schema$Route>, callback: BodyResponseCallback<Schema$Route>): void;
get(params: Params$Resource$Projects$Locations$Routes$Get, callback: BodyResponseCallback<Schema$Route>): void;
get(callback: BodyResponseCallback<Schema$Route>): void;
/**
* run.projects.locations.routes.list
* @desc Rpc to list routes.
* @alias run.projects.locations.routes.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the routes should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Routes$List, options?: MethodOptions): GaxiosPromise<Schema$ListRoutesResponse>;
list(params: Params$Resource$Projects$Locations$Routes$List, options: MethodOptions | BodyResponseCallback<Schema$ListRoutesResponse>, callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
list(params: Params$Resource$Projects$Locations$Routes$List, callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
list(callback: BodyResponseCallback<Schema$ListRoutesResponse>): void;
}
interface Params$Resource$Projects$Locations$Routes$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the route being retrieved. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
}
interface Params$Resource$Projects$Locations$Routes$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the routes should be listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
class Resource$Projects$Locations$Services {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* run.projects.locations.services.create
* @desc Rpc to create a service.
* @alias run.projects.locations.services.create
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.parent The project ID or project number in which this service should be created.
* @param {().Service} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
create(params?: Params$Resource$Projects$Locations$Services$Create, options?: MethodOptions): GaxiosPromise<Schema$Service>;
create(params: Params$Resource$Projects$Locations$Services$Create, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
create(params: Params$Resource$Projects$Locations$Services$Create, callback: BodyResponseCallback<Schema$Service>): void;
create(callback: BodyResponseCallback<Schema$Service>): void;
/**
* run.projects.locations.services.delete
* @desc Rpc to delete a service. This will cause the Service to stop
* serving traffic and will delete the child entities like Routes,
* Configurations and Revisions.
* @alias run.projects.locations.services.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.apiVersion Cloud Run currently ignores this parameter.
* @param {string=} params.kind Cloud Run currently ignores this parameter.
* @param {string} params.name The name of the service being deleted. If needed, replace {namespace_id} with the project ID.
* @param {boolean=} params.orphanDependents Deprecated. Specifies the cascade behavior on delete. Cloud Run only supports cascading behavior, so this must be false. This attribute is deprecated, and is now replaced with PropagationPolicy See https://github.com/kubernetes/kubernetes/issues/46659 for more info.
* @param {string=} params.propagationPolicy Specifies the propagation policy of delete. Cloud Run currently ignores this setting, and deletes in the background. Please see kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for more information.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$Projects$Locations$Services$Delete, options?: MethodOptions): GaxiosPromise<Schema$Empty>;
delete(params: Params$Resource$Projects$Locations$Services$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty>): void;
delete(params: Params$Resource$Projects$Locations$Services$Delete, callback: BodyResponseCallback<Schema$Empty>): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
/**
* run.projects.locations.services.get
* @desc Rpc to get information about a service.
* @alias run.projects.locations.services.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the service being retrieved. If needed, replace {namespace_id} with the project ID.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$Projects$Locations$Services$Get, options?: MethodOptions): GaxiosPromise<Schema$Service>;
get(params: Params$Resource$Projects$Locations$Services$Get, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
get(params: Params$Resource$Projects$Locations$Services$Get, callback: BodyResponseCallback<Schema$Service>): void;
get(callback: BodyResponseCallback<Schema$Service>): void;
/**
* run.projects.locations.services.getIamPolicy
* @desc Get the IAM Access Control policy currently in effect for the given
* Cloud Run service. This result does not include any inherited policies.
* @alias run.projects.locations.services.getIamPolicy
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.resource_ REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
getIamPolicy(params?: Params$Resource$Projects$Locations$Services$Getiampolicy, options?: MethodOptions): GaxiosPromise<Schema$Policy>;
getIamPolicy(params: Params$Resource$Projects$Locations$Services$Getiampolicy, options: MethodOptions | BodyResponseCallback<Schema$Policy>, callback: BodyResponseCallback<Schema$Policy>): void;
getIamPolicy(params: Params$Resource$Projects$Locations$Services$Getiampolicy, callback: BodyResponseCallback<Schema$Policy>): void;
getIamPolicy(callback: BodyResponseCallback<Schema$Policy>): void;
/**
* run.projects.locations.services.list
* @desc Rpc to list services.
* @alias run.projects.locations.services.list
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.continue Optional encoded string to continue paging.
* @param {string=} params.fieldSelector Allows to filter resources based on a specific value for a field name. Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not currently used by Cloud Run.
* @param {boolean=} params.includeUninitialized Not currently used by Cloud Run.
* @param {string=} params.labelSelector Allows to filter resources based on a label. Supported operations are =, !=, exists, in, and notIn.
* @param {integer=} params.limit The maximum number of records that should be returned.
* @param {string} params.parent The project ID or project number from which the services should be listed.
* @param {string=} params.resourceVersion The baseline resource version from which the list or watch operation should start. Not currently used by Cloud Run.
* @param {boolean=} params.watch Flag that indicates that the client expects to watch this resource as well. Not currently used by Cloud Run.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$Projects$Locations$Services$List, options?: MethodOptions): GaxiosPromise<Schema$ListServicesResponse>;
list(params: Params$Resource$Projects$Locations$Services$List, options: MethodOptions | BodyResponseCallback<Schema$ListServicesResponse>, callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
list(params: Params$Resource$Projects$Locations$Services$List, callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
list(callback: BodyResponseCallback<Schema$ListServicesResponse>): void;
/**
* run.projects.locations.services.replaceService
* @desc Rpc to replace a service. Only the spec and metadata labels and
* annotations are modifiable. After the Update request, Cloud Run will work
* to make the 'status' match the requested 'spec'. May provide
* metadata.resourceVersion to enforce update from last read for optimistic
* concurrency control.
* @alias run.projects.locations.services.replaceService
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the service being replaced. If needed, replace {namespace_id} with the project ID.
* @param {().Service} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
replaceService(params?: Params$Resource$Projects$Locations$Services$Replaceservice, options?: MethodOptions): GaxiosPromise<Schema$Service>;
replaceService(params: Params$Resource$Projects$Locations$Services$Replaceservice, options: MethodOptions | BodyResponseCallback<Schema$Service>, callback: BodyResponseCallback<Schema$Service>): void;
replaceService(params: Params$Resource$Projects$Locations$Services$Replaceservice, callback: BodyResponseCallback<Schema$Service>): void;
replaceService(callback: BodyResponseCallback<Schema$Service>): void;
/**
* run.projects.locations.services.setIamPolicy
* @desc Sets the IAM Access control policy for the specified Service.
* Overwrites any existing policy.
* @alias run.projects.locations.services.setIamPolicy
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.resource_ REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field.
* @param {().SetIamPolicyRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
setIamPolicy(params?: Params$Resource$Projects$Locations$Services$Setiampolicy, options?: MethodOptions): GaxiosPromise<Schema$Policy>;
setIamPolicy(params: Params$Resource$Projects$Locations$Services$Setiampolicy, options: MethodOptions | BodyResponseCallback<Schema$Policy>, callback: BodyResponseCallback<Schema$Policy>): void;
setIamPolicy(params: Params$Resource$Projects$Locations$Services$Setiampolicy, callback: BodyResponseCallback<Schema$Policy>): void;
setIamPolicy(callback: BodyResponseCallback<Schema$Policy>): void;
/**
* run.projects.locations.services.testIamPermissions
* @desc Returns permissions that a caller has on the specified Project.
* There are no permissions required for making this API call.
* @alias run.projects.locations.services.testIamPermissions
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string} params.resource_ REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field.
* @param {().TestIamPermissionsRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
testIamPermissions(params?: Params$Resource$Projects$Locations$Services$Testiampermissions, options?: MethodOptions): GaxiosPromise<Schema$TestIamPermissionsResponse>;
testIamPermissions(params: Params$Resource$Projects$Locations$Services$Testiampermissions, options: MethodOptions | BodyResponseCallback<Schema$TestIamPermissionsResponse>, callback: BodyResponseCallback<Schema$TestIamPermissionsResponse>): void;
testIamPermissions(params: Params$Resource$Projects$Locations$Services$Testiampermissions, callback: BodyResponseCallback<Schema$TestIamPermissionsResponse>): void;
testIamPermissions(callback: BodyResponseCallback<Schema$TestIamPermissionsResponse>): void;
}
interface Params$Resource$Projects$Locations$Services$Create extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The project ID or project number in which this service should be created.
*/
parent?: string;
/**
* Request body metadata
*/
requestBody?: Schema$Service;
}
interface Params$Resource$Projects$Locations$Services$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Cloud Run currently ignores this parameter.
*/
apiVersion?: string;
/**
* Cloud Run currently ignores this parameter.
*/
kind?: string;
/**
* The name of the service being deleted. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Deprecated. Specifies the cascade behavior on delete. Cloud Run only
* supports cascading behavior, so this must be false. This attribute is
* deprecated, and is now replaced with PropagationPolicy See
* https://github.com/kubernetes/kubernetes/issues/46659 for more info.
*/
orphanDependents?: boolean;
/**
* Specifies the propagation policy of delete. Cloud Run currently ignores
* this setting, and deletes in the background. Please see
* kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/ for
* more information.
*/
propagationPolicy?: string;
}
interface Params$Resource$Projects$Locations$Services$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the service being retrieved. If needed, replace
* {namespace_id} with the project ID.
*/
name?: string;
}
interface Params$Resource$Projects$Locations$Services$Getiampolicy extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* REQUIRED: The resource for which the policy is being requested. See the
* operation documentation for the appropriate value for this field.
*/
resource?: string;
}
interface Params$Resource$Projects$Locations$Services$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Optional encoded string to continue paging.
*/
continue?: string;
/**
* Allows to filter resources based on a specific value for a field name.
* Send this in a query string format. i.e. 'metadata.name%3Dlorem'. Not
* currently used by Cloud Run.
*/
fieldSelector?: string;
/**
* Not currently used by Cloud Run.
*/
includeUninitialized?: boolean;
/**
* Allows to filter resources based on a label. Supported operations are =,
* !=, exists, in, and notIn.
*/
labelSelector?: string;
/**
* The maximum number of records that should be returned.
*/
limit?: number;
/**
* The project ID or project number from which the services should be
* listed.
*/
parent?: string;
/**
* The baseline resource version from which the list or watch operation
* should start. Not currently used by Cloud Run.
*/
resourceVersion?: string;
/**
* Flag that indicates that the client expects to watch this resource as
* well. Not currently used by Cloud Run.
*/
watch?: boolean;
}
interface Params$Resource$Projects$Locations$Services$Replaceservice extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The name of the service being replaced. If needed, replace {namespace_id}
* with the project ID.
*/
name?: string;
/**
* Request body metadata
*/
requestBody?: Schema$Service;
}
interface Params$Resource$Projects$Locations$Services$Setiampolicy extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* REQUIRED: The resource for which the policy is being specified. See the
* operation documentation for the appropriate value for this field.
*/
resource?: string;
/**
* Request body metadata
*/
requestBody?: Schema$SetIamPolicyRequest;
}
interface Params$Resource$Projects$Locations$Services$Testiampermissions extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* REQUIRED: The resource for which the policy detail is being requested.
* See the operation documentation for the appropriate value for this field.
*/
resource?: string;
/**
* Request body metadata
*/
requestBody?: Schema$TestIamPermissionsRequest;
}
} | the_stack |
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import * as IltUtil from "./IltUtil";
import testbase from "test-base";
const log = testbase.logging.log;
import ExtendedEnumerationWithPartlyDefinedValues from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedEnumerationWithPartlyDefinedValues";
import ExtendedTypeCollectionEnumerationInTypeCollection from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedTypeCollectionEnumerationInTypeCollection";
import Enumeration from "../generated-javascript/joynr/interlanguagetest/Enumeration";
import MapStringString from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/MapStringString";
import ArrayTypeDefStruct from "../generated-javascript/joynr/interlanguagetest/typeDefCollection/ArrayTypeDefStruct";
import joynr from "joynr";
import TestInterfaceProxy from "../generated-javascript/joynr/interlanguagetest/TestInterfaceProxy";
import WebSocketLibjoynrRuntime from "joynr/joynr/start/WebSocketLibjoynrRuntime";
import UdsLibJoynrRuntime from "joynr/joynr/start/UdsLibJoynrRuntime";
if (process.env.domain === undefined) {
log("please pass a domain as argument");
process.exit(0);
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const domain: string = process.env.domain!;
log(`domain: ${domain}`);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const runtime: string = process.env.runtime!;
log(`runtime: ${runtime}`);
describe("Consumer test", () => {
const provisioning = testbase.provisioning_common;
if (process.env.runtime !== undefined) {
if (runtime === "websocket") {
// provisioning data are defined in test-base
joynr.selectRuntime(WebSocketLibjoynrRuntime);
} else if (runtime === "uds") {
if (!process.env.udspath || !process.env.udsclientid || !process.env.udsconnectsleeptimems) {
log("please pass udspath, udsclientid, udsconnectsleeptimems as argument");
process.exit(1);
}
provisioning.uds = {
socketPath: process.env.udspath,
clientId: process.env.udsclientid,
connectSleepTimeMs: Number(process.env.udsconnectsleeptimems)
};
joynr.selectRuntime(UdsLibJoynrRuntime);
}
}
provisioning.persistency = {
clearPersistency: true
};
let testInterfaceProxy: TestInterfaceProxy;
let onErrorSpy: jest.Mock;
async function loadJoynr(compressed: any) {
log("Environment not yet setup");
await joynr.load(provisioning);
log("joynr started");
const messagingQos = new joynr.messaging.MessagingQos({
ttl: 60000,
compress: compressed
});
log(`messagingQos - compressed = ${compressed}`);
testInterfaceProxy = await joynr.proxyBuilder.build<TestInterfaceProxy>(TestInterfaceProxy, {
domain,
messagingQos
});
log("testInterface proxy build");
}
describe("with compressed joynr", () => {
beforeAll(async () => {
return await loadJoynr(true);
});
it("callMethodWithoutParametersCompressed", async () => {
log("callMethodWithoutParametersCompressed");
await testInterfaceProxy.methodWithoutParameters();
});
afterAll(async () => {
await joynr.shutdown();
});
});
describe("without compressed joynr", () => {
beforeAll(async () => {
return await loadJoynr(false);
});
beforeEach(() => {
onErrorSpy = jest.fn();
});
it("proxy is defined", () => {
expect(testInterfaceProxy).toBeDefined();
});
it("callMethodWithoutParameters", async () => {
log("callMethodWithoutParameters");
return await testInterfaceProxy.methodWithoutParameters();
});
it("callMethodWithoutInputParameter", async () => {
log("callMethodWithoutInputParameter");
const retObj = await testInterfaceProxy.methodWithoutInputParameter();
expect(retObj).toBeDefined();
expect(retObj.booleanOut).toBeDefined();
expect(retObj.booleanOut).toBeTruthy();
});
it("callMethodWithoutOutputParameter", async () => {
log("callMethodWithoutOutputParameter");
const args = {
booleanArg: false
};
await testInterfaceProxy.methodWithoutOutputParameter(args);
log("callMethodWithoutOutputParameter - OK");
});
it("callMethodWithSinglePrimitiveParameters", async () => {
log("callMethodWithSinglePrimitiveParameters");
const args = {
uInt16Arg: 32767
};
const retObj = await testInterfaceProxy.methodWithSinglePrimitiveParameters(args);
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
const x = 32767;
expect(retObj.stringOut).toEqual(x.toString());
log("callMethodWithSinglePrimitiveParameters - OK");
});
it("callMethodWithMultiplePrimitiveParameters", async () => {
const arg2 = 47.11;
log("callMethodWithMultiplePrimitiveParameters");
const args = {
int32Arg: 2147483647,
floatArg: arg2,
booleanArg: false
};
const retObj = await testInterfaceProxy.methodWithMultiplePrimitiveParameters(args);
expect(retObj).toBeDefined();
expect(retObj.doubleOut).toBeDefined();
expect(retObj.stringOut).toBeDefined();
const x = 2147483647;
expect(retObj.doubleOut).toBeCloseTo(arg2);
expect(retObj.stringOut).toEqual(x.toString());
log("callMethodWithMultiplePrimitiveParameters - OK");
});
it("callMethodWithSingleArrayParameters", async () => {
log("callMethodWithSingleArrayParameters");
const doubleArray = IltUtil.create("DoubleArray");
const args = {
doubleArrayArg: doubleArray
};
const retObj = await testInterfaceProxy.methodWithSingleArrayParameters(args);
expect(retObj).toBeDefined();
expect(retObj.stringArrayOut).toBeDefined();
expect(IltUtil.check("StringArray", retObj.stringArrayOut)).toBeTruthy();
log("callMethodWithSingleArrayParameters - OK");
});
it("callMethodWithMultipleArrayParameters", async () => {
log("callMethodWithMultipleArrayParameters");
const args = {
stringArrayArg: IltUtil.create("StringArray"),
int8ArrayArg: IltUtil.create("ByteArray"),
enumArrayArg: IltUtil.create("ExtendedInterfaceEnumInTypeCollectionArray"),
structWithStringArrayArrayArg: IltUtil.create("StructWithStringArrayArray")
};
const retObj = await testInterfaceProxy.methodWithMultipleArrayParameters(args);
expect(retObj).toBeDefined();
expect(retObj.uInt64ArrayOut).toBeDefined();
expect(retObj.structWithStringArrayArrayOut).toBeDefined();
expect(retObj.structWithStringArrayArrayOut).not.toBeNull();
expect(IltUtil.check("UInt64Array", retObj.uInt64ArrayOut)).toBeTruthy();
expect(IltUtil.check("StructWithStringArrayArray", retObj.structWithStringArrayArrayOut)).toBeTruthy();
log("callMethodWithMultipleArrayParameters - OK");
});
async function callProxyMethodWithParameter(testMethod: any, testValue: any) {
log(`callProxyMethodWithParameter called with testValue = ${JSON.stringify(testValue)}`);
const retObj = await testMethod(testValue);
expect(retObj).toBeDefined();
expect(Object.values(retObj)[0]).toBeDefined();
log(`returned value: ${JSON.stringify(Object.values(retObj)[0])}`);
expect(Object.values(retObj)[0]).toEqual(Object.values(testValue)[0]);
return retObj;
}
it("callMethodWithSingleByteBufferParameter", async () => {
const byteBufferArg = [-128, 0, 127];
log("callMethodWithSingleByteBufferParameter");
const args = {
byteBufferIn: byteBufferArg
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithSingleByteBufferParameter, args);
log("callMethodWithSingleByteBufferParameter - OK");
});
it("callMethodWithMultipleByteBufferParameters", async () => {
const byteBufferArg1 = [-5, 125];
const byteBufferArg2 = [78, 0];
log("callMethodWithMultipleByteBufferParameters");
const args = {
byteBufferIn1: byteBufferArg1,
byteBufferIn2: byteBufferArg2
};
const retObj = await testInterfaceProxy.methodWithMultipleByteBufferParameters(args);
expect(retObj).toBeDefined();
expect(retObj.byteBufferOut).toBeDefined();
expect(IltUtil.cmpByteBuffers(retObj.byteBufferOut, byteBufferArg1.concat(byteBufferArg2))).toBeTruthy();
log("callMethodWithMultipleByteBufferParameters - OK");
});
it("callMethodWithInt64TypeDefParameter", async () => {
log("callMethodWithInt64TypeDefParameter");
const args = {
int64TypeDefIn: 1
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithInt64TypeDefParameter, args);
log("callMethodWithInt64TypeDefParameter - OK");
});
it("callMethodWithStringTypeDefParameter", async () => {
log("callMethodWithStringTypeDefParameter");
const args = {
stringTypeDefIn: "TypeDefTestString"
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithStringTypeDefParameter, args);
log("callMethodWithStringTypeDefParameter - OK");
});
it("callMethodWithStructTypeDefParameter", async () => {
log("callMethodWithStructTypeDefParameter");
const args = {
structTypeDefIn: IltUtil.create("BaseStruct")
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithStructTypeDefParameter, args);
log("callMethodWithStructTypeDefParameter - OK");
});
it("callMethodWithMapTypeDefParameter", async () => {
log("callMethodWithMapTypeDefParameter");
const value = new MapStringString();
for (let i = 1; i <= 3; i++) {
value.put(`keyString${i}`, `valueString${i}`);
}
const args = {
mapTypeDefIn: value
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithMapTypeDefParameter, args);
log("callMethodWithMapTypeDefParameter - OK");
});
it("callMethodWithEnumTypeDefParameter", async () => {
log("callMethodWithEnumTypeDefParameter");
const args = {
enumTypeDefIn: Enumeration.ENUM_0_VALUE_1
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithEnumTypeDefParameter, args);
log("callMethodWithEnumTypeDefParameter - OK");
});
it("callMethodWithByteBufferTypeDefParameter", async () => {
log("callMethodWithByteBufferTypeDefParameter");
const args = {
byteBufferTypeDefIn: IltUtil.create("ByteArray")
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithByteBufferTypeDefParameter, args);
log("callMethodWithByteBufferTypeDefParameter - OK");
});
it("callMethodWithArrayTypeDefParameter", async () => {
log("callMethodWithArrayTypeDefParameter");
const stringArray = {
typeDefStringArray: IltUtil.create("StringArray")
};
const arrayTypeDefArg = new ArrayTypeDefStruct(stringArray);
const args = {
arrayTypeDefIn: arrayTypeDefArg
};
await callProxyMethodWithParameter(testInterfaceProxy.methodWithArrayTypeDefParameter, args);
log("callMethodWithArrayTypeDefParameter - OK");
});
it("callMethodWithSingleEnumParameters", async () => {
log("callMethodWithSingleEnumParameters");
const args = {
enumerationArg:
ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES
};
const retObj = await testInterfaceProxy.methodWithSingleEnumParameters(args);
expect(retObj).toBeDefined();
expect(retObj.enumerationOut).toBeDefined();
expect(retObj.enumerationOut).toEqual(
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
);
log("callMethodWithSingleEnumParameters - OK");
});
it("callMethodWithMultipleEnumParameters", async () => {
const args = {
enumerationArg: Enumeration.ENUM_0_VALUE_3,
extendedEnumerationArg:
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
};
const retObj = await testInterfaceProxy.methodWithMultipleEnumParameters(args);
expect(retObj).toBeDefined();
expect(retObj.enumerationOut).toBeDefined();
expect(retObj.extendedEnumerationOut).toBeDefined();
expect(retObj.enumerationOut).toEqual(Enumeration.ENUM_0_VALUE_1);
expect(retObj.extendedEnumerationOut).toEqual(
ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES
);
log("callMethodWithMultipleEnumParameters - OK");
});
it("callMethodWithSingleStructParameters", async () => {
log("callMethodWithSingleStructParameters");
const args = {
extendedBaseStructArg: IltUtil.create("ExtendedBaseStruct")
};
const retObj = await testInterfaceProxy.methodWithSingleStructParameters(args);
expect(retObj).toBeDefined();
expect(retObj.extendedStructOfPrimitivesOut).toBeDefined();
expect(IltUtil.checkExtendedStructOfPrimitives(retObj.extendedStructOfPrimitivesOut)).toBeTruthy();
log("callMethodWithSingleStructParameters - OK");
});
it("callMethodWithMultipleStructParameters", async () => {
log("callMethodWithMultipleStructParameters");
const args = {
extendedStructOfPrimitivesArg: IltUtil.createExtendedStructOfPrimitives(),
// TODO
// currently not supported:
// anonymousBaseStructArg:
baseStructArg: IltUtil.create("BaseStruct")
};
const retObj = await testInterfaceProxy.methodWithMultipleStructParameters(args);
expect(retObj).toBeDefined();
expect(retObj.baseStructWithoutElementsOut).toBeDefined();
expect(retObj.extendedExtendedBaseStructOut).toBeDefined();
expect(IltUtil.check("BaseStructWithoutElements", retObj.baseStructWithoutElementsOut)).toBeTruthy();
expect(IltUtil.check("ExtendedExtendedBaseStruct", retObj.extendedExtendedBaseStructOut)).toBeTruthy();
log("callMethodWithMultipleStructParameters - OK");
});
it("callMethodFireAndForgetWithoutParameter", done => {
/*
* FireAndForget methods do not have a return value and the calling proxy does not receive an answer to a fireAndForget method call.
* The attribute attributeFireAndForget is used in fireAndForget method calls to check if the method is called at the provider.
* The provider will change the attribute to a (fireAndForget) method specific value which will be checked in the subscription listener.
*/
log("callMethodFireAndForgetWithoutParameter");
let expected = -1;
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
let attributeFireAndForgetSubscriptionId: any;
// set attributeFireAndForget to 0 (it might have been set to the expected value by another test)
log("callMethodFireAndForgetWithoutParameter - setAttributeFireAndForget");
const args = {
value: 0
};
testInterfaceProxy.attributeFireAndForget
.set(args)
.then(() => {
log("callMethodFireAndForgetWithoutParameter - setAttributeFireAndForget - OK");
// subscribe to attributeFireAndForget
log("callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget");
return testInterfaceProxy.attributeFireAndForget.subscribe({
subscriptionQos: subscriptionQosOnChange,
onReceive,
onError: done.fail
});
})
.then((subscriptionId: string) => {
attributeFireAndForgetSubscriptionId = subscriptionId;
log(
`callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget subscriptionId = ${attributeFireAndForgetSubscriptionId}`
);
})
.catch((error: any) => {
done.fail(
`callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget - FAILED: ${error}`
);
});
let firstReceive = true;
function onReceive(attributeFireAndForgetValue: any) {
if (firstReceive) {
firstReceive = false;
expect(attributeFireAndForgetValue).toBeDefined();
expect(attributeFireAndForgetValue).toEqual(0);
log("callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget - OK");
// call methodFireAndForgetWithoutParameter
expected = attributeFireAndForgetValue + 1;
log("callMethodFireAndForgetWithoutParameter CALL");
testInterfaceProxy.methodFireAndForgetWithoutParameter().catch((error: any) => {
done.fail(`callMethodFireAndForgetWithoutParameter CALL - FAILED: ${error}`);
});
} else {
expect(attributeFireAndForgetValue).toBeDefined();
expect(attributeFireAndForgetValue).toEqual(expected);
log("callMethodFireAndForgetWithoutParameter - OK");
// unsubscribe again
log("callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget unsubscribe");
testInterfaceProxy.attributeFireAndForget
.unsubscribe({
subscriptionId: attributeFireAndForgetSubscriptionId
})
.then(() => {
log(
"callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget unsubscribe - OK"
);
log("callMethodFireAndForgetWithoutParameter - DONE");
done();
})
.catch((error: any) => {
done.fail(
`callMethodFireAndForgetWithoutParameter - subscribeToAttributeFireAndForget unsubscribe - FAILED: ${error}`
);
});
}
}
});
it("callMethodFireAndForgetWithInputParameter", done => {
log("callMethodFireAndForgetWithInputParameter");
let expected = -1;
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
let attributeFireAndForgetSubscriptionId: any;
// set attributeFireAndForget to 0 (it might have been set to the expected value by another test)
log("callMethodFireAndForgetWithInputParameter - setAttributeFireAndForget");
const args = {
value: 0
};
testInterfaceProxy.attributeFireAndForget
.set(args)
.then(() => {
log("callMethodFireAndForgetWithInputParameter - setAttributeFireAndForget - OK");
// subscribe to attributeFireAndForget
log("callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget");
/*eslint-disable no-use-before-define*/
return testInterfaceProxy.attributeFireAndForget.subscribe({
subscriptionQos: subscriptionQosOnChange,
onReceive,
onError: done.fail
});
/*eslint-enable no-use-before-define*/
})
.then((subscriptionId: any) => {
attributeFireAndForgetSubscriptionId = subscriptionId;
log(
`callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget subscriptionId = ${attributeFireAndForgetSubscriptionId}`
);
})
.catch((error: any) => {
done.fail(
`callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget - FAILED: ${error}`
);
});
let firstReceive = true;
function onReceive(attributeFireAndForgetValue: any) {
if (firstReceive) {
firstReceive = false;
expect(attributeFireAndForgetValue).toBeDefined();
expect(attributeFireAndForgetValue).toEqual(0);
log("callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget - OK");
// call methodFireAndForgetWithInputParameter
expected = attributeFireAndForgetValue + 1;
log("callMethodFireAndForgetWithInputParameter CALL");
testInterfaceProxy.methodFireAndForgetWithoutParameter().catch((error: any) => {
done.fail(`callMethodFireAndForgetWithInputParameter CALL - FAILED: ${error}`);
});
} else {
expect(attributeFireAndForgetValue).toBeDefined();
expect(attributeFireAndForgetValue).toEqual(expected);
log("callMethodFireAndForgetWithInputParameter - OK");
// unsubscribe again
log("callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget unsubscribe");
testInterfaceProxy.attributeFireAndForget
.unsubscribe({
subscriptionId: attributeFireAndForgetSubscriptionId
})
.then(() => {
log(
"callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget unsubscribe - OK"
);
log("callMethodFireAndForgetWithInputParameter - DONE");
done();
})
.catch((error: any) => {
done.fail(
`callMethodFireAndForgetWithInputParameter - subscribeToAttributeFireAndForget unsubscribe - FAILED: ${error}`
);
});
}
}
});
it("callOverloadedMethod_1", async () => {
log("callOverloadedMethod_1");
const retObj = await testInterfaceProxy.overloadedMethod();
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("TestString 1");
log("callOverloadedMethod_1 - OK");
});
it("callOverloadedMethod_2", async () => {
const args = {
booleanArg: false
};
log("callOverloadedMethod_2");
const retObj = await testInterfaceProxy.overloadedMethod(args);
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("TestString 2");
log("callOverloadedMethod_2 - OK");
});
it("callOverloadedMethod_3", async () => {
const args = {
enumArrayArg: IltUtil.create("ExtendedExtendedEnumerationArray"),
int64Arg: 1,
baseStructArg: IltUtil.create("BaseStruct"),
booleanArg: false
};
log("callOverloadedMethod_3");
const retObj: TestInterfaceProxy.OverloadedMethodReturns3 = (await testInterfaceProxy.overloadedMethod(
args
)) as any;
expect(retObj).toBeDefined();
expect(retObj.doubleOut).toBeDefined();
expect(retObj.stringArrayOut).toBeDefined();
expect(retObj.extendedBaseStructOut).toBeDefined();
expect(IltUtil.cmpDouble(retObj.doubleOut, 0.0)).toBeTruthy();
expect(IltUtil.check("StringArray", retObj.stringArrayOut)).toBeTruthy();
expect(IltUtil.check("ExtendedBaseStruct", retObj.extendedBaseStructOut)).toBeTruthy();
log("callOverloadedMethod_3 - OK");
});
it("callOverloadedMethodWithSelector_1", async () => {
log("callOverloadedMethodWithSelector_1");
const retObj = await testInterfaceProxy.overloadedMethodWithSelector();
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("Return value from overloadedMethodWithSelector 1");
log("callOverloadedMethodWithSelector_1 - OK");
});
it("callOverloadedMethodWithSelector_2", async () => {
const args = {
booleanArg: false
};
log("callOverloadedMethodWithSelector_2");
const retObj = await testInterfaceProxy.overloadedMethodWithSelector(args);
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("Return value from overloadedMethodWithSelector 2");
log("callOverloadedMethodWithSelector_2 - OK");
});
it("callOverloadedMethodWithSelector_3", async () => {
const args = {
enumArrayArg: IltUtil.create("ExtendedExtendedEnumerationArray"),
int64Arg: 1,
baseStructArg: IltUtil.create("BaseStruct"),
booleanArg: false
};
log("callOverloadedMethodWithSelector_3");
const retObj: TestInterfaceProxy.OverloadedMethodReturns3 = (await testInterfaceProxy.overloadedMethod(
args
)) as any;
expect(retObj).toBeDefined();
expect(retObj.doubleOut).toBeDefined();
expect(retObj.stringArrayOut).toBeDefined();
expect(retObj.extendedBaseStructOut).toBeDefined();
expect(IltUtil.cmpDouble(retObj.doubleOut, 0.0)).toBeTruthy();
expect(IltUtil.check("StringArray", retObj.stringArrayOut)).toBeTruthy();
expect(IltUtil.check("ExtendedBaseStruct", retObj.extendedBaseStructOut)).toBeTruthy();
log("callOverloadedMethodWithSelector_3 - OK");
});
it("callMethodWithStringsAndSpecifiedStringOutputLength", async () => {
log("callMethodWithStringsAndSpecifiedStringOutputLength");
const args = {
stringArg: "Hello world",
int32StringLengthArg: 32
};
const retObj = await testInterfaceProxy.methodWithStringsAndSpecifiedStringOutLength(args);
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut.length).toEqual(32);
log("callMethodWithStringsAndSpecifiedStringOutputLength - OK");
});
it("callMethodWithoutErrorEnum", async () => {
log("callMethodWithoutErrorEnum");
const args = {
wantedExceptionArg: "ProviderRuntimeException"
};
expect.assertions(4);
try {
await testInterfaceProxy.methodWithoutErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from methodWithoutErrorEnum");
log("callMethodWithoutErrorEnum - OK");
}
});
it("callMethodWithAnonymousErrorEnum", async () => {
log("callMethodWithAnonymousErrorEnunm");
let args = {
wantedExceptionArg: "ProviderRuntimeException"
};
expect.assertions(8);
try {
await testInterfaceProxy.methodWithAnonymousErrorEnum(args);
} catch (retObj) {
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from methodWithAnonymousErrorEnum");
log("callMethodWithAnonymousErrorEnunm - 1st - OK");
}
args = {
wantedExceptionArg: "ApplicationException"
};
try {
await testInterfaceProxy.methodWithAnonymousErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ApplicationException");
expect(retObj.error).toBeDefined();
//expect(retObj.error).toEqual(MethodWithAnonymousErrorEnumErrorEnum.ERROR_3_1_NTC);
expect(retObj.error._typeName).toEqual(
"joynr.interlanguagetest.TestInterface.MethodWithAnonymousErrorEnumErrorEnum"
);
expect(retObj.error.name).toEqual("ERROR_3_1_NTC");
log("callMethodWithAnonymousErrorEnun - 2nd - OK");
}
});
it("callMethodWithExistingErrorEnum", async () => {
log("callMethodWithExistingErrorEnunm");
let args = {
wantedExceptionArg: "ProviderRuntimeException"
};
expect.assertions(14);
try {
await testInterfaceProxy.methodWithExistingErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from methodWithExistingErrorEnum");
log("callMethodWithExistingErrorEnunm - 1st - OK");
}
args = {
wantedExceptionArg: "ApplicationException_1"
};
try {
await testInterfaceProxy.methodWithExistingErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ApplicationException");
expect(retObj.error).toBeDefined();
// following statement does not work
//expect(retObj.error).toEqual(ExtendedErrorEnumTc.ERROR_2_3_TC2);
expect(retObj.error._typeName).toEqual(
"joynr.interlanguagetest.namedTypeCollection2.ExtendedErrorEnumTc"
);
expect(retObj.error.name).toEqual("ERROR_2_3_TC2");
log("callMethodWithExistingErrorEnun - 2nd - OK");
}
args = {
wantedExceptionArg: "ApplicationException_2"
};
try {
await testInterfaceProxy.methodWithExistingErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ApplicationException");
expect(retObj.error).toBeDefined();
//expect(retObj.error).toEqual(ExtendedErrorEnumTc.ERROR_1_2_TC_2);
expect(retObj.error._typeName).toEqual(
"joynr.interlanguagetest.namedTypeCollection2.ExtendedErrorEnumTc"
);
expect(retObj.error.name).toEqual("ERROR_1_2_TC_2");
log("callMethodWithExistingErrorEnum - 3rd - OK");
}
});
it("callMethodWithExtendedErrorEnum", async () => {
log("callMethodWithExtendedErrorEnum");
expect.assertions(14);
let args = {
wantedExceptionArg: "ProviderRuntimeException"
};
try {
await testInterfaceProxy.methodWithExtendedErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from methodWithExtendedErrorEnum");
log("callMethodWithExtendedErrorEnum - 1st - OK");
}
args = {
wantedExceptionArg: "ApplicationException_1"
};
try {
await testInterfaceProxy.methodWithExtendedErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ApplicationException");
expect(retObj.error).toBeDefined();
//expect(retObj.error).toEqual(ExtendedErrorEnumTc.ERROR_3_3_NTC);
expect(retObj.error._typeName).toEqual(
"joynr.interlanguagetest.TestInterface.MethodWithExtendedErrorEnumErrorEnum"
);
expect(retObj.error.name).toEqual("ERROR_3_3_NTC");
log("callMethodWithExtendedErrorEnum - 2nd - OK");
}
args = {
wantedExceptionArg: "ApplicationException_2"
};
try {
await testInterfaceProxy.methodWithExtendedErrorEnum(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ApplicationException");
expect(retObj.error).toBeDefined();
//expect(retObj.error).toEqual(ExtendedErrorEnumTc.ERROR_2_1_TC2);
expect(retObj.error._typeName).toEqual(
"joynr.interlanguagetest.TestInterface.MethodWithExtendedErrorEnumErrorEnum"
);
expect(retObj.error.name).toEqual("ERROR_2_1_TC2");
log("callMethodWithExtendedErrorEnum - 3rd - OK");
}
});
it("callGetAttributeWithExceptionFromGetter", async () => {
log("callGetAttributeWithExceptionFromGetter");
expect.assertions(4);
try {
await testInterfaceProxy.attributeWithExceptionFromGetter.get();
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from getAttributeWithExceptionFromGetter");
log("callGetAttributeWithExceptionFromGetter - OK");
}
});
it("callSetAttributeWithExceptionFromSetter", async () => {
log("callSetAttributeWithExceptionFromSetter");
const args = {
value: false
};
expect.assertions(4);
try {
await testInterfaceProxy.attributeWithExceptionFromSetter.set(args);
} catch (retObj) {
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from setAttributeWithExceptionFromSetter");
log("callSetAttributeWithExceptionFromSetter - OK");
}
});
it("callMethodWithSingleMapParameters", async () => {
log("callMethodWithSingleMapParameters");
const mapArg = new MapStringString();
for (let i = 1; i <= 3; i++) {
mapArg.put(`keyString${i}`, `valueString${i}`);
}
const args = {
mapArg
};
const retObj = await testInterfaceProxy.methodWithSingleMapParameters(args);
expect(retObj).toBeDefined();
expect(retObj.mapOut).toBeDefined();
for (let i = 1; i <= 3; i++) {
expect(retObj.mapOut.get(`valueString${i}`)).toEqual(`keyString${i}`);
}
log("callMethodWithSingleMapParameters - OK");
});
async function genericSetGet(testObj: any, testValue: any) {
log(`genericSetGet called with testValue = ${JSON.stringify(testValue)}`);
await testObj.set({ value: testValue });
const retObj = await testObj.get();
expect(retObj).toBeDefined();
expect(retObj).toEqual(testValue);
}
it("callSetandGetAttributeMapStringString", async () => {
log("callSetandGetAttributeMapStringString");
const mapArg = new MapStringString();
for (let i = 1; i <= 3; i++) {
mapArg.put(`keyString${i}`, `valueString${i}`);
}
return await genericSetGet(testInterfaceProxy.attributeMapStringString, mapArg);
});
it("callSetandGetAttributeUInt8", async () => {
log("callSetandGetAttributeUInt8");
return await genericSetGet(testInterfaceProxy.attributeUInt8, 127);
});
it("callSetandGetAttributeDouble", async () => {
log("callSetandGetAttributeDouble");
return await genericSetGet(testInterfaceProxy.attributeDouble, 1.1);
});
it("callGetAttributeBooleanReadonly", async () => {
log("callGetAttributeBooleanReadonly");
const retObj = await testInterfaceProxy.attributeBooleanReadonly.get();
expect(retObj).toBeDefined();
expect(retObj).toBeTruthy();
});
it("callSetandGetAttributeStringNoSubscriptions", async () => {
log("callSetandGetAttributeStringNoSubscriptions");
return await genericSetGet(testInterfaceProxy.attributeStringNoSubscriptions, "Hello world");
});
it("callGetAttributeInt8readonlyNoSubscriptions", async () => {
log("callGetAttributeInt8readonlyNoSubscriptions");
const retObj = await testInterfaceProxy.attributeInt8readonlyNoSubscriptions.get();
expect(retObj).toBeDefined();
expect(retObj).toEqual(-128);
});
it("callSetandGetAttributeArrayOfStringImplicit", async () => {
log("callSetandGetAttributeArrayOfStringImplicit");
return await genericSetGet(
testInterfaceProxy.attributeArrayOfStringImplicit,
IltUtil.create("StringArray")
);
});
it("callSetandGetAttributeByteBuffer", async () => {
log("callSetandGetAttributeByteBuffer");
return await genericSetGet(testInterfaceProxy.attributeByteBuffer, IltUtil.create("ByteArray"));
});
it("callSetandGetAttributeInt64TypeDef", async () => {
log("callSetandGetAttributeInt64TypeDef");
const testValue = 1;
return await genericSetGet(testInterfaceProxy.attributeInt64TypeDef, testValue);
});
it("callSetandGetAttributeStringTypeDef", async () => {
log("callSetandGetAttributeStringTypeDef");
return await genericSetGet(testInterfaceProxy.attributeStringTypeDef, "StringTypeDef");
});
it("callSetandGetAttributeStructTypeDef", async () => {
log("callSetandGetAttributeStructTypeDef");
return await genericSetGet(testInterfaceProxy.attributeStructTypeDef, IltUtil.create("BaseStruct"));
});
it("callSetandGetAttributeMapTypeDef", async () => {
log("callSetandGetAttributeMapTypeDef");
const value = new MapStringString();
for (let i = 1; i <= 3; i++) {
value.put(`keyString${i}`, `valueString${i}`);
}
return await genericSetGet(testInterfaceProxy.attributeMapTypeDef, value);
});
it("callSetandGetAttributeEnumTypeDef", async () => {
log("callSetandGetAttributeEnumTypeDef");
return await genericSetGet(testInterfaceProxy.attributeEnumTypeDef, Enumeration.ENUM_0_VALUE_1);
});
it("callSetandGetAttributeByteBufferTypeDef", async () => {
log("callSetandGetAttributeByteBufferTypeDef");
return await genericSetGet(testInterfaceProxy.attributeByteBufferTypeDef, IltUtil.create("ByteArray"));
});
it("callSetandGetAttributeArrayTypeDef", async () => {
log("callSetandGetAttributeArrayTypeDef");
const args = {
typeDefStringArray: IltUtil.create("StringArray")
};
const arrayTypeDefArg = new ArrayTypeDefStruct(args);
return await genericSetGet(testInterfaceProxy.attributeArrayTypeDef, arrayTypeDefArg);
});
it("callSetandGetAttributeEnumeration", async () => {
log("callSetandGetAttributeEnumeration");
return await genericSetGet(testInterfaceProxy.attributeEnumeration, Enumeration.ENUM_0_VALUE_2);
});
it("callGetAttributeExtendedEnumerationReadonly", async () => {
log("callGetAttributeExtendedEnumerationReadonly");
const retObj = await testInterfaceProxy.attributeExtendedEnumerationReadonly.get();
expect(retObj).toBeDefined();
expect(retObj).toEqual(
ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES
);
});
it("callSetandGetAttributeBaseStruct", async () => {
log("callSetandGetAttributeBaseStruct");
return await genericSetGet(testInterfaceProxy.attributeBaseStruct, IltUtil.create("BaseStruct"));
});
it("callSetandGetAttributeExtendedExtendedBaseStruct", async () => {
log("callSetandGetAttributeExtendedExtendedBaseStruct");
return await genericSetGet(
testInterfaceProxy.attributeExtendedExtendedBaseStruct,
IltUtil.create("ExtendedExtendedBaseStruct")
);
});
it("callSubscribeAttributeEnumeration", async () => {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeAttributeEnumeration");
const subscriptionId = await testInterfaceProxy.attributeEnumeration.subscribe({
subscriptionQos: subscriptionQosOnChange,
onReceive: onReceiveDeferred.resolve,
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
const retObj = await onReceiveDeferred.promise;
expect(retObj).toBeDefined();
expect(retObj).toEqual(Enumeration.ENUM_0_VALUE_2);
await testInterfaceProxy.attributeEnumeration.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
});
it("callSubscribeAttributeWithExceptionFromGetter", async () => {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeAttributeWithExceptionFromGetter");
const subscriptionId = await testInterfaceProxy.attributeWithExceptionFromGetter.subscribe({
subscriptionQos: subscriptionQosOnChange,
onReceive: onErrorSpy,
onError: onReceiveDeferred.resolve,
onSubscribed: onSubscribedDeferred.resolve
});
log(`callSubscribeAttributeWithExceptionFromGetter - subscriptionId = ${subscriptionId}`);
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
const retObj = await onReceiveDeferred.promise;
log(`retObj = ${JSON.stringify(retObj)}`);
expect(retObj).toBeDefined();
expect(retObj._typeName).toEqual("joynr.exceptions.ProviderRuntimeException");
expect(retObj.detailMessage).toBeDefined();
expect(retObj.detailMessage).toEqual("Exception from getAttributeWithExceptionFromGetter");
await testInterfaceProxy.attributeWithExceptionFromGetter.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
});
async function callSubscribeBroadcastWithSinglePrimitiveParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithSinglePrimitiveParameter");
const subscriptionId = await testInterfaceProxy.broadcastWithSinglePrimitiveParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("boom");
log(`publication retObj: ${JSON.stringify(retObj)}`);
testInterfaceProxy.broadcastWithSinglePrimitiveParameter
.unsubscribe({
subscriptionId
})
.then(onReceiveDeferred.resolve)
.catch(onReceiveDeferred.reject);
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
log(`subscriptionId = ${subscriptionId}`);
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
await testInterfaceProxy.methodToFireBroadcastWithSinglePrimitiveParameter({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithSinglePrimitiveParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithSinglePrimitiveParameter([]);
});
it("callSubscribeBroadcastWithSinglePrimitiveParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithSinglePrimitiveParameter(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithMultiplePrimitiveParameters(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("subscribeBroadcastWithMultiplePrimitiveParameters");
const subscriptionId = await testInterfaceProxy.broadcastWithMultiplePrimitiveParameters.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.doubleOut).toBeDefined();
expect(IltUtil.cmpDouble(retObj.doubleOut, 1.1)).toBeTruthy();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("boom");
log(`publication retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
log(`subscriptionId = ${subscriptionId}`);
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
await testInterfaceProxy.methodToFireBroadcastWithMultiplePrimitiveParameters({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
await testInterfaceProxy.broadcastWithMultiplePrimitiveParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithMultiplePrimitiveParameters_NoPartitions", async () => {
return await callSubscribeBroadcastWithMultiplePrimitiveParameters([]);
});
it("callSubscribeBroadcastWithMultiplePrimitiveParameters_SimplePartitions", async () => {
return await callSubscribeBroadcastWithMultiplePrimitiveParameters(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithSingleArrayParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithSingleArrayParameter");
const subscriptionId = await testInterfaceProxy.broadcastWithSingleArrayParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.stringArrayOut).toBeDefined();
expect(IltUtil.check("StringArray", retObj.stringArrayOut)).toBeTruthy();
log(`publication retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
log(`subscriptionId = ${subscriptionId}`);
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
await testInterfaceProxy.methodToFireBroadcastWithSingleArrayParameter({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithSingleArrayParameter.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithSingleArrayParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithSingleArrayParameter([]);
});
it("callSubscribeBroadcastWithSingleArrayParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithSingleArrayParameter(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithMultipleArrayParameters(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithMultipleArrayParameters");
const subscriptionId = await testInterfaceProxy.broadcastWithMultipleArrayParameters.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.uInt64ArrayOut).toBeDefined();
expect(IltUtil.check("UInt64Array", retObj.uInt64ArrayOut)).toBeTruthy();
expect(retObj.structWithStringArrayArrayOut).toBeDefined();
expect(
IltUtil.check("StructWithStringArrayArray", retObj.structWithStringArrayArrayOut)
).toBeTruthy();
log(`publication retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
log(`subscriptionId = ${subscriptionId}`);
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
await testInterfaceProxy.methodToFireBroadcastWithMultipleArrayParameters({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithMultipleArrayParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithMultipleArrayParameters_NoPartitions", async () => {
return await callSubscribeBroadcastWithMultipleArrayParameters([]);
});
it("callSubscribeBroadcastWithMultipleArrayParameters_SimplePartitions", async () => {
return await callSubscribeBroadcastWithMultipleArrayParameters(["partition0", "partition1"]);
});
const byteBufferArg = [-128, 0, 127];
async function callSubscribeBroadcastWithSingleByteBufferParameter(byteBufferArg: any, partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithSingleByteBufferParameter");
const subscriptionId = await testInterfaceProxy.broadcastWithSingleByteBufferParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.byteBufferOut).toBeDefined();
expect(IltUtil.cmpByteBuffers(retObj.byteBufferOut, byteBufferArg)).toBeTruthy();
log(`Successful publication of retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`Subscription was successful with subscriptionId = ${subscriptionId}`);
// execute fire method here
testInterfaceProxy.methodToFireBroadcastWithSingleByteBufferParameter({
byteBufferIn: byteBufferArg,
partitions: partitionsToUse
});
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithSingleByteBufferParameter.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithSingleByteBufferParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithSingleByteBufferParameter(byteBufferArg, []);
});
it("callSubscribeBroadcastWithSingleByteBufferParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithSingleByteBufferParameter(byteBufferArg, [
"partition0",
"partition1"
]);
});
const byteBufferArg1 = [-5, 125];
const byteBufferArg2 = [78, 0];
async function callSubscribeBroadcastWithMultipleByteBufferParameters(
byteBufferArg1: any,
byteBufferArg2: any,
partitionsToUse: any
) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithMultipleByteBufferParameters");
const subscriptionId = await testInterfaceProxy.broadcastWithMultipleByteBufferParameters.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.byteBufferOut1).toBeDefined();
expect(retObj.byteBufferOut2).toBeDefined();
expect(IltUtil.cmpByteBuffers(retObj.byteBufferOut1, byteBufferArg1)).toBeTruthy();
expect(IltUtil.cmpByteBuffers(retObj.byteBufferOut2, byteBufferArg2)).toBeTruthy();
log(`Successful publication of retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`Subscription was successful with subscriptionId = ${subscriptionId}`);
// execute fire method here
await testInterfaceProxy.methodToFireBroadcastWithMultipleByteBufferParameters({
byteBufferIn1: byteBufferArg1,
byteBufferIn2: byteBufferArg2,
partitions: partitionsToUse
});
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithMultipleByteBufferParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
log("Successfully unsubscribed from broadcast");
}
it("callSubscribeBroadcastWithMultipleByteBufferParameters_NoPartitions", async () => {
return await callSubscribeBroadcastWithMultipleByteBufferParameters(byteBufferArg1, byteBufferArg2, []);
});
it("callSubscribeBroadcastWithMultipleByteBufferParameters_SimplePartitions", async () => {
return await callSubscribeBroadcastWithMultipleByteBufferParameters(byteBufferArg1, byteBufferArg2, [
"partition0",
"partition1"
]);
});
async function callSubscribeBroadcastWithSingleEnumerationParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithSingleEnumerationParameter");
const subscriptionId = await testInterfaceProxy.broadcastWithSingleEnumerationParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.enumerationOut).toBeDefined();
expect(retObj.enumerationOut).toEqual(
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
);
log(`publication retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
await testInterfaceProxy.methodToFireBroadcastWithSingleEnumerationParameter({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithSingleEnumerationParameter.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithSingleEnumerationParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithSingleEnumerationParameter([]);
});
it("callSubscribeBroadcastWithSingleEnumerationParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithSingleEnumerationParameter(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithMultipleEnumerationParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithMultipleEnumerationParameters");
const subscriptionId = await testInterfaceProxy.broadcastWithMultipleEnumerationParameters.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.extendedEnumerationOut).toBeDefined();
expect(retObj.extendedEnumerationOut).toEqual(
ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES
);
expect(retObj.enumerationOut).toBeDefined();
expect(retObj.enumerationOut).toEqual(Enumeration.ENUM_0_VALUE_1);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
testInterfaceProxy.methodToFireBroadcastWithMultipleEnumerationParameters({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithMultipleEnumerationParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithMultipleEnumerationParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithMultipleEnumerationParameter([]);
});
it("callSubscribeBroadcastWithMultipleEnumerationParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithMultipleEnumerationParameter(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithSingleStructParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithSingleStructParameter");
const subscriptionId = await testInterfaceProxy.broadcastWithSingleStructParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
expect(retObj).toBeDefined();
expect(retObj.extendedStructOfPrimitivesOut).toBeDefined();
expect(IltUtil.checkExtendedStructOfPrimitives(retObj.extendedStructOfPrimitivesOut)).toBeTruthy();
log(`publication retObj: ${JSON.stringify(retObj)}`);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
await testInterfaceProxy.methodToFireBroadcastWithSingleStructParameter({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithSingleStructParameter.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithSingleStructParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithSingleStructParameter([]);
});
it("callSubscribeBroadcastWithSingleStructParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithSingleStructParameter(["partition0", "partition1"]);
});
async function callSubscribeBroadcastWithMultipleStructParameter(partitionsToUse: any) {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithMultipleStructParameters");
const subscriptionId = await testInterfaceProxy.broadcastWithMultipleStructParameters.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: partitionsToUse,
onReceive: (retObj: any) => {
log(`XXX: publication retObj: ${JSON.stringify(retObj)}`);
expect(retObj).toBeDefined();
expect(retObj.baseStructWithoutElementsOut).toBeDefined();
expect(
IltUtil.check("BaseStructWithoutElements", retObj.baseStructWithoutElementsOut)
).toBeTruthy();
expect(retObj.extendedExtendedBaseStructOut).toBeDefined();
expect(
IltUtil.check("ExtendedExtendedBaseStruct", retObj.extendedExtendedBaseStructOut)
).toBeTruthy();
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
await testInterfaceProxy.methodToFireBroadcastWithMultipleStructParameters({
partitions: partitionsToUse
});
// call to fire broadcast went ok
// now wait for the publication to happen
await onReceiveDeferred.promise;
// unsubscribe again
await testInterfaceProxy.broadcastWithMultipleStructParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
}
it("callSubscribeBroadcastWithMultipleStructParameter_NoPartitions", async () => {
return await callSubscribeBroadcastWithMultipleStructParameter([]);
});
it("callSubscribeBroadcastWithMultipleStructParameter_SimplePartitions", async () => {
return await callSubscribeBroadcastWithMultipleStructParameter(["partition0", "partition1"]);
});
// different pattern compared to the rest of the tests
it("doNotReceivePublicationsForOtherPartitions", async () => {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
const onReceivedSpy = jest.fn();
const subscribeToPartitions = ["partition0", "partition1"];
const broadcastPartition = ["otherPartition"];
log("doNotReceivePublicationsForOtherPartitions");
const subscriptionId = await testInterfaceProxy.broadcastWithSingleEnumerationParameter.subscribe({
subscriptionQos: subscriptionQosOnChange,
partitions: subscribeToPartitions,
onReceive: (retObj: any) => {
onReceivedSpy(retObj);
onReceiveDeferred.resolve();
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
await testInterfaceProxy.methodToFireBroadcastWithSingleEnumerationParameter({
partitions: broadcastPartition
});
// The partitions do not match. Expect no broadcast
expect(onReceivedSpy).not.toHaveBeenCalled();
await testInterfaceProxy.methodToFireBroadcastWithSingleEnumerationParameter({
partitions: subscribeToPartitions
});
await onReceiveDeferred.promise;
await testInterfaceProxy.broadcastWithMultipleStructParameters.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
});
it("callSubscribeBroadcastWithFiltering", async () => {
const subscriptionQosOnChange = new joynr.proxy.OnChangeSubscriptionQos({
minIntervalMs: 50,
validityMs: 60000
});
const onSubscribedDeferred = IltUtil.createDeferred();
const onReceiveDeferred = IltUtil.createDeferred();
log("callSubscribeBroadcastWithFiltering");
const filterParameters = testInterfaceProxy.broadcastWithFiltering.createFilterParameters();
const stringOfInterest = "fireBroadcast";
filterParameters.setStringOfInterest(stringOfInterest);
//filterParameters.setStringArrayOfInterest(JSON.stringify(IltUtil.createStringArray()));
//filterParameters.setEnumerationOfInterest(JSON.stringify(ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION));
//filterParameters.setStructWithStringArrayOfInterest(JSON.stringify(IltUtil.createStructWithStringArray()));
//filterParameters.setStructWithStringArrayArrayOfInterest(JSON.stringify(IltUtil.createStructWithStringArrayArray()));
filterParameters.setStringArrayOfInterest('["Hello","World"]');
filterParameters.setEnumerationOfInterest('"ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION"');
filterParameters.setStructWithStringArrayOfInterest(
'{"_typeName":"joynr.interlanguagetest.namedTypeCollection1.StructWithStringArray","stringArrayElement":["Hello","World"]}'
);
filterParameters.setStructWithStringArrayArrayOfInterest(
'[{"_typeName":"joynr.interlanguagetest.namedTypeCollection1.StructWithStringArray","stringArrayElement":["Hello","World"]},{"_typeName":"joynr.interlanguagetest.namedTypeCollection1.StructWithStringArray","stringArrayElement":["Hello","World"]}]'
);
const subscriptionId = await testInterfaceProxy.broadcastWithFiltering.subscribe({
subscriptionQos: subscriptionQosOnChange,
onReceive: (retObj: any) => {
onReceiveDeferred.resolve(retObj);
},
onError: onErrorSpy,
onSubscribed: onSubscribedDeferred.resolve,
filterParameters
});
const id = await onSubscribedDeferred.promise;
expect(id).toEqual(subscriptionId);
log(`subscriptionId = ${subscriptionId}`);
// execute fire method here
const args = {
stringArg: "fireBroadcast"
};
await testInterfaceProxy.methodToFireBroadcastWithFiltering(args);
// call to fire broadcast went ok
// now wait for the publication to happen
const retObj = await onReceiveDeferred.promise;
log(`XXX: publication retObj: ${JSON.stringify(retObj)}`);
expect(retObj).toBeDefined();
expect(retObj.stringOut).toBeDefined();
expect(retObj.stringOut).toEqual("fireBroadcast");
expect(retObj.enumerationOut).toBeDefined();
expect(retObj.enumerationOut).toEqual(
ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION
);
expect(retObj.stringArrayOut).toBeDefined();
expect(IltUtil.check("StringArray", retObj.stringArrayOut)).toBeTruthy();
expect(retObj.structWithStringArrayOut).toBeDefined();
expect(IltUtil.check("StructWithStringArray", retObj.structWithStringArrayOut)).toBeTruthy();
expect(retObj.structWithStringArrayArrayOut).toBeDefined();
expect(IltUtil.check("StructWithStringArrayArray", retObj.structWithStringArrayArrayOut)).toBeTruthy();
// unsubscribe again
await testInterfaceProxy.broadcastWithFiltering.unsubscribe({
subscriptionId
});
expect(onErrorSpy).not.toHaveBeenCalled();
});
afterAll(async () => {
await joynr.shutdown();
});
});
}); | the_stack |
import * as assert from 'assert'
import { Application } from 'spectron'
import { v4 as uuid } from 'uuid'
import { load } from 'js-yaml'
import * as Selectors from './selectors'
import * as CLI from './cli'
import * as Common from './common'
import * as ReplExpect from './repl-expect'
import * as SidecarExpect from './sidecar-expect'
import { keys } from './keys'
export interface AppAndCount {
app: Application
count: number
splitIndex?: number
}
/**
* subset means that it is ok for struct1 to be a subset of struct2
* so: every key in struct1 must be in struct2, but not vice versa
*
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sameStruct = (struct1: Record<string, any>, struct2: Record<string, any>, subset = false): boolean => {
if (struct1 === struct2) {
return true
} else if (typeof struct1 !== typeof struct2) {
return false
}
for (const key in struct1) {
if (!(key in struct2)) {
console.log(`!(${key} in struct2)`)
return false
} else if (struct1[key].constructor === RegExp) {
// then we have a validator regular expression
if (!struct1[key].test(struct2[key])) {
return false
}
} else if (typeof struct1[key] === 'function') {
// then we have a validator function
if (!struct1[key](struct2[key])) {
return false
}
} else if (typeof struct1[key] !== typeof struct2[key]) {
console.log(`typeof struct1[${key}] !== typeof struct2[${key}] ${typeof struct1[key]} ${typeof struct2[key]}`)
console.log(struct1)
console.log(struct2)
return false
} else if (typeof struct1[key] === 'object') {
if (!sameStruct(struct1[key], struct2[key], subset)) {
return false
}
} else if (struct1[key] !== struct2[key]) {
console.log(`struct1[${key}] !== struct2[${key}] ${struct1[key]} ${struct2[key]}`)
return false
}
}
// if struct1 if expected to be a subset of struct2, then we're done
if (subset) return true
for (const key in struct2) {
if (!(key in struct1)) {
console.log(`!(${key} in struct1)`)
return false
} else if (typeof struct1[key] === 'function') {
// then we have a validator function
if (!struct1[key](struct2[key])) {
return false
}
} else if (typeof struct1[key] !== typeof struct2[key]) {
console.log(`typeof struct1[${key}] !== typeof struct2[${key}] ${typeof struct1[key]} ${typeof struct2[key]}`)
console.log(struct1)
console.log(struct2)
return false
} else if (typeof struct2[key] === 'object') {
if (!sameStruct(struct1[key], struct2[key], subset)) {
return false
}
} else if (struct1[key] !== struct2[key]) {
console.log(`struct1[${key}] !== struct2[${key}] ${struct1[key]} ${struct2[key]}`)
return false
}
}
return true
}
export const expectSubset = (struct1: object, failFast = true) => (str: string) => {
try {
const ok = sameStruct(struct1, JSON.parse(str), true)
if (failFast) {
assert.ok(ok)
}
return true
} catch (err) {
console.error('Error comparing subset for actual value=' + str)
throw err
}
}
/** is the given struct2 the same as the given struct2 (given as a string) */
export const expectStruct = (struct1: object, noParse = false, failFast = true) => (str: string) => {
try {
const ok = sameStruct(struct1, noParse ? str : JSON.parse(str))
if (failFast) {
assert.ok(ok)
}
return ok
} catch (err) {
console.error('Error comparing structs for actual value=' + str)
throw err
}
}
export const expectYAML = (struct1: object, subset = false, failFast = true) => (str: string) => {
try {
const struct2 = load(str)
const ok = sameStruct(
struct1,
typeof struct2 === 'object' ? struct2 : JSON.parse(typeof struct2 === 'number' ? `${struct2}` : struct2),
subset
)
if (failFast) {
assert.ok(ok)
}
return ok
} catch (err) {
if (failFast) {
return false
} else {
console.error('Error comparing subset for actual value=' + str)
throw err
}
}
}
export const expectYAMLSubset = (struct1: object, failFast = true) => expectYAML(struct1, true, failFast)
/** is the given actual array the same as the given expected array? */
export const expectArray = (expected: Array<string>, failFast = true, subset = false) => (
actual: string | Array<string>
) => {
if (!Array.isArray(actual)) {
// webdriver.io's getText will return a singleton if there is only one match
actual = [actual]
}
const matchFn = function(u: string, i: number) {
return u === expected[i]
}
const ok = !subset ? actual.length === expected.length && actual.every(matchFn) : actual.some(matchFn)
if (!ok) {
console.error(`array mismatch; expected=${expected} actual=${actual}`)
}
if (failFast) {
assert.ok(ok)
} else {
return ok
}
}
/** Expand the fold on the given line of a monaco editor */
export async function clickToExpandMonacoFold(res: AppAndCount, lineIdx: number) {
const container =
res.splitIndex !== undefined
? `${Selectors.PROMPT_BLOCK_N_FOR_SPLIT(res.count, res.splitIndex)} .kui--tab-content:not([hidden])`
: `${Selectors.PROMPT_BLOCK_N(res.count)} .kui--tab-content:not([hidden])`
console.log('MF1')
const selector = `${container} .monaco-editor-wrapper`
const wrapper = await res.app.client.$(selector)
await wrapper.waitForExist({ timeout: CLI.waitTimeout })
console.log('MF2')
const marginOverlaysSelector = `.margin-view-overlays > div:nth-child(${lineIdx + 1})` // css is 1-indexed
const foldingSelector = `${marginOverlaysSelector} .codicon-folding-collapsed`
const foldingClickable = await wrapper.$(foldingSelector)
console.log('MF3')
await foldingClickable.waitForExist({ timeout: CLI.waitTimeout })
console.log('MF4')
await foldingClickable.click()
console.log('MF5')
const unfoldingSelector = `${marginOverlaysSelector} .codicon-folding-expanded`
const unfoldingClickable = await wrapper.$(unfoldingSelector)
await unfoldingClickable.waitForExist({ timeout: CLI.waitTimeout })
console.log('MF6')
}
/** get the monaco editor text */
export const getValueFromMonaco = async (res: AppAndCount, container?: string) => {
if (!container) {
container =
res.splitIndex !== undefined
? `${Selectors.PROMPT_BLOCK_N_FOR_SPLIT(res.count, res.splitIndex)} .kui--tab-content:not([hidden])`
: `${Selectors.PROMPT_BLOCK_N(res.count)} .kui--tab-content:not([hidden])`
}
const selector = `${container} .monaco-editor-wrapper`
try {
await res.app.client.$(selector).then(_ => _.waitForExist({ timeout: CLI.waitTimeout }))
} catch (err) {
console.error('cannot find editor', err)
await res.app.client
.$(Selectors.SIDECAR(res.count, res.splitIndex))
.then(_ => _.getHTML())
.then(html => {
console.log('here is the content of the sidecar:')
console.log(html)
})
throw err
}
return res.app.client.execute(selector => {
try {
return ((document.querySelector(selector) as any) as { getValueForTests: () => string }).getValueForTests()
} catch (err) {
console.error('error in getValueFromMonaco1', err)
// intentionally returning undefined
}
}, selector)
}
export const waitForXtermInput = (app: Application, N: number) => {
const selector = `${Selectors.PROMPT_BLOCK_N(N)} .xterm-helper-textarea`
return app.client.$(selector).then(_ => _.waitForExist())
}
export const expectText = (app: Application, expectedText: string, exact = true, timeout = CLI.waitTimeout) => async (
selector: string
) => {
let idx = 0
await app.client.waitUntil(
async () => {
const actualText = await app.client.$(selector).then(_ => _.getText())
if (++idx > 5) {
console.error(
`still waiting for text; actualText=${actualText} expectedText=${expectedText} selector=${selector}`
)
}
if (exact) {
return actualText === expectedText
} else {
if (actualText.indexOf(expectedText) < 0) {
console.error(`Expected string not found: expected=${expectedText} actual=${actualText}`)
}
return actualText.indexOf(expectedText) >= 0
}
},
{ timeout }
)
return app
}
/** @return the current number of tabs */
export async function tabCount(app: Application): Promise<number> {
const topTabs = await app.client.$$(Selectors.TOP_TAB)
return topTabs.length
}
/** Close all except the first tab */
export function closeAllExceptFirstTab(this: Common.ISuite, expectedInitialNTabs = 2) {
it('should close all but first tab', async () => {
try {
await this.app.client.waitUntil(async () => {
const currentCount = await tabCount(this.app)
return currentCount === expectedInitialNTabs
})
let nTabs = await tabCount(this.app)
while (nTabs > 1) {
const N = nTabs--
await this.app.client.$(Selectors.TOP_TAB_CLOSE_N(N)).then(_ => _.click())
await this.app.client.waitUntil(async () => {
const currentCount = await tabCount(this.app)
return currentCount === N - 1
})
}
} catch (err) {
await Common.oops(this, true)(err)
}
})
}
export function uniqueFileForSnapshot() {
return `/tmp/${uuid()}.kui`
}
/** Click the specified button action button */
export async function clickBlockActionButton(res: AppAndCount, buttonSelector: string) {
const N = res.count
const prompt = await res.app.client.$(Selectors.PROMPT_N(N))
await prompt.scrollIntoView()
await prompt.moveTo()
const removeButton = await res.app.client.$(buttonSelector)
await removeButton.scrollIntoView()
await removeButton.waitForDisplayed({ timeout: CLI.waitTimeout })
await removeButton.click()
}
/** Click the close button on a block, and expect it to be gone */
export async function removeBlock(res: AppAndCount) {
return clickBlockActionButton(res, Selectors.BLOCK_REMOVE_BUTTON(res.count))
}
/** Click the section button on a block, and expect it to be a section */
export async function markBlockAsSection(res: AppAndCount) {
return clickBlockActionButton(res, Selectors.BLOCK_SECTION_BUTTON(res.count))
}
/** Click the section button on a block, and expect it to be a section */
export async function copyBlockLink(res: AppAndCount) {
return clickBlockActionButton(res, Selectors.BLOCK_LINK_BUTTON(res.count))
}
/** Click the section button on a block, and expect it to be a section */
export async function rerunCommand(res: AppAndCount) {
return clickBlockActionButton(res, Selectors.COMMAND_RERUN_BUTTON(res.count))
}
/** Switch sidecar tab */
export function switchToTab(mode: string) {
return async (res: AppAndCount) => {
const tab = await res.app.client.$(Selectors.SIDECAR_MODE_BUTTON(res.count, mode, res.splitIndex))
await tab.waitForDisplayed()
await tab.click()
await res.app.client
.$(Selectors.SIDECAR_MODE_BUTTON_SELECTED(res.count, mode, res.splitIndex))
.then(_ => _.waitForDisplayed())
return res
}
}
/** Output of the given block */
export function outputOf(res: AppAndCount) {
return res.app.client.$(Selectors.OUTPUT_N(res.count, res.splitIndex)).then(_ => _.getText())
}
/**
* Execute `command` and expect a table with `name`
*
*/
export async function doList(ctx: Common.ISuite, command: string, name: string) {
try {
const tableRes = await CLI.command(command, ctx.app)
return ReplExpect.okWithCustom<string>({ selector: Selectors.BY_NAME(name) })(tableRes)
} catch (err) {
await Common.oops(ctx, true)(err)
}
}
export async function openSidecarByClick(
ctx: Common.ISuite,
selector: string,
name: string,
mode?: string,
activationId?: string,
splitIndex = 2, // after we click, we expect two splits
inNotebook = false
) {
const app = ctx.app
// Note! if we already have 2 splits, we need to grab the count before we click! see https://github.com/IBM/kui/issues/6636
const currentSplitCount = (await app.client.$$(Selectors.SPLITS)).length
const currentLastBlockIdx =
currentSplitCount === splitIndex ? (await CLI.lastBlock(app, splitIndex, 1, inNotebook)).count : -1
// now click on the table row
const clickOn = await app.client.$(selector)
await clickOn.waitForExist({ timeout: CLI.waitTimeout })
await clickOn.scrollIntoView(false)
await clickOn.click()
// expect 2 splits in total
await ReplExpect.splitCount(splitIndex)(app)
// expect sidecar shown in the last blck of the second split
await app.client.waitUntil(async () => {
const sidecarRes = await CLI.lastBlock(app, splitIndex, 1, inNotebook)
return sidecarRes.count > currentLastBlockIdx
})
const sidecarRes = await CLI.lastBlock(app, splitIndex, 1, inNotebook)
await SidecarExpect.open(sidecarRes).then(SidecarExpect.showing(name, activationId))
if (mode) {
await SidecarExpect.mode(mode)(sidecarRes)
}
return sidecarRes
}
/**
* Execute `command` and expect a table with `name`,
* and then open sidecar by clicking the `name`
*
*/
export async function listAndOpenSidecarNoWait(ctx: Common.ISuite, command: string, name: string, mode?: string) {
const selector = `${await doList(ctx, command, name)} [data-value="${name}"].clickable`
return openSidecarByClick(ctx, selector, name, mode)
}
/**
* Click sidecar mode button by `mode`
*
*/
export async function clickSidecarModeButton(ctx: Common.ISuite, res: AppAndCount, mode: string) {
return ctx.app.client.$(Selectors.SIDECAR_MODE_BUTTON(res.count, mode, res.splitIndex)).then(async _ => {
await _.waitForDisplayed()
await _.click()
})
}
/**
* Click a sidecar button with `selector`
*
*/
export async function clickSidecarButtonCustomized(ctx: Common.ISuite, res: AppAndCount, selector: string) {
return ctx.app.client.$(`${Selectors.SIDECAR(res.count, res.splitIndex)} ${selector}`).then(async _ => {
await _.waitForDisplayed()
await _.click()
})
}
export function doCancel(this: Common.ISuite, cmd = '') {
return this.app.client
.$(Selectors.CURRENT_PROMPT_BLOCK)
.then(async _ => {
await _.waitForExist()
return _.getAttribute('data-input-count')
})
.then(count => parseInt(count, 10))
.then(count =>
this.app.client
.keys(cmd)
.then(() => this.app.client.keys(keys.ctrlC))
.then(() => ({ app: this.app, count: count }))
.then(ReplExpect.blank)
.then(() => this.app.client.$(Selectors.PROMPT_N(count))) // make sure the cancelled command text is still there, in the previous block
.then(_ => _.getText())
.then(input => assert.strictEqual(input, cmd))
)
.catch(Common.oops(this, true))
}
export function switchToTopLevelTabViaClick(ctx: Common.ISuite, N: number) {
return ctx.app.client
.$(Selectors.TOP_TAB_N_CLICKABLE(N))
.then(_ => _.click())
.then(() => ctx.app.client.$(Selectors.TAB_SELECTED_N(N)))
.then(_ => _.waitForDisplayed())
.catch(Common.oops(ctx, true))
}
export function doClear(this: Common.ISuite, residualBlockCount = 1, splitIndex = 1) {
return CLI.commandInSplit('clear', this.app, splitIndex)
.then(() => ReplExpect.consoleToBeClear(this.app, residualBlockCount, splitIndex))
.then(() => SidecarExpect.closed)
.catch(Common.oops(this, true))
}
export function clickNewTabButton(ctx: Common.ISuite, expectedNewTabIndex: number) {
return ctx.app.client
.$(Selectors.tabButtonSelector)
.then(_ => _.click())
.then(() => ctx.app.client.$(Selectors.TAB_SELECTED_N(expectedNewTabIndex)))
.then(_ => _.waitForDisplayed())
.then(() => CLI.waitForRepl(ctx.app)) // should have an active repl
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Backend } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
BackendContract,
BackendListByServiceNextOptionalParams,
BackendListByServiceOptionalParams,
BackendListByServiceResponse,
BackendGetEntityTagOptionalParams,
BackendGetEntityTagResponse,
BackendGetOptionalParams,
BackendGetResponse,
BackendCreateOrUpdateOptionalParams,
BackendCreateOrUpdateResponse,
BackendUpdateParameters,
BackendUpdateOptionalParams,
BackendUpdateResponse,
BackendDeleteOptionalParams,
BackendReconnectOptionalParams,
BackendListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Backend operations. */
export class BackendImpl implements Backend {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class Backend class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Lists a collection of backends in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: BackendListByServiceOptionalParams
): PagedAsyncIterableIterator<BackendContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: BackendListByServiceOptionalParams
): AsyncIterableIterator<BackendContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: BackendListByServiceOptionalParams
): AsyncIterableIterator<BackendContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Lists a collection of backends in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: BackendListByServiceOptionalParams
): Promise<BackendListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Gets the entity state (Etag) version of the backend specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
backendId: string,
options?: BackendGetEntityTagOptionalParams
): Promise<BackendGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, backendId, options },
getEntityTagOperationSpec
);
}
/**
* Gets the details of the backend specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
backendId: string,
options?: BackendGetOptionalParams
): Promise<BackendGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, backendId, options },
getOperationSpec
);
}
/**
* Creates or Updates a backend.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param parameters Create parameters.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
serviceName: string,
backendId: string,
parameters: BackendContract,
options?: BackendCreateOrUpdateOptionalParams
): Promise<BackendCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, backendId, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates an existing backend.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Update parameters.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
backendId: string,
ifMatch: string,
parameters: BackendUpdateParameters,
options?: BackendUpdateOptionalParams
): Promise<BackendUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
backendId,
ifMatch,
parameters,
options
},
updateOperationSpec
);
}
/**
* Deletes the specified backend.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
serviceName: string,
backendId: string,
ifMatch: string,
options?: BackendDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, backendId, ifMatch, options },
deleteOperationSpec
);
}
/**
* Notifies the APIM proxy to create a new connection to the backend after the specified timeout. If no
* timeout was specified, timeout of 2 minutes is used.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param backendId Identifier of the Backend entity. Must be unique in the current API Management
* service instance.
* @param options The options parameters.
*/
reconnect(
resourceGroupName: string,
serviceName: string,
backendId: string,
options?: BackendReconnectOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, backendId, options },
reconnectOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: BackendListByServiceNextOptionalParams
): Promise<BackendListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BackendCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.BackendGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BackendContract,
headersMapper: Mappers.BackendGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.BackendContract,
headersMapper: Mappers.BackendCreateOrUpdateHeaders
},
201: {
bodyMapper: Mappers.BackendContract,
headersMapper: Mappers.BackendCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters18,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.BackendContract,
headersMapper: Mappers.BackendUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters19,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [Parameters.accept, Parameters.ifMatch1],
serializer
};
const reconnectOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backends/{backendId}/reconnect",
httpMethod: "POST",
responses: {
202: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters20,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.backendId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BackendCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.skip,
Parameters.apiVersion
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { createDuration } from './datelib/duration'
import { mergeProps, isPropsEqual } from './util/object'
import { createFormatter } from './datelib/formatting'
import { parseFieldSpecs } from './util/misc'
import { DateProfileGeneratorClass } from './DateProfileGenerator'
// public
import {
CssDimValue,
DateInput,
DateRangeInput,
BusinessHoursInput,
EventSourceInput,
ViewApi,
LocaleSingularArg, LocaleInput,
EventInput, EventInputTransformer,
OverlapFunc, ConstraintInput, AllowFunc,
PluginDef,
ViewComponentType,
SpecificViewContentArg, SpecificViewMountArg,
ClassNamesGenerator, CustomContentGenerator, DidMountHandler, WillUnmountHandler,
NowIndicatorContentArg, NowIndicatorMountArg,
WeekNumberContentArg, WeekNumberMountArg,
SlotLaneContentArg, SlotLaneMountArg,
SlotLabelContentArg, SlotLabelMountArg,
AllDayContentArg, AllDayMountArg,
DayHeaderContentArg, DayHeaderMountArg,
DayCellContentArg, DayCellMountArg,
ViewContentArg, ViewMountArg,
EventClickArg,
EventHoveringArg,
DateSelectArg, DateUnselectArg,
CalendarApi,
VUIEvent,
WeekNumberCalculation,
FormatterInput,
ToolbarInput, CustomButtonInput, ButtonIconsInput, ButtonTextCompoundInput,
EventContentArg, EventMountArg,
DatesSetArg,
EventApi, EventAddArg, EventChangeArg, EventRemoveArg,
MoreLinkContentArg,
MoreLinkMountArg,
MoreLinkAction,
ButtonHintCompoundInput,
} from './api-type-deps'
// base options
// ------------
export const BASE_OPTION_REFINERS = {
navLinkDayClick: identity as Identity<string | ((this: CalendarApi, date: Date, jsEvent: VUIEvent) => void)>,
navLinkWeekClick: identity as Identity<string | ((this: CalendarApi, weekStart: Date, jsEvent: VUIEvent) => void)>,
duration: createDuration,
bootstrapFontAwesome: identity as Identity<ButtonIconsInput | false>, // TODO: move to bootstrap plugin
buttonIcons: identity as Identity<ButtonIconsInput | false>,
customButtons: identity as Identity<{ [name: string]: CustomButtonInput }>,
defaultAllDayEventDuration: createDuration,
defaultTimedEventDuration: createDuration,
nextDayThreshold: createDuration,
scrollTime: createDuration,
scrollTimeReset: Boolean,
slotMinTime: createDuration,
slotMaxTime: createDuration,
dayPopoverFormat: createFormatter,
slotDuration: createDuration,
snapDuration: createDuration,
headerToolbar: identity as Identity<ToolbarInput | false>,
footerToolbar: identity as Identity<ToolbarInput | false>,
defaultRangeSeparator: String,
titleRangeSeparator: String,
forceEventDuration: Boolean,
dayHeaders: Boolean,
dayHeaderFormat: createFormatter,
dayHeaderClassNames: identity as Identity<ClassNamesGenerator<DayHeaderContentArg>>,
dayHeaderContent: identity as Identity<CustomContentGenerator<DayHeaderContentArg>>,
dayHeaderDidMount: identity as Identity<DidMountHandler<DayHeaderMountArg>>,
dayHeaderWillUnmount: identity as Identity<WillUnmountHandler<DayHeaderMountArg>>,
dayCellClassNames: identity as Identity<ClassNamesGenerator<DayCellContentArg>>,
dayCellContent: identity as Identity<CustomContentGenerator<DayCellContentArg>>,
dayCellDidMount: identity as Identity<DidMountHandler<DayCellMountArg>>,
dayCellWillUnmount: identity as Identity<WillUnmountHandler<DayCellMountArg>>,
initialView: String,
aspectRatio: Number,
weekends: Boolean,
weekNumberCalculation: identity as Identity<WeekNumberCalculation>,
weekNumbers: Boolean,
weekNumberClassNames: identity as Identity<ClassNamesGenerator<WeekNumberContentArg>>,
weekNumberContent: identity as Identity<CustomContentGenerator<WeekNumberContentArg>>,
weekNumberDidMount: identity as Identity<DidMountHandler<WeekNumberMountArg>>,
weekNumberWillUnmount: identity as Identity<WillUnmountHandler<WeekNumberMountArg>>,
editable: Boolean,
viewClassNames: identity as Identity<ClassNamesGenerator<ViewContentArg>>,
viewDidMount: identity as Identity<DidMountHandler<ViewMountArg>>,
viewWillUnmount: identity as Identity<WillUnmountHandler<ViewMountArg>>,
nowIndicator: Boolean,
nowIndicatorClassNames: identity as Identity<ClassNamesGenerator<NowIndicatorContentArg>>,
nowIndicatorContent: identity as Identity<CustomContentGenerator<NowIndicatorContentArg>>,
nowIndicatorDidMount: identity as Identity<DidMountHandler<NowIndicatorMountArg>>,
nowIndicatorWillUnmount: identity as Identity<WillUnmountHandler<NowIndicatorMountArg>>,
showNonCurrentDates: Boolean,
lazyFetching: Boolean,
startParam: String,
endParam: String,
timeZoneParam: String,
timeZone: String,
locales: identity as Identity<LocaleInput[]>,
locale: identity as Identity<LocaleSingularArg>,
themeSystem: String as Identity<'standard' | string>,
dragRevertDuration: Number,
dragScroll: Boolean,
allDayMaintainDuration: Boolean,
unselectAuto: Boolean,
dropAccept: identity as Identity<string | ((this: CalendarApi, draggable: any) => boolean)>, // TODO: type draggable
eventOrder: parseFieldSpecs,
eventOrderStrict: Boolean,
handleWindowResize: Boolean,
windowResizeDelay: Number,
longPressDelay: Number,
eventDragMinDistance: Number,
expandRows: Boolean,
height: identity as Identity<CssDimValue>,
contentHeight: identity as Identity<CssDimValue>,
direction: String as Identity<'ltr' | 'rtl'>,
weekNumberFormat: createFormatter,
eventResizableFromStart: Boolean,
displayEventTime: Boolean,
displayEventEnd: Boolean,
weekText: String, // the short version
weekTextLong: String, // falls back to weekText
progressiveEventRendering: Boolean,
businessHours: identity as Identity<BusinessHoursInput>,
initialDate: identity as Identity<DateInput>,
now: identity as Identity<DateInput | ((this: CalendarApi) => DateInput)>,
eventDataTransform: identity as Identity<EventInputTransformer>,
stickyHeaderDates: identity as Identity<boolean | 'auto'>,
stickyFooterScrollbar: identity as Identity<boolean | 'auto'>,
viewHeight: identity as Identity<CssDimValue>,
defaultAllDay: Boolean,
eventSourceFailure: identity as Identity<(this: CalendarApi, error: any) => void>,
eventSourceSuccess: identity as Identity<(this: CalendarApi, eventsInput: EventInput[], xhr?: XMLHttpRequest) => EventInput[] | void>,
eventDisplay: String, // TODO: give more specific
eventStartEditable: Boolean,
eventDurationEditable: Boolean,
eventOverlap: identity as Identity<boolean | OverlapFunc>,
eventConstraint: identity as Identity<ConstraintInput>,
eventAllow: identity as Identity<AllowFunc>,
eventBackgroundColor: String,
eventBorderColor: String,
eventTextColor: String,
eventColor: String,
eventClassNames: identity as Identity<ClassNamesGenerator<EventContentArg>>,
eventContent: identity as Identity<CustomContentGenerator<EventContentArg>>,
eventDidMount: identity as Identity<DidMountHandler<EventMountArg>>,
eventWillUnmount: identity as Identity<WillUnmountHandler<EventMountArg>>,
selectConstraint: identity as Identity<ConstraintInput>,
selectOverlap: identity as Identity<boolean | OverlapFunc>,
selectAllow: identity as Identity<AllowFunc>,
droppable: Boolean,
unselectCancel: String,
slotLabelFormat: identity as Identity<FormatterInput | FormatterInput[]>,
slotLaneClassNames: identity as Identity<ClassNamesGenerator<SlotLaneContentArg>>,
slotLaneContent: identity as Identity<CustomContentGenerator<SlotLaneContentArg>>,
slotLaneDidMount: identity as Identity<DidMountHandler<SlotLaneMountArg>>,
slotLaneWillUnmount: identity as Identity<WillUnmountHandler<SlotLaneMountArg>>,
slotLabelClassNames: identity as Identity<ClassNamesGenerator<SlotLabelContentArg>>,
slotLabelContent: identity as Identity<CustomContentGenerator<SlotLabelContentArg>>,
slotLabelDidMount: identity as Identity<DidMountHandler<SlotLabelMountArg>>,
slotLabelWillUnmount: identity as Identity<WillUnmountHandler<SlotLabelMountArg>>,
dayMaxEvents: identity as Identity<boolean | number>,
dayMaxEventRows: identity as Identity<boolean | number>,
dayMinWidth: Number,
slotLabelInterval: createDuration,
allDayText: String,
allDayClassNames: identity as Identity<ClassNamesGenerator<AllDayContentArg>>,
allDayContent: identity as Identity<CustomContentGenerator<AllDayContentArg>>,
allDayDidMount: identity as Identity<DidMountHandler<AllDayMountArg>>,
allDayWillUnmount: identity as Identity<WillUnmountHandler<AllDayMountArg>>,
slotMinWidth: Number, // move to timeline?
navLinks: Boolean,
eventTimeFormat: createFormatter,
rerenderDelay: Number, // TODO: move to @fullcalendar/core right? nah keep here
moreLinkText: identity as Identity<string | ((this: CalendarApi, num: number) => string)>, // this not enforced :( check others too
moreLinkHint: identity as Identity<string | ((this: CalendarApi, num: number) => string)>,
selectMinDistance: Number,
selectable: Boolean,
selectLongPressDelay: Number,
eventLongPressDelay: Number,
selectMirror: Boolean,
eventMaxStack: Number,
eventMinHeight: Number,
eventMinWidth: Number,
eventShortHeight: Number,
slotEventOverlap: Boolean,
plugins: identity as Identity<PluginDef[]>,
firstDay: Number,
dayCount: Number,
dateAlignment: String,
dateIncrement: createDuration,
hiddenDays: identity as Identity<number[]>,
monthMode: Boolean,
fixedWeekCount: Boolean,
validRange: identity as Identity<DateRangeInput | ((this: CalendarApi, nowDate: Date) => DateRangeInput)>, // `this` works?
visibleRange: identity as Identity<DateRangeInput | ((this: CalendarApi, currentDate: Date) => DateRangeInput)>, // `this` works?
titleFormat: identity as Identity<FormatterInput>, // DONT parse just yet. we need to inject titleSeparator
eventInteractive: Boolean,
// only used by list-view, but languages define the value, so we need it in base options
noEventsText: String,
viewHint: identity as Identity<string | ((...args: any[]) => string)>,
navLinkHint: identity as Identity<string | ((...args: any[]) => string)>,
closeHint: String,
timeHint: String,
eventHint: String,
moreLinkClick: identity as Identity<MoreLinkAction>,
moreLinkClassNames: identity as Identity<ClassNamesGenerator<MoreLinkContentArg>>,
moreLinkContent: identity as Identity<CustomContentGenerator<MoreLinkContentArg>>,
moreLinkDidMount: identity as Identity<DidMountHandler<MoreLinkMountArg>>,
moreLinkWillUnmount: identity as Identity<WillUnmountHandler<MoreLinkMountArg>>,
}
type BuiltInBaseOptionRefiners = typeof BASE_OPTION_REFINERS
export interface BaseOptionRefiners extends BuiltInBaseOptionRefiners {
// for ambient-extending
}
export type BaseOptions = RawOptionsFromRefiners< // as RawOptions
Required<BaseOptionRefiners> // Required is a hack for "Index signature is missing"
>
// do NOT give a type here. need `typeof BASE_OPTION_DEFAULTS` to give real results.
// raw values.
export const BASE_OPTION_DEFAULTS = {
eventDisplay: 'auto',
defaultRangeSeparator: ' - ',
titleRangeSeparator: ' \u2013 ', // en dash
defaultTimedEventDuration: '01:00:00',
defaultAllDayEventDuration: { day: 1 },
forceEventDuration: false,
nextDayThreshold: '00:00:00',
dayHeaders: true,
initialView: '',
aspectRatio: 1.35,
headerToolbar: {
start: 'title',
center: '',
end: 'today prev,next',
},
weekends: true,
weekNumbers: false,
weekNumberCalculation: 'local' as WeekNumberCalculation,
editable: false,
nowIndicator: false,
scrollTime: '06:00:00',
scrollTimeReset: true,
slotMinTime: '00:00:00',
slotMaxTime: '24:00:00',
showNonCurrentDates: true,
lazyFetching: true,
startParam: 'start',
endParam: 'end',
timeZoneParam: 'timeZone',
timeZone: 'local', // TODO: throw error if given falsy value?
locales: [],
locale: '', // blank values means it will compute based off locales[]
themeSystem: 'standard',
dragRevertDuration: 500,
dragScroll: true,
allDayMaintainDuration: false,
unselectAuto: true,
dropAccept: '*',
eventOrder: 'start,-duration,allDay,title',
dayPopoverFormat: { month: 'long', day: 'numeric', year: 'numeric' },
handleWindowResize: true,
windowResizeDelay: 100, // milliseconds before an updateSize happens
longPressDelay: 1000,
eventDragMinDistance: 5, // only applies to mouse
expandRows: false,
navLinks: false,
selectable: false,
eventMinHeight: 15,
eventMinWidth: 30,
eventShortHeight: 30,
}
export type BaseOptionsRefined = DefaultedRefinedOptions<
RefinedOptionsFromRefiners<Required<BaseOptionRefiners>>, // Required is a hack for "Index signature is missing"
keyof typeof BASE_OPTION_DEFAULTS
>
// calendar listeners
// ------------------
export const CALENDAR_LISTENER_REFINERS = {
datesSet: identity as Identity<(arg: DatesSetArg) => void>,
eventsSet: identity as Identity<(events: EventApi[]) => void>,
eventAdd: identity as Identity<(arg: EventAddArg) => void>,
eventChange: identity as Identity<(arg: EventChangeArg) => void>,
eventRemove: identity as Identity<(arg: EventRemoveArg) => void>,
windowResize: identity as Identity<(arg: { view: ViewApi }) => void>,
eventClick: identity as Identity<(arg: EventClickArg) => void>, // TODO: resource for scheduler????
eventMouseEnter: identity as Identity<(arg: EventHoveringArg) => void>,
eventMouseLeave: identity as Identity<(arg: EventHoveringArg) => void>,
select: identity as Identity<(arg: DateSelectArg) => void>, // resource for scheduler????
unselect: identity as Identity<(arg: DateUnselectArg) => void>,
loading: identity as Identity<(isLoading: boolean) => void>,
// internal
_unmount: identity as Identity<() => void>,
_beforeprint: identity as Identity<() => void>,
_afterprint: identity as Identity<() => void>,
_noEventDrop: identity as Identity<() => void>,
_noEventResize: identity as Identity<() => void>,
_resize: identity as Identity<(forced: boolean) => void>,
_scrollRequest: identity as Identity<(arg: any) => void>,
}
type BuiltInCalendarListenerRefiners = typeof CALENDAR_LISTENER_REFINERS
export interface CalendarListenerRefiners extends BuiltInCalendarListenerRefiners {
// for ambient extending
}
type CalendarListenersLoose = RefinedOptionsFromRefiners<Required<CalendarListenerRefiners>> // Required hack
export type CalendarListeners = Required<CalendarListenersLoose> // much more convenient for Emitters and whatnot
// calendar-specific options
// -------------------------
export const CALENDAR_OPTION_REFINERS = { // does not include base nor calendar listeners
buttonText: identity as Identity<ButtonTextCompoundInput>,
buttonHints: identity as Identity<ButtonHintCompoundInput>,
views: identity as Identity<{ [viewId: string]: ViewOptions }>,
plugins: identity as Identity<PluginDef[]>,
initialEvents: identity as Identity<EventSourceInput>,
events: identity as Identity<EventSourceInput>,
eventSources: identity as Identity<EventSourceInput[]>,
}
type BuiltInCalendarOptionRefiners = typeof CALENDAR_OPTION_REFINERS
export interface CalendarOptionRefiners extends BuiltInCalendarOptionRefiners {
// for ambient-extending
}
export type CalendarOptions =
BaseOptions &
CalendarListenersLoose &
RawOptionsFromRefiners<Required<CalendarOptionRefiners>> // Required hack https://github.com/microsoft/TypeScript/issues/15300
export type CalendarOptionsRefined =
BaseOptionsRefined &
CalendarListenersLoose &
RefinedOptionsFromRefiners<Required<CalendarOptionRefiners>> // Required hack
export const COMPLEX_OPTION_COMPARATORS: {
[optionName in keyof CalendarOptions]: (a: CalendarOptions[optionName], b: CalendarOptions[optionName]) => boolean
} = {
headerToolbar: isBoolComplexEqual,
footerToolbar: isBoolComplexEqual,
buttonText: isBoolComplexEqual,
buttonHints: isBoolComplexEqual,
buttonIcons: isBoolComplexEqual,
}
function isBoolComplexEqual(a, b) {
if (typeof a === 'object' && typeof b === 'object' && a && b) { // both non-null objects
return isPropsEqual(a, b)
}
return a === b
}
// view-specific options
// ---------------------
export const VIEW_OPTION_REFINERS: {
[name: string]: any
} = {
type: String,
component: identity as Identity<ViewComponentType>,
buttonText: String,
buttonTextKey: String, // internal only
dateProfileGeneratorClass: identity as Identity<DateProfileGeneratorClass>,
usesMinMaxTime: Boolean, // internal only
classNames: identity as Identity<ClassNamesGenerator<SpecificViewContentArg>>,
content: identity as Identity<CustomContentGenerator<SpecificViewContentArg>>,
didMount: identity as Identity<DidMountHandler<SpecificViewMountArg>>,
willUnmount: identity as Identity<WillUnmountHandler<SpecificViewMountArg>>,
}
type BuiltInViewOptionRefiners = typeof VIEW_OPTION_REFINERS
export interface ViewOptionRefiners extends BuiltInViewOptionRefiners {
// for ambient-extending
}
export type ViewOptions =
BaseOptions &
CalendarListenersLoose &
RawOptionsFromRefiners<Required<ViewOptionRefiners>> // Required hack
export type ViewOptionsRefined =
BaseOptionsRefined &
CalendarListenersLoose &
RefinedOptionsFromRefiners<Required<ViewOptionRefiners>> // Required hack
// util funcs
// ----------------------------------------------------------------------------------------------------
export function mergeRawOptions(optionSets: Dictionary[]) {
return mergeProps(optionSets, COMPLEX_OPTION_COMPARATORS)
}
export function refineProps<Refiners extends GenericRefiners, Raw extends RawOptionsFromRefiners<Refiners>>(
input: Raw,
refiners: Refiners,
): {
refined: RefinedOptionsFromRefiners<Refiners>,
extra: Dictionary,
} {
let refined = {} as any
let extra = {} as any
for (let propName in refiners) {
if (propName in input) {
refined[propName] = refiners[propName](input[propName])
}
}
for (let propName in input) {
if (!(propName in refiners)) {
extra[propName] = input[propName]
}
}
return { refined, extra }
}
// definition utils
// ----------------------------------------------------------------------------------------------------
export type GenericRefiners = {
[propName: string]: (input: any) => any
}
export type GenericListenerRefiners = {
[listenerName: string]: Identity<(this: CalendarApi, ...args: any[]) => void>
}
export type RawOptionsFromRefiners<Refiners extends GenericRefiners> = {
[Prop in keyof Refiners]?: // all optional
Refiners[Prop] extends ((input: infer RawType) => infer RefinedType)
? (any extends RawType ? RefinedType : RawType) // if input type `any`, use output (for Boolean/Number/String)
: never
}
export type RefinedOptionsFromRefiners<Refiners extends GenericRefiners> = {
[Prop in keyof Refiners]?: // all optional
Refiners[Prop] extends ((input: any) => infer RefinedType) ? RefinedType : never
}
export type DefaultedRefinedOptions<RefinedOptions extends Dictionary, DefaultKey extends keyof RefinedOptions> =
Required<Pick<RefinedOptions, DefaultKey>> &
Partial<Omit<RefinedOptions, DefaultKey>>
export type Dictionary = Record<string, any>
export type Identity<T = any> = (raw: T) => T
export function identity<T>(raw: T): T {
return raw
} | the_stack |
import { expect, test } from '@jest/globals';
import { Injector, InjectorContext, injectorReference } from '../src/injector';
import { provide, Tag } from '../src/provider';
import { InjectorModule } from '../src/module';
import { typeOf } from '@deepkit/type';
import { Inject } from '../src/types';
test('basic', () => {
class Service {
}
const module1 = new InjectorModule([Service]);
const context = new InjectorContext(module1);
const injector = context.getInjector(module1);
expect(injector.get(Service)).toBeInstanceOf(Service);
expect(injector.get(Service) === injector.get(Service)).toBe(true);
});
test('parent dependency', () => {
class Router {
}
class Controller {
constructor(public router: Router) {
}
}
const module1 = new InjectorModule([Router]);
const module2 = new InjectorModule([Controller], module1)
const context = new InjectorContext(module1);
const injector = context.getInjector(module2);
expect(injector.get(Controller)).toBeInstanceOf(Controller);
});
test('scoped provider', () => {
class Service {
}
const module1 = new InjectorModule([{ provide: Service, scope: 'http' }]);
const context = new InjectorContext(module1);
const injector = context.getInjector(module1);
expect(() => injector.get(Service)).toThrow('not found');
expect(context.createChildScope('http').get(Service)).toBeInstanceOf(Service);
const scope = { name: 'http', instances: {} };
expect(injector.get(Service, scope)).toBeInstanceOf(Service);
expect(injector.get(Service, scope) === injector.get(Service, scope)).toBe(true);
});
test('scoped provider with dependency to unscoped', () => {
class Service {
}
const module1 = new InjectorModule([{ provide: Service, scope: 'http' }]);
const context = new InjectorContext(module1);
const injector = context.getInjector(module1);
expect(() => injector.get(Service)).toThrow('not found');
const scope = context.createChildScope('http');
expect(scope.get(Service)).toBeInstanceOf(Service);
expect(scope.get(Service) === scope.get(Service)).toBe(true);
});
test('reset', () => {
class Service {
}
const module1 = new InjectorModule([Service]);
const context = new InjectorContext(module1);
const injector = context.getInjector(module1);
const service1 = injector.get(Service);
expect(service1).toBeInstanceOf(Service);
expect(injector.get(Service) === injector.get(Service)).toBe(true);
injector.clear();
const service2 = injector.get(Service);
expect(service2).toBeInstanceOf(Service);
expect(service2 === service1).toBe(false);
expect(service2 === injector.get(Service)).toBe(true);
});
test('scopes', () => {
class Service {
}
const module1 = new InjectorModule([{ provide: Service, scope: 'http' }]);
const context = new InjectorContext(module1);
const scope1 = context.createChildScope('http');
const scope2 = context.createChildScope('http');
expect(scope1.get(Service, module1)).toBeInstanceOf(Service);
expect(scope1.get(Service, module1) === scope1.get(Service, module1)).toBe(true);
expect(scope2.get(Service, module1)).toBeInstanceOf(Service);
expect(scope2.get(Service, module1) === scope2.get(Service, module1)).toBe(true);
expect(scope1.get(Service, module1) === scope2.get(Service, module1)).toBe(false);
});
test('tags', () => {
class ServiceA {
}
class ServiceB {
}
class ServiceC {
collect() {
}
}
interface Collector {
collect(): void;
}
class CollectorTag extends Tag<Collector> {
}
class CollectorManager {
constructor(protected collectors: CollectorTag) {
}
getCollectors(): Collector[] {
return this.collectors.services;
}
}
const module1 = new InjectorModule([CollectorManager, ServiceA, ServiceB, CollectorTag.provide(ServiceC)]);
const context = new InjectorContext(module1);
const collector = context.getInjector(module1).get(CollectorManager).getCollectors();
expect(collector).toHaveLength(1);
expect(collector[0]).toBeInstanceOf(ServiceC);
});
test('scope late binding', () => {
let createdSessions: number = 0;
let createdRequests: number = 0;
class Session {
constructor() {
createdSessions++;
}
}
class Request {
constructor() {
createdRequests++;
}
}
class Controller {
constructor(public session: Session, public request: Request) {
}
}
const root1 = new InjectorModule([
{ provide: Session, scope: 'http' },
{ provide: Request, scope: 'http' },
]);
const module1 = new InjectorModule([{ provide: Controller, scope: 'http' }], root1);
const request = new Request();
for (let i = 0; i < 10; i++) {
const context = new InjectorContext(root1).createChildScope('http');
context.set(Request, request, root1);
const controller = context.get(Controller, module1);
expect(controller.request === request).toBe(true);
expect(createdSessions).toBe(i + 1);
expect(createdRequests).toBe(1);
}
});
test('all same scope', () => {
class RpcKernelConnection {
}
class Controller {
constructor(public connection: RpcKernelConnection) {
}
}
const injector = InjectorContext.forProviders([
{ provide: RpcKernelConnection, scope: 'rpc' },
{ provide: Controller, scope: 'rpc' },
]);
const controller = injector.createChildScope('rpc').get(Controller);
expect(controller).toBeInstanceOf(Controller);
});
test('exports have access to encapsulated module', () => {
//for exports its important that exported providers still have access to the encapsulated module they were defined in.
class ServiceHelper {
}
class Service {
constructor(public helper: ServiceHelper) {
}
}
class Controller {
constructor(public service: Service) {
}
}
{
const root = new InjectorModule([Controller]);
const module1 = new InjectorModule([
Service, ServiceHelper
], root, {}, [Service]);
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.service).toBeInstanceOf(Service);
expect(controller.service.helper).toBeInstanceOf(ServiceHelper);
expect(injector.get(Service) === controller.service).toBe(true);
expect(() => injector.get(ServiceHelper)).toThrow('not found');
expect(injector.get(ServiceHelper, module1) === controller.service.helper).toBe(true);
}
{
class RootModule extends InjectorModule {
}
class MiddleMan extends InjectorModule {
}
class ServiceModule extends InjectorModule {
}
const root = new RootModule([Controller]);
const module1 = new MiddleMan([], root, {}, []);
const module2 = new ServiceModule([
Service, ServiceHelper
], module1, {}, [Service]);
module1.exports = [module2];
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.service).toBeInstanceOf(Service);
expect(controller.service.helper).toBeInstanceOf(ServiceHelper);
expect(injector.get(Service) === controller.service).toBe(true);
expect(() => injector.get(ServiceHelper)).toThrow('not found');
expect(injector.get(ServiceHelper, module2) === controller.service.helper).toBe(true);
}
{
class RootModule extends InjectorModule {
}
class MiddleMan1 extends InjectorModule {
}
class MiddleMan2 extends InjectorModule {
}
class ServiceModule extends InjectorModule {
}
const root = new RootModule([Controller]);
const module1 = new MiddleMan1([], root, {}, []);
const module2 = new MiddleMan2([], module1, {}, []);
const module3 = new ServiceModule([
Service, ServiceHelper
], module2, {}, [Service]);
module1.exports = [module2];
module2.exports = [module3];
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.service).toBeInstanceOf(Service);
expect(controller.service.helper).toBeInstanceOf(ServiceHelper);
expect(injector.get(Service) === controller.service).toBe(true);
expect(() => injector.get(ServiceHelper)).toThrow('not found');
expect(injector.get(ServiceHelper, module3) === controller.service.helper).toBe(true);
}
});
test('useClass redirects and does not create 2 instances when its already provided', () => {
class DefaultStrategy {
}
class SpecialisedStrategy {
}
{
const root = new InjectorModule([
DefaultStrategy,
{ provide: DefaultStrategy, useClass: SpecialisedStrategy }
]);
const injector = new InjectorContext(root);
const defaultStrategy = injector.get(DefaultStrategy);
expect(defaultStrategy).toBeInstanceOf(SpecialisedStrategy);
//useClass does not get their own token.
expect(() => injector.get(SpecialisedStrategy)).toThrow('not found');
}
{
const root = new InjectorModule([
SpecialisedStrategy,
{ provide: DefaultStrategy, useClass: SpecialisedStrategy }
]);
const injector = new InjectorContext(root);
const defaultStrategy = injector.get(DefaultStrategy);
expect(defaultStrategy).toBeInstanceOf(SpecialisedStrategy);
//because useClass it not the same as useExisting
expect(defaultStrategy === injector.get(SpecialisedStrategy)).toBe(false);
}
{
const root = new InjectorModule([
SpecialisedStrategy,
{ provide: DefaultStrategy, useExisting: SpecialisedStrategy }
]);
const injector = new InjectorContext(root);
const defaultStrategy = injector.get(DefaultStrategy);
expect(defaultStrategy).toBeInstanceOf(SpecialisedStrategy);
expect(defaultStrategy === injector.get(SpecialisedStrategy)).toBe(true);
}
});
test('scope merging', () => {
class Request {
constructor(public id: number) {
}
}
const root = new InjectorModule([
{ provide: Request, useValue: new Request(-1) },
{ provide: Request, useValue: new Request(0), scope: 'rpc' },
{ provide: Request, useValue: new Request(1), scope: 'http' },
{ provide: Request, useValue: new Request(2), scope: 'http' },
]);
const injector = new InjectorContext(root);
injector.getInjector(root); //trigger build
const preparedProvider = root.getPreparedProvider(Request);
expect(preparedProvider!.providers).toHaveLength(3);
expect(preparedProvider!.providers[0].scope).toBe('rpc');
expect(preparedProvider!.providers[1].scope).toBe('http');
expect(preparedProvider!.providers[2].scope).toBe(undefined);
{
const request1 = injector.createChildScope('rpc').get(Request);
expect(request1).toBeInstanceOf(Request);
expect(request1.id).toBe(0);
const request2 = injector.createChildScope('http').get(Request);
expect(request2).toBeInstanceOf(Request);
expect(request2.id).toBe(2); //last provider is used
const request3 = injector.createChildScope('unknown').get(Request);
expect(request3).toBeInstanceOf(Request);
expect(request3.id).toBe(-1); //unscoped
}
});
test('forRoot', () => {
class Router {
}
class Controller {
constructor(public router: Router) {
}
}
{
const root = new InjectorModule([
Controller,
]);
const module1 = new InjectorModule([
Router
], root, {}, []).forRoot();
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.router).toBeInstanceOf(Router);
expect(controller.router === injector.get(Router, module1)).toBe(true);
}
{
const root = new InjectorModule([
Controller,
]);
const module1 = new InjectorModule([], root, {}, []);
const module2 = new InjectorModule([
Router
], module1, {}, []).forRoot();
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.router).toBeInstanceOf(Router);
expect(controller.router === injector.get(Router, module2)).toBe(true);
}
});
test('disableExports', () => {
class Router {
}
class Controller {
constructor(public router?: Router) {
}
}
{
const root = new InjectorModule([
Controller,
]);
const module1 = new InjectorModule([
Router
], root, {}, []).disableExports();
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller).toBeInstanceOf(Controller);
expect(controller.router).toBe(undefined);
expect(injector.get(Router, module1)).toBeInstanceOf(Router);
}
});
test('unscoped to scope dependency invalid', () => {
class HttpRequest {
}
class Controller {
constructor(public request: HttpRequest) {
}
}
{
const root = new InjectorModule([
Controller, { provide: HttpRequest, scope: 'http' },
]);
const injector = new InjectorContext(root);
const scope = injector.createChildScope('http');
expect(() => scope.get(Controller)).toThrow(`Dependency 'request: HttpRequest' of Controller.request can not be injected into no scope, since HttpRequest only exists in scope http`);
}
});
test('non-exported dependencies can not be overwritten', () => {
class Encapsulated {
}
class Service {
constructor(public encapsulated: Encapsulated) {
}
}
class Controller {
constructor(public service: Service) {
}
}
{
const root = new InjectorModule([
Controller
]);
const serviceModule = new InjectorModule([
Service, Encapsulated,
], root, {}, [Service]);
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller.service).toBeInstanceOf(Service);
expect(controller.service.encapsulated).toBeInstanceOf(Encapsulated);
}
{
class MyService {
constructor(public encapsulated: Encapsulated) {
}
}
const root = new InjectorModule([
Controller, { provide: Service, useClass: MyService }
]);
const serviceModule = new InjectorModule([
Service, Encapsulated,
], root, {}, [Service]);
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller.service).toBeInstanceOf(MyService);
expect(controller.service.encapsulated).toBeInstanceOf(Encapsulated);
}
{
class MyEncapsulated {
}
class MyService {
constructor(public encapsulated: Encapsulated) {
}
}
const root = new InjectorModule([
Controller,
{ provide: Service, useClass: MyService },
{ provide: Encapsulated, useClass: MyEncapsulated },
]);
const serviceModule = new InjectorModule([
Service, Encapsulated,
], root, {}, [Service]);
const injector = new InjectorContext(root);
const controller = injector.get(Controller);
expect(controller.service).toBeInstanceOf(MyService);
//since Encapsulated was not exported, it can not be overwritten.
expect(controller.service.encapsulated).toBeInstanceOf(Encapsulated);
}
});
test('forRoot module keeps reference to config', () => {
class Config {
listen: string = '';
}
class Service {
constructor(public listen: Config['listen']) {
}
}
class MyModule extends InjectorModule {
}
const root = new InjectorModule([]);
const module = new MyModule([
Service
], root, { listen: 'localhost' }).forRoot().setConfigDefinition(Config);
const injector = new InjectorContext(root);
const service = injector.get(Service, module);
expect(service).toBeInstanceOf(Service);
expect(service.listen).toBe('localhost');
});
test('setup provider by class', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
const root = new InjectorModule([Service]);
root.setupProvider<Service>().add('a');
root.setupProvider<Service>().add('b');
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service.list).toEqual(['a', 'b']);
});
test('setup provider by interface 1', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
interface ServiceInterface {
add(item: any): any;
}
const root = new InjectorModule([Service]);
root.setupProvider<ServiceInterface>().add('a');
root.setupProvider<ServiceInterface>().add('b');
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service.list).toEqual(['a', 'b']);
});
test('setup provider by interface 2', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
interface ServiceInterface {
list: any[];
add(item: any): any;
}
const root = new InjectorModule([provide<ServiceInterface>(Service)]);
root.setupProvider<ServiceInterface>().add('a');
root.setupProvider<ServiceInterface>().add('b');
const injector = new InjectorContext(root);
const service = injector.get<ServiceInterface>();
expect(service.list).toEqual(['a', 'b']);
});
test('setup provider in sub module', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
const root = new InjectorModule([]);
const module = new InjectorModule([Service], root);
module.setupProvider<Service>().add('a');
module.setupProvider<Service>().add('b');
const injector = new InjectorContext(root);
const service = injector.get(Service, module);
expect(service.list).toEqual(['a', 'b']);
});
test('setup provider in exported sub module', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
const root = new InjectorModule([]);
const module = new InjectorModule([Service], root, {}, [Service]);
module.setupProvider<Service>().add('a');
module.setupProvider(0, Service).add('b');
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service.list).toEqual(['a', 'b']);
});
test('global setup provider', () => {
class Service {
list: any[] = [];
add(item: any) {
this.list.push(item);
}
}
const root = new InjectorModule([Service]);
const module = new InjectorModule([], root);
module.setupGlobalProvider<Service>().add('a');
module.setupGlobalProvider<Service>().add('b');
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service.list).toEqual(['a', 'b']);
});
test('second forRoot modules overwrites first forRoot providers', () => {
class Service {
}
class NewService {
}
const root = new InjectorModule([]);
//the order in which imports are added is important. Last imports have higher importance.
const module1 = new InjectorModule([Service], root).forRoot();
const module2 = new InjectorModule([{ provide: Service, useClass: NewService }], root).forRoot();
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service).toBeInstanceOf(NewService);
});
test('set service', () => {
class Service {
}
const injector = InjectorContext.forProviders([
{ provide: Service, useValue: undefined },
]);
const s = new Service;
injector.set(Service, s);
expect(injector.get(Service) === s).toBe(true);
});
test('set service in scope', () => {
class Service {
}
class Connection {
constructor(public service: Service) {
}
}
class Request {
}
const injector = InjectorContext.forProviders([
Service,
{ provide: Request, scope: 'tcp' },
{ provide: Connection, scope: 'tcp' }
]);
const s1 = injector.get(Service);
{
const scope = injector.createChildScope('tcp');
const c1 = new Connection(scope.get(Service));
scope.set(Connection, c1);
expect(scope.get(Connection) === c1).toBe(true);
expect(scope.get(Connection) === c1).toBe(true);
expect(scope.get(Connection).service === s1).toBe(true);
}
{
const scope = injector.createChildScope('tcp');
const c1 = new Connection(scope.get(Service));
scope.set(Connection, c1);
expect(scope.get(Connection) === c1).toBe(true);
expect(scope.get(Connection) === c1).toBe(true);
expect(scope.get(Connection).service === s1).toBe(true);
}
});
test('global service from another module is available in sibling module', () => {
class HttpRequest {
}
const httpModule = new InjectorModule([{ provide: HttpRequest, scope: 'http' }]);
class Controller {
constructor(public request: HttpRequest) {
}
}
const apiModule = new InjectorModule([{ provide: Controller, scope: 'http' }]);
const root = new InjectorModule();
httpModule.forRoot().setParent(root);
apiModule.setParent(root);
// const properties = root.getPreparedProviders({} as any);
// (root as any).handleExports({} as any);
// expect(properties.has(HttpRequest)).toBe(true);
const injector = new InjectorContext(root);
const scope = injector.createChildScope('http');
const controller = scope.get(Controller, apiModule);
expect(controller).toBeInstanceOf(Controller);
expect(controller.request).toBeInstanceOf(HttpRequest);
});
test('string reference manually type', () => {
class Service {
add() {
}
}
const root = new InjectorModule([{ provide: 'service', useClass: Service }]);
const injector = new InjectorContext(root);
const service = injector.get<Service>('service');
service.add();
expect(service).toBeInstanceOf(Service);
});
test('provide() with provider', () => {
interface Redis {
get(key: string): any;
}
class RedisImplementation implements Redis {
get(key: string): any {
return true;
}
}
class Service {
constructor(public redis: Redis) {
}
}
const root = new InjectorModule([
Service,
provide<Redis>({
useFactory: () => {
return new RedisImplementation;
}
})
]);
const injector = new InjectorContext(root);
const service = injector.get(Service);
expect(service.redis.get('abc')).toBe(true);
});
test('injectorReference from other module', () => {
class Service {
}
class Registry {
services: any[] = [];
register(service: any) {
this.services.push(service);
}
}
const module1 = new InjectorModule([Service]);
const module2 = new InjectorModule([Registry]);
module2.setupProvider<Registry>().register(injectorReference(Service, module1));
const root = new InjectorModule([]).addImport(module1, module2);
const injector = new InjectorContext(root);
{
const registry = injector.get(Registry, module2);
expect(registry.services).toHaveLength(1);
expect(registry.services[0]).toBeInstanceOf(Service);
}
});
test('inject its own module', () => {
class Service {
constructor(public module: ApiModule) {
}
}
class ApiModule extends InjectorModule {
}
{
const module1 = new ApiModule([Service]);
const root = new InjectorModule([]).addImport(module1);
const injector = new InjectorContext(root);
const service = injector.get(Service, module1);
expect(service.module).toBeInstanceOf(ApiModule);
}
{
const module1 = new ApiModule([Service]).addExport(Service);
const root = new InjectorModule([]).addImport(module1);
const injector = new InjectorContext(root);
const service = injector.get(Service, module1);
expect(service.module).toBeInstanceOf(ApiModule);
}
});
test('provider with function as token', () => {
function MyOldClass() {
return 'hi';
}
//in es5 code, classes are actual functions and not detectable as class
const root = new InjectorModule([{ provide: MyOldClass as any, useValue: MyOldClass }]);
const injector = new InjectorContext(root);
const fn = injector.get(MyOldClass);
expect(fn()).toBe('hi');
});
test('instantiatedCount singleton', () => {
class Service {
}
class Registry {
}
const module1 = new InjectorModule([Service]);
const module2 = new InjectorModule([Registry]).addExport(Registry);
const root = new InjectorModule([]).addImport(module1, module2);
const injector = new InjectorContext(root);
{
expect(injector.instantiationCount(Service, module1)).toBe(0);
injector.get(Service, module1);
expect(injector.instantiationCount(Service, module1)).toBe(1);
injector.get(Service, module1);
expect(injector.instantiationCount(Service, module1)).toBe(1);
}
{
expect(injector.instantiationCount(Registry, module2)).toBe(0);
injector.get(Registry, module2);
expect(injector.instantiationCount(Registry, module2)).toBe(1);
injector.get(Registry, module2);
expect(injector.instantiationCount(Registry, module2)).toBe(1);
injector.createChildScope('http').get(Registry, module2);
expect(injector.instantiationCount(Registry, module2)).toBe(1);
}
});
test('instantiatedCount scope', () => {
class Request {
}
const module1 = new InjectorModule([{ provide: Request, scope: 'http' }]).addExport(Request);
const root = new InjectorModule([{ provide: Request, scope: 'rpc' }]).addImport(module1);
const injector = new InjectorContext(root);
expect(injector.instantiationCount(Request, module1)).toBe(0);
{
expect(injector.createChildScope('http').instantiationCount(Request, module1, 'http')).toBe(0);
injector.createChildScope('http').get(Request, module1);
expect(injector.instantiationCount(Request, module1)).toBe(0);
expect(injector.createChildScope('http').instantiationCount(Request, module1, 'http')).toBe(1);
injector.createChildScope('http').get(Request, module1);
expect(injector.createChildScope('http').instantiationCount(Request, module1, 'http')).toBe(2);
injector.createChildScope('rpc').get(Request);
expect(injector.instantiationCount(Request, undefined, 'http')).toBe(2);
expect(injector.instantiationCount(Request, undefined, 'rpc')).toBe(1);
}
});
test('configuration work in deeply nested imports with overridden service', () => {
class BrokerConfig {
listen!: string;
}
class BrokerServer {
constructor(public listen: BrokerConfig['listen']) {
}
}
class BrokerModule extends InjectorModule {
}
class ApplicationServer {
constructor(public broker: BrokerServer) {
}
}
class FrameworkModule extends InjectorModule {
}
const brokerModule = new BrokerModule([BrokerServer], undefined, { listen: '0.0.0.0' }).addExport(BrokerServer).setConfigDefinition(BrokerConfig);
const frameworkModule = new FrameworkModule([ApplicationServer]).addImport(brokerModule).addExport(BrokerModule, ApplicationServer);
class Broker {
constructor(public server: BrokerServer) {
}
}
class BrokerMemoryServer extends BrokerServer {
}
const root = new InjectorModule([
{ provide: BrokerServer, useClass: BrokerMemoryServer }
]).addImport(frameworkModule);
const injector = new InjectorContext(root);
const applicationServer = injector.get(ApplicationServer);
expect(applicationServer.broker.listen).toBe('0.0.0.0');
expect(applicationServer.broker).toBeInstanceOf(BrokerMemoryServer);
const brokerServer = injector.get(BrokerServer);
expect(brokerServer).toBeInstanceOf(BrokerMemoryServer);
expect(brokerServer.listen).toBe('0.0.0.0');
});
test('exported scoped can be replaced for another scope', () => {
class HttpRequest {
}
class HttpModule extends InjectorModule {
}
const httpModule = new HttpModule([{ provide: HttpRequest, scope: 'http' }]).addExport(HttpRequest);
class FrameworkModule extends InjectorModule {
}
const frameworkModule = new FrameworkModule([{ provide: HttpRequest, scope: 'rpc' }]).addImport(httpModule).addExport(HttpModule, HttpRequest);
const root = new InjectorModule().addImport(frameworkModule);
const injector = new InjectorContext(root);
expect(() => injector.get(HttpRequest)).toThrow('not found');
const scopeHttp = injector.createChildScope('http');
const httpRequest1 = scopeHttp.get(HttpRequest);
expect(httpRequest1).toBeInstanceOf(HttpRequest);
const scopeRpc = injector.createChildScope('rpc');
const httpRequest2 = scopeRpc.get(HttpRequest);
expect(httpRequest2).toBeInstanceOf(HttpRequest);
expect(httpRequest2 !== httpRequest1).toBe(true);
});
test('consume config from imported modules', () => {
class ModuleConfig {
host: string = '0.0.0.0';
}
class ModuleService {
constructor(public host: ModuleConfig['host']) {
}
}
const moduleModule = new InjectorModule([ModuleService]).setConfigDefinition(ModuleConfig);
class OverriddenService extends ModuleService {
}
const root = new InjectorModule([OverriddenService]).addImport(moduleModule);
const injector = new InjectorContext(root);
const service = injector.get(OverriddenService);
expect(service.host).toBe('0.0.0.0');
});
test('injector.get by type', () => {
interface LoggerInterface {
log(): boolean;
}
class Logger {
log(): boolean {
return true;
}
}
class Controller {
constructor(public logger: LoggerInterface) {
}
}
const root = new InjectorModule([Controller, Logger]);
const injector = new InjectorContext(root);
const service = injector.get<LoggerInterface>();
expect(service).toBeInstanceOf(Logger);
const controller = injector.get<Controller>();
expect(controller.logger).toBeInstanceOf(Logger);
});
test('exported token from interface', () => {
interface LoggerInterface {
log(): boolean;
}
class Logger {
log(): boolean {
return true;
}
}
class ModuleController {
constructor(public logger: LoggerInterface) {
}
}
class Controller {
constructor(public logger: LoggerInterface) {
}
}
{
const module = new InjectorModule([provide<LoggerInterface>(Logger), ModuleController]).addExport(typeOf<LoggerInterface>(), ModuleController);
const root = new InjectorModule([Controller]).addImport(module);
const injector = new InjectorContext(root);
const service = injector.get<LoggerInterface>();
expect(service).toBeInstanceOf(Logger);
const controller = injector.get<Controller>();
expect(controller.logger).toBeInstanceOf(Logger);
const moduleController = injector.get<ModuleController>();
expect(moduleController.logger).toBeInstanceOf(Logger);
}
{
class OverwrittenLogger {
log(): boolean {
return true;
}
}
const module = new InjectorModule([provide<LoggerInterface>(Logger), ModuleController]).addExport(typeOf<LoggerInterface>(), ModuleController);
const root = new InjectorModule([Controller, OverwrittenLogger]).addImport(module);
const injector = new InjectorContext(root);
const service = injector.get<LoggerInterface>();
expect(service).toBeInstanceOf(OverwrittenLogger);
const controller = injector.get<Controller>();
expect(controller.logger).toBeInstanceOf(OverwrittenLogger);
const moduleController = injector.get<ModuleController>();
expect(moduleController.logger).toBeInstanceOf(OverwrittenLogger);
}
});
test('2 level deep module keeps its instances encapsulated', () => {
class Logger {
}
class QualificationRepository {
}
class QualificationService {
constructor(public qualificationRepo: QualificationRepository, public logger: Logger) {
}
}
class QualificationModule extends InjectorModule {
constructor() {
super();
this.addProvider(QualificationRepository, QualificationService);
this.addExport(QualificationService);
}
}
class EmergencyService {
constructor(public qualificationService: QualificationService) {
}
}
class EmergencyModule extends InjectorModule {
}
const emergencyModule = new EmergencyModule([EmergencyService]).addImport(new QualificationModule).addExport(EmergencyService);
class AnotherModule extends InjectorModule {
}
class AnotherService {
constructor(public qualificationService: QualificationService) {
}
}
const anotherModule = new AnotherModule([AnotherService]).addImport(new QualificationModule);
/**
* Module hierarchy is like
* app
* - EmergencyModule
* - QualificationModule
* - AnotherModule
* - QualificationModule
*
* Each sub-module of app has its own QualificationModule and thus its instances are scoped and not moved to root app.
*
*/
const app = new InjectorModule([Logger]).addImport(emergencyModule, anotherModule);
const injector = new InjectorContext(app);
const emergencyService = injector.get(EmergencyService, emergencyModule);
expect(emergencyService).toBeInstanceOf(EmergencyService);
expect(emergencyService === injector.get(EmergencyService)); //it's moved to the root module
expect(emergencyService.qualificationService).toBeInstanceOf(QualificationService);
expect(emergencyService.qualificationService.qualificationRepo).toBeInstanceOf(QualificationRepository);
expect(emergencyService.qualificationService.logger).toBeInstanceOf(Logger);
const emergencyService2 = injector.get(AnotherService, anotherModule);
expect(emergencyService.qualificationService !== emergencyService2.qualificationService).toBe(true);
});
test('encapsulated module services cannot be used', () => {
//encapsulated service
class Module1Service {
}
class MyModule1 extends InjectorModule {
}
const myModule1 = new MyModule1([Module1Service]);
class Module2Service {
//this should not be possible, even if we import MyModule1
constructor(public module1: Module1Service) {
}
}
class MyModule2 extends InjectorModule {
}
const myModule2 = new MyModule2([Module2Service]).addImport(myModule1);
const app = new InjectorModule([]).addImport(myModule2);
const injector = new InjectorContext(app);
expect(() => injector.get(Module2Service, myModule2)).toThrow(`Undefined dependency "module1: Module1Service" of Module2Service(?)`);
});
test('external pseudo class without annotation', () => {
const Stripe = eval('(function Stripe() {this.isStripe = true;})');
class MyService {
constructor(public stripe: typeof Stripe) {
}
}
const app = new InjectorModule([
{
provide: Stripe, useFactory() {
return new Stripe;
}
},
MyService
]);
const injector = new InjectorContext(app);
const service = injector.get<MyService>();
expect(service.stripe).toBeInstanceOf(Stripe);
expect(service.stripe.isStripe).toBe(true);
});
test('external class without annotation', () => {
const Stripe = eval('(class Stripe { constructor() {this.isStripe = true}})');
class MyService {
constructor(public stripe: typeof Stripe) {
}
}
const app = new InjectorModule([
{
provide: Stripe, useFactory() {
return new Stripe;
}
},
MyService
]);
const injector = new InjectorContext(app);
const service = injector.get<MyService>();
expect(service.stripe).toBeInstanceOf(Stripe);
expect(service.stripe.isStripe).toBe(true);
});
test('inject via string', () => {
const symbol1 = 'string1';
const symbol2 = 'string2';
class MyService {
constructor(
public service1: Inject<any, typeof symbol1>,
public service2: Inject<any, typeof symbol2>,
) {
}
}
const app = new InjectorModule([
{
provide: symbol1, useFactory() {
return { value: 1 };
}
},
{
provide: symbol2, useFactory() {
return { value: 2 };
}
},
MyService
]);
const injector = new InjectorContext(app);
const service = injector.get<MyService>();
expect(service.service1.value).toBe(1);
expect(service.service2.value).toBe(2);
});
test('inject via symbols', () => {
const symbol1 = Symbol();
const symbol2 = Symbol();
class MyService {
constructor(
public service1: Inject<any, typeof symbol1>,
public service2: Inject<any, typeof symbol2>,
) {
}
}
const app = new InjectorModule([
{
provide: symbol1, useFactory() {
return { value: 1 };
}
},
{
provide: symbol2, useFactory() {
return { value: 2 };
}
},
MyService
]);
const injector = new InjectorContext(app);
const service = injector.get<MyService>();
expect(service.service1.value).toBe(1);
expect(service.service2.value).toBe(2);
});
test('class inheritance', () => {
class A {
}
class B {
constructor(public a: A) {
}
}
class C extends B {
}
const app = new InjectorModule([A, C]);
const injector = new InjectorContext(app);
const c = injector.get(C);
expect(c).toBeInstanceOf(C);
expect(c).toBeInstanceOf(B);
expect(c.a).toBeInstanceOf(A);
}); | the_stack |
declare namespace photonui {
// Base
namespace Helpers {
function escapeHtml(string: string): void;
function uuid4(): string;
function cleanNode(node: HTMLElement): void;
function getAbsolutePosition(element: HTMLElement|string): { x: number; y: number };
function numberToCssSize(value: number, defaultValue?: number, nullValue?: string): string;
}
class Base {
constructor(params?: { [key: string]: any });
destroy(): void;
registerCallback(id: string, wEvent: string, callback: Function, thisArg: any): void;
removeCallback(id: string): void;
}
class Widget extends Base {
absolutePosition: { x: number; y: number; }; // readonly
contextMenu: PopupWindow;
contextMenuName: string;
html: HTMLElement; // readonly
layoutOptions: { [key: string]: any };
name: string;
offsetWidth: number; // readonly
offsetHeight: number; // readonly
parent: Widget;
parentName: string;
tooltip: string;
visible: boolean;
show(): void;
hide(): void;
unparent(): void;
addClass(className: string): void;
removeClass(className: string): void;
static getWidget(name: string): Widget;
static domInsert(widget: Widget, element?: HTMLElement|string): void;
}
// Methods
function domInsert(widget: Widget, element?: HTMLElement|string): void;
function getWidget(name: string): Widget;
//Widgets
class FileManager extends Base {
acceptedExts: string[];
acceptedMimes: string[];
dropZone: HTMLElement;
multiselect: boolean;
open(): void;
}
class Translation extends Base {
locale: string;
addCatalogs(catalogs: { [key: string]: any }): void;
guessUserLanguage(): string;
gettext(string: string, replacements?: { [key: string]: string }): string;
lazyGettext(string: string, replacements?: { [key: string]: string }): string;
enableDomScan(enable: boolean): void;
updateDomTranslation(): void;
}
class AccelManager extends Base {
addAccel(id: string, keys: string, callback: Function, safe?: boolean): void;
removeAccel(id: string): void;
}
class MouseManager extends Base {
constructor(params?: { [key: string]: any });
constructor(element?: Widget|HTMLElement, params?: { [key: string]: any });
element: HTMLElement;
threshold: number;
action: string; // readonly
btnLeft: boolean; // readonly
btnMiddle: boolean; // readonly
btnRight: boolean; // readonly
button: string; // readonly
pageX: number; // readonly
pageY: number; // readonly
x: number; // readonly
y: number; // readonly
deltaX: number; // readonly
deltaY: number; // readonly
}
// -----------------------------------
class BaseIcon extends Widget {}
class FAIcon extends BaseIcon {
constructor(params?: { [key: string]: any });
constructor(name: string, params?: { [key: string]: any });
color: string;
iconName: string;
size: string;
}
class SpriteIcon extends BaseIcon {
constructor(params?: { [key: string]: any });
constructor(name: string, params?: { [key: string]: any });
icon: string;
iconName: string;
spriteSheetName: string;
}
// -----------------------------------
class Image extends Widget {
width: number;
height: number;
url: string;
}
class SpriteSheet extends Base {
name: string;
imageUrl: string;
size: string;
icons: { [iconName: string]: number[] };
addIcon(iconName: string, x: number, y: number): void;
removeIcon(iconName: string): void;
getIconPosition(iconName: string): { x: number; y: number; };
getIconCSS(iconName: string): string;
static getSpriteSheet(name: string): SpriteSheet;
}
class Canvas extends Widget {
canvas: HTMLElement;
interactiveMode: HTMLElement;
width: number;
height: number;
getContext(contextId: string): any;
setContext(contextId: string): void;
supportsContext(contextId: string): boolean;
toBlod(imageFormat: string): any; // returns Blob
toBlodHD(imageFormat: string): any; // returns Blob
toDataUrl(imageFormat: string): string;
toDataUrlHD(imageFormat: string): string;
transferControlToProxy(): void;
}
class Label extends Widget {
constructor(params?: { [key: string]: any });
constructor(name: string, params?: { [key: string]: any });
forInput: Field|CheckBox;
forInputName: string;
text: string;
textAlign: string;
}
class Text extends Widget {
rawHtml: string;
text: string;
}
class ProgressBar extends Widget {
orientation: string;
pulsate: boolean;
textVisible: boolean;
value: number;
}
class Separator extends Widget {
orientation: string;
}
class Button extends Widget {
appearance: string; // normal | flat
buttonColor: string;
leftIconName: string;
leftIcon: BaseIcon;
leftIconVisible: boolean;
rightIconName: string;
rightIcon: BaseIcon;
rightIconVisible: boolean;
text: string;
textVisible: boolean;
}
class ColorButton extends Widget {
color: Color;
dialogOnly: boolean;
value: string;
}
class CheckBox extends Widget {
value: boolean;
}
class Switch extends CheckBox {}
class ToggleButton extends CheckBox {}
// -----------------------------------
class Color extends Base {
constructor(color: string);
constructor(params?: { [key: string]: any });
hexString: string;
rgbString: string; // readonly
rgbaString: string; // readonly
red: number;
green: number;
blue: number;
alpha: number;
hue: number;
saturation: number;
brightness: number;
setRGB(red: number, green: number, blue: number): void;
getRGB(): number[];
setRGBA(red: number, green: number, blue: number, alpha: number): void;
getRGBA(): number[];
setHSB(hue: number, saturation: number, brightness: number): void;
}
class ColorPalette extends Widget {
color: Color;
palette: Array<string[]>;
value: string;
static palette: Array<string[]>;
}
class ColorPicker extends Widget {
color: Color;
value: string;
}
// -----------------------------------
class Field extends Widget {
placeholder: string;
value: boolean;
}
class NumericField extends Field {
min: number;
max: number;
step: number;
decimalDigits: number;
decimalSymbol: string;
}
class Slider extends NumericField {
fieldVisible: boolean;
}
class TextAreaField extends Field {
cols: number;
rows: number;
}
class TextField extends Field {
type: string; // text, password, email, search, tel, url
}
// -----------------------------------
class Select extends Widget {
children: Widget[];
childrenNames: string[];
iconVisible: boolean;
placeholder: string;
popupWidth: number;
popupHeight: number;
popupMaxWidth: number;
popupMinWidth: number;
popupMaxHeight: number;
popupMinHeight: number;
popupOffsetWidth: number; // readonly
popupOffsetHeight: number; // readonly
popupPadding: number;
value: any; // string (maybe)
addChild(widget: Widget, layoutOptions?: any): void;
}
class FontSelect extends Select {
fonts: string[];
addFont(fontName: string): void;
}
// -----------------------------------
class Container extends Widget {
child: Widget;
childName: string;
containerNode: HTMLElement; // readonly
horizontalChildExpansion: boolean;
verticalChildExpansion: boolean;
removeChild(widget: Widget): void;
}
class Layout extends Container {
children: Widget[];
childrenNames: string[];
addChild(widget: Widget, layoutOptions?: { [key: string]: any }): void;
empty(): void;
}
class BoxLayout extends Layout {
horizontalPadding: number;
verticalPadding: number;
orientation: string;
spacing: number;
}
class FluidLayout extends Layout {
horizontalPadding: number;
verticalPadding: number;
}
class GridLayout extends Layout {
horizontalPadding: number;
verticalPadding: number;
horizontalSpacing: number;
verticalSpacing: number;
}
class Menu extends Layout {
iconVisible: boolean;
}
class MenuItem extends Menu {
active: boolean;
icon: BaseIcon;
iconName: string;
text: string;
value: any; // string (maybe)
}
class SubMenuItem extends MenuItem {
menu: Menu;
menuName: string;
}
// -----------------------------------
class Viewport extends Container {
width: number;
minWidth: number;
maxWidth: number;
height: number;
minHeight: number;
maxHeight: number;
padding: number;
horizontalScrollbar: boolean;
verticalScrollbar: boolean;
}
// -----------------------------------
class BaseWindow extends Container {
width: number;
minWidth: number;
maxWidth: number;
height: number;
minHeight: number;
maxHeight: number;
padding: number;
position: { x: number; y: number };
x: number;
y: number;
center(): void;
}
class PopupWindow extends BaseWindow {
popupXY(x: number, y: number): void;
popupWidget(widget: Widget): void;
}
class PopupMenu extends PopupWindow {}
class Window extends BaseWindow {
closeButtonVisible: boolean;
modal: boolean;
movable: boolean;
title: string;
moveToFront(): void;
moveToBack(): void;
}
class Dialog extends Window {
buttons: Widget[];
buttonNames: string[];
addButton(widget: Widget, layoutOptions: any): void;
removeButton(widget: Widget): void;
}
class ColorPickerDialog extends Dialog {
color: Color;
}
// -----------------------------------
class TabItem extends Container {
tabHtml: HTMLElement; // readonly
title: string;
}
class TabLayout extends Layout {
activeTab: Widget;
activeTabName: string;
padding: number;
tabsPosition: string; // top, bottom, left, right
}
}
declare function _(string: string, replacements?: { [key: string]: string }): string; // alias of Translation.lazyGettext() | the_stack |
import React from 'react';
import {
Text,
TouchableOpacity,
View,
} from 'react-native';
import {
fireEvent,
render,
RenderAPI,
waitForElement,
} from 'react-native-testing-library';
import {
light,
mapping,
} from '@eva-design/eva';
import { ApplicationProvider } from '../../theme';
import {
RangeDatepicker,
RangeDatepickerProps,
} from './RangeDatepicker.component';
import { RangeCalendar } from '../calendar/rangeCalendar.component';
import {
CalendarRange,
CalendarViewModes,
} from '../calendar/type';
jest.mock('react-native', () => {
const ActualReactNative = jest.requireActual('react-native');
ActualReactNative.UIManager.measureInWindow = (node, callback) => {
callback(0, 0, 42, 42);
};
return ActualReactNative;
});
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
describe('@range-datepicker: component checks', () => {
afterAll(() => {
jest.clearAllMocks();
});
const TestRangeDatepicker = React.forwardRef((props: Partial<RangeDatepickerProps>,
ref: React.Ref<RangeDatepicker>) => {
const [range, setRange] = React.useState(props.range || {});
const onSelect = (nextRange: CalendarRange<Date>): void => {
setRange(nextRange);
props.onSelect && props.onSelect(nextRange);
};
return (
<ApplicationProvider mapping={mapping} theme={light}>
<RangeDatepicker
ref={ref}
{...props}
range={range}
onSelect={onSelect}
/>
</ApplicationProvider>
);
});
/*
* In this test:
* [0] for input touchable
* [1] for backdrop
* ...rest for calendar touchable components
*/
const touchables = {
findInputTouchable: (api: RenderAPI) => api.queryAllByType(TouchableOpacity)[0],
findBackdropTouchable: (api: RenderAPI) => api.queryAllByType(TouchableOpacity)[1],
};
it('should not render range calendar when not focused', () => {
const component = render(
<TestRangeDatepicker/>,
);
expect(component.queryByType(RangeCalendar)).toBeFalsy();
});
it('should render range calendar when becomes focused', async () => {
const component = render(
<TestRangeDatepicker/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeTruthy();
});
it('should render label as string', async () => {
const component = render(
<TestRangeDatepicker label='I love Babel'/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render label as component', async () => {
const component = render(
<TestRangeDatepicker label={props => <Text {...props}>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render label as pure JSX component', async () => {
const component = render(
<TestRangeDatepicker label={<Text>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption as string', async () => {
const component = render(
<TestRangeDatepicker caption='I love Babel'/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption as component', async () => {
const component = render(
<TestRangeDatepicker caption={props => <Text {...props}>I love Babel</Text>}/>,
);
expect(component.queryByText('I love Babel')).toBeTruthy();
});
it('should render caption', async () => {
const component = render(
<TestRangeDatepicker caption={props => <View {...props} testID='caption icon'/>}/>,
);
expect(component.queryByTestId('caption icon')).toBeTruthy();
});
it('should render caption as pure JSX component', async () => {
const component = render(
<TestRangeDatepicker caption={<View testID='caption icon'/>}/>,
);
expect(component.queryByTestId('caption icon')).toBeTruthy();
});
it('should render component passed to accessoryLeft prop', async () => {
const component = render(
<TestRangeDatepicker accessoryLeft={props => <View {...props} testID='accessory left'/>}/>,
);
expect(component.queryByTestId('accessory left')).toBeTruthy();
});
it('should render pure JSX component passed to accessoryLeft prop', async () => {
const component = render(
<TestRangeDatepicker accessoryLeft={<View testID='accessory left'/>}/>,
);
expect(component.queryByTestId('accessory left')).toBeTruthy();
});
it('should render component passed to accessoryRight prop', async () => {
const component = render(
<TestRangeDatepicker accessoryRight={props => <View {...props} testID='accessory right'/>}/>,
);
expect(component.queryByTestId('accessory right')).toBeTruthy();
});
it('should render pure JSX component passed to accessoryRight prop', async () => {
const component = render(
<TestRangeDatepicker accessoryRight={<View testID='accessory right'/>}/>,
);
expect(component.queryByTestId('accessory right')).toBeTruthy();
});
it('should call onSelect only with start date', async () => {
const onSelect = jest.fn((range: CalendarRange<Date>) => {
expect(range).toEqual({
startDate: new Date(today.getFullYear(), today.getMonth(), 7),
endDate: null,
});
});
const component = render(
<TestRangeDatepicker onSelect={onSelect}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('7')[0]);
fireEvent.press(dateTouchable);
});
it('should call onSelect with start and end dates if start date passed to props', async () => {
const onSelect = jest.fn((range: CalendarRange<Date>) => {
expect(range).toEqual({
startDate: new Date(today.getFullYear(), today.getMonth(), 7),
endDate: new Date(today.getFullYear(), today.getMonth(), 8),
});
});
const component = render(
<TestRangeDatepicker
range={{ startDate: new Date(today.getFullYear(), today.getMonth(), 7) }}
onSelect={onSelect}
/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('8')[0]);
fireEvent.press(dateTouchable);
});
it('should call onSelect only with start date if start and end dates passed to props', async () => {
const onSelect = jest.fn((range: CalendarRange<Date>) => {
expect(range).toEqual({
startDate: new Date(today.getFullYear(), today.getMonth(), 7),
endDate: null,
});
});
const initialRange: CalendarRange<Date> = {
startDate: new Date(today.getFullYear(), today.getMonth(), 7),
endDate: new Date(today.getFullYear(), today.getMonth(), 8),
};
const component = render(
<TestRangeDatepicker
range={initialRange}
onSelect={onSelect}
/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const dateTouchable = await waitForElement(() => component.queryAllByText('7')[0]);
fireEvent.press(dateTouchable);
});
it('should render element provided with renderDay prop', async () => {
const component = render(
<TestRangeDatepicker renderDay={() => <View testID='@range-datepicker/cell'/>}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const cells = await waitForElement(() => component.queryAllByTestId('@range-datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should render element provided with renderMonth prop', async () => {
const component = render(
<TestRangeDatepicker
startView={CalendarViewModes.MONTH}
renderMonth={() => <View testID='@range-datepicker/cell'/>}
/>,
);
fireEvent.press(component.queryAllByType(TouchableOpacity)[0]);
const cells = await waitForElement(() => component.queryAllByTestId('@range-datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should render element provided with renderYear prop', async () => {
const component = render(
<TestRangeDatepicker
startView={CalendarViewModes.YEAR}
renderYear={() => <View testID='@range-datepicker/cell'/>}
/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const cells = await waitForElement(() => component.queryAllByTestId('@range-datepicker/cell'));
expect(cells.length).not.toEqual(0);
});
it('should hide calendar when backdrop pressed', async () => {
const component = render(
<TestRangeDatepicker/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const backdrop = await waitForElement(() => touchables.findBackdropTouchable(component));
fireEvent.press(backdrop);
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeFalsy();
});
it('should call onFocus when calendar becomes visible', async () => {
const onFocus = jest.fn();
const component = render(
<TestRangeDatepicker onFocus={onFocus}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
await waitForElement(() => null);
expect(onFocus).toBeCalled();
});
it('should call onBlur when calendar becomes invisible', async () => {
const onBlur = jest.fn();
const component = render(
<TestRangeDatepicker onBlur={onBlur}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
const backdrop = await waitForElement(() => touchables.findBackdropTouchable(component));
fireEvent.press(backdrop);
expect(onBlur).toBeCalled();
});
it('should show calendar by calling `show` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
const component = render(
<TestRangeDatepicker ref={componentRef}/>,
);
componentRef.current.show();
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeTruthy();
});
it('should hide calendar by calling `hide` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
const component = render(
<TestRangeDatepicker ref={componentRef}/>,
);
componentRef.current.show();
await waitForElement(() => null);
componentRef.current.hide();
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeFalsy();
});
it('should show calendar by calling `focus` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
const component = render(
<TestRangeDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeTruthy();
});
it('should hide calendar by calling `blur` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
const component = render(
<TestRangeDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
await waitForElement(() => null);
componentRef.current.blur();
const calendar = await waitForElement(() => component.queryByType(RangeCalendar));
expect(calendar).toBeFalsy();
});
it('should return false if calendar not visible by calling `isFocused` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
render(
<TestRangeDatepicker ref={componentRef}/>,
);
expect(componentRef.current.isFocused()).toEqual(false);
});
it('should return true if calendar visible by calling `isFocused` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
render(
<TestRangeDatepicker ref={componentRef}/>,
);
componentRef.current.focus();
await waitForElement(() => null);
expect(componentRef.current.isFocused()).toEqual(true);
});
it('should call onSelect with empty object when calling `clear` with ref', async () => {
const componentRef: React.RefObject<RangeDatepicker> = React.createRef();
const onSelect = jest.fn();
render(
<TestRangeDatepicker
ref={componentRef}
onSelect={onSelect}
/>,
);
componentRef.current.clear();
await waitForElement(() => null);
expect(onSelect).toBeCalledWith({});
});
it('should call onPress', async () => {
const onPress = jest.fn();
const component = render(
<TestRangeDatepicker onPress={onPress}/>,
);
fireEvent.press(touchables.findInputTouchable(component));
expect(onPress).toBeCalled();
});
it('should call onPressIn', async () => {
const onPressIn = jest.fn();
const component = render(
<TestRangeDatepicker onPressIn={onPressIn}/>,
);
fireEvent(touchables.findInputTouchable(component), 'pressIn');
expect(onPressIn).toBeCalled();
});
it('should call onPressOut', async () => {
const onPressOut = jest.fn();
const component = render(
<TestRangeDatepicker onPressOut={onPressOut}/>,
);
fireEvent(touchables.findInputTouchable(component), 'pressOut');
expect(onPressOut).toBeCalled();
});
}); | the_stack |
import { describe, expect, it } from '@jest/globals'
import http from 'http'
import path from 'path'
import { readFile } from 'fs/promises'
import { App } from '../../packages/app/src'
import { renderFile } from 'eta'
import type { EtaConfig } from 'eta/dist/types/config'
import { InitAppAndTest } from '../../test_helpers/initAppAndTest'
import { makeFetch } from 'supertest-fetch'
describe('Testing App', () => {
it('should launch a basic server', async () => {
const { fetch } = InitAppAndTest((_req, res) => void res.send('Hello World'))
await fetch('/').expect(200, 'Hello World')
})
it('should chain middleware', () => {
const app = new App()
app.use((_req, _res, next) => next()).use((_req, _res, next) => next())
expect(app.middleware.length).toBe(2)
})
it('app.locals are get and set', () => {
const app = new App()
app.locals.hello = 'world'
expect(app.locals.hello).toBe('world')
})
it('Custom noMatchHandler works', async () => {
const app = new App({
noMatchHandler: (req, res) => res.status(404).end(`Oopsie! Page ${req.url} is lost.`)
})
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(404, 'Oopsie! Page / is lost.')
})
it('Custom onError works', async () => {
const app = new App({
onError: (err, req, res) => res.status(500).end(`Ouch, ${err} hurt me on ${req.url} page.`)
})
app.use((_req, _res, next) => next('you'))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(500, 'Ouch, you hurt me on / page.')
})
it('App works with HTTP 1.1', async () => {
const app = new App()
const server = http.createServer()
server.on('request', app.attach)
await makeFetch(server)('/').expect(404)
})
it('req and res inherit properties from previous middlewares', async () => {
const app = new App()
app
.use((req, _res, next) => {
req.body = { hello: 'world' }
next()
})
.use((req, res) => {
res.json(req.body)
})
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, { hello: 'world' })
})
it('req and res inherit properties from previous middlewares asynchronously', async () => {
const app = new App()
app
.use(async (req, _res, next) => {
req.body = await readFile(`${process.cwd()}/tests/fixtures/test.txt`)
next()
})
.use((req, res) => res.send(req.body.toString()))
const server = app.listen()
await makeFetch(server)('/').expect(200, 'I am a text file.')
})
})
describe('Testing App routing', () => {
it('should add routes added before app.use', async () => {
const app = new App()
const router = new App()
router.get('/list', (_, res) => {
res.send('router/list')
})
router.get('/find', (_, res) => {
res.send('router/find')
})
app.use('/router', router)
const server = app.listen(3000)
await makeFetch(server)('/router/list').expect(200, 'router/list')
await makeFetch(server)('/router/find').expect(200, 'router/find')
})
it('should respond on matched route', async () => {
const { fetch } = InitAppAndTest((_req, res) => void res.send('Hello world'), '/route')
await fetch('/route').expect(200, 'Hello world')
})
it('should match wares containing base path', async () => {
const app = new App()
const server = app.listen()
app.use('/abc', (_req, res) => void res.send('Hello world'))
await makeFetch(server)('/abc/def').expect(200, 'Hello world')
await makeFetch(server)('/abcdef').expect(404)
})
it('"*" should catch all undefined routes', async () => {
const app = new App()
const server = app.listen()
app
.get('/route', (_req, res) => void res.send('A different route'))
.all('*', (_req, res) => void res.send('Hello world'))
await makeFetch(server)('/route').expect(200, 'A different route')
await makeFetch(server)('/test').expect(200, 'Hello world')
})
it('should throw 404 on no routes', async () => {
await makeFetch(new App().listen())('/').expect(404)
})
it('should flatten the array of wares', async () => {
const app = new App()
let counter = 1
app.use('/abc', [(_1, _2, next) => counter++ && next(), (_1, _2, next) => counter++ && next()], (_req, res) => {
expect(counter).toBe(3)
res.send('Hello World')
})
await makeFetch(app.listen())('/abc').expect(200, 'Hello World')
})
it('should can set url prefix for the application', async () => {
const app = new App()
const route1 = new App()
route1.get('/route1', (_req, res) => res.send('route1'))
const route2 = new App()
route2.get('/route2', (_req, res) => res.send('route2'))
const route3 = new App()
route3.get('/route3', (_req, res) => res.send('route3'))
app.use('/abc', ...[route1, route2, route3])
await makeFetch(app.listen())('/abc/route1').expect(200, 'route1')
await makeFetch(app.listen())('/abc/route2').expect(200, 'route2')
await makeFetch(app.listen())('/abc/route3').expect(200, 'route3')
})
describe('next(err)', () => {
it('next function skips current middleware', async () => {
const app = new App()
app.locals['log'] = 'test'
app
.use((req, _res, next) => {
app.locals['log'] = req.url
next()
})
.use((_req, res) => void res.json({ ...app.locals }))
await makeFetch(app.listen())('/').expect(200, { log: '/' })
})
it('next function handles errors', async () => {
const app = new App()
app.use((req, res, next) => {
if (req.url === '/broken') {
next('Your appearance destroyed this world.')
} else {
res.send('Welcome back')
}
})
await makeFetch(app.listen())('/broken').expect(500, 'Your appearance destroyed this world.')
})
it("next function sends error message if it's not an HTTP status code or string", async () => {
const app = new App()
app.use((req, res, next) => {
if (req.url === '/broken') {
next(new Error('Your appearance destroyed this world.'))
} else {
res.send('Welcome back')
}
})
await makeFetch(app.listen())('/broken').expect(500, 'Your appearance destroyed this world.')
})
it('errors in async wares do not destroy the app', async () => {
const app = new App()
app.use(async (_req, _res) => {
throw `bruh`
})
const server = app.listen()
await makeFetch(server)('/').expect(500, 'bruh')
})
it('errors in sync wares do not destroy the app', async () => {
const app = new App()
app.use((_req, _res) => {
throw `bruh`
})
const server = app.listen()
await makeFetch(server)('/').expect(500, 'bruh')
})
})
})
describe('App methods', () => {
it('`app.set` sets a setting', () => {
const app = new App().set('subdomainOffset', 1)
expect(app.settings.subdomainOffset).toBe(1)
})
it(`app.enable enables a setting`, () => {
const app = new App({
settings: {
xPoweredBy: false
}
}).enable('xPoweredBy')
expect(app.settings.xPoweredBy).toBe(true)
})
it(`app.disable disables a setting`, async () => {
const app = new App({
settings: {
xPoweredBy: true
}
}).disable('xPoweredBy')
expect(app.settings.xPoweredBy).toBe(false)
})
it('app.route works properly', async () => {
const app = new App()
app.route('/').get((req, res) => res.end(req.url))
const server = app.listen()
await makeFetch(server)('/').expect(200)
})
it('app.route supports chaining route methods', async () => {
const app = new App()
app.route('/').get((req, res) => res.end(req.url))
const server = app.listen()
await makeFetch(server)('/').expect(200)
})
it('app.route supports chaining route methods', async () => {
const app = new App()
app
.route('/')
.get((_, res) => res.send('GET request'))
.post((_, res) => res.send('POST request'))
const server = app.listen()
await makeFetch(server)('/').expect(200, 'GET request')
await makeFetch(server)('/', { method: 'POST' }).expect(200, 'POST request')
})
})
describe('HTTP methods', () => {
it('app.get handles get request', async () => {
const app = new App()
app.get('/', (req, res) => void res.send(req.method))
await makeFetch(app.listen())('/').expect(200, 'GET')
})
it('app.post handles post request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', 'POST')
await fetch('/', {
method: 'POST'
}).expect(200, 'POST')
})
it('app.put handles put request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', 'PUT')
await fetch('/', {
method: 'PUT'
}).expect(200, 'PUT')
})
it('app.patch handles patch request', async () => {
const { fetch } = InitAppAndTest((req, res) => void res.send(req.method), '/', 'PATCH')
await fetch('/', { method: 'PATCH' }).expect(200, 'PATCH')
})
it('app.head handles head request', async () => {
const app = new App()
app.head('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'HEAD' }).expect(200, '')
})
it('app.delete handles delete request', async () => {
const app = new App()
app.delete('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'DELETE' }).expect(200, 'DELETE')
})
it('app.checkout handles checkout request', async () => {
const app = new App()
app.checkout('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'CHECKOUT' }).expect(200, 'CHECKOUT')
})
it('app.copy handles copy request', async () => {
const app = new App()
app.copy('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'COPY' }).expect(200, 'COPY')
})
it('app.lock handles lock request', async () => {
const app = new App()
app.lock('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'LOCK' }).expect(200, 'LOCK')
})
it('app.merge handles merge request', async () => {
const app = new App()
app.merge('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'MERGE' }).expect(200, 'MERGE')
})
it('app.mkactivity handles mkactivity request', async () => {
const app = new App()
app.mkactivity('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'MKACTIVITY' }).expect(200, 'MKACTIVITY')
})
it('app.mkcol handles mkcol request', async () => {
const app = new App()
app.mkcol('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'MKCOL' }).expect(200, 'MKCOL')
})
it('app.move handles move request', async () => {
const app = new App()
app.move('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'MOVE' }).expect(200, 'MOVE')
})
it('app.search handles search request', async () => {
const app = new App()
app.search('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'SEARCH' }).expect(200, 'SEARCH')
})
it('app.notify handles notify request', async () => {
const app = new App()
app.notify('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'NOTIFY' }).expect(200, 'NOTIFY')
})
it('app.purge handles purge request', async () => {
const app = new App()
app.purge('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'PURGE' }).expect(200, 'PURGE')
})
it('app.report handles report request', async () => {
const app = new App()
app.report('/', (req, res) => void res.send(req.method))
const fetch = makeFetch(app.listen())
await fetch('/', { method: 'REPORT' }).expect(200, 'REPORT')
})
it('app.subscribe handles subscribe request', async () => {
const app = new App()
app.subscribe('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'SUBSCRIBE' }).expect(200, 'SUBSCRIBE')
})
it('app.unsubscribe handles unsubscribe request', async () => {
const app = new App()
app.unsubscribe('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'UNSUBSCRIBE' }).expect(200, 'UNSUBSCRIBE')
})
it('app.trace handles trace request', async () => {
const app = new App()
app.trace('/', (req, res) => void res.send(req.method))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'TRACE' }).expect(200, 'TRACE')
})
it('HEAD request works when any of the method handlers are defined', async () => {
const app = new App()
app.get('/', (_, res) => res.send('It works'))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/', { method: 'HEAD' }).expect(200)
})
it('HEAD request does not work for undefined handlers', async () => {
const app = new App()
app.get('/', (_, res) => res.send('It works'))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/hello', { method: 'HEAD' }).expect(404)
})
})
describe('Route handlers', () => {
it('router accepts array of middlewares', async () => {
const app = new App()
app.use('/', [
(req, _, n) => {
req.body = 'hello'
n()
},
(req, _, n) => {
req.body += ' '
n()
},
(req, _, n) => {
req.body += 'world'
n()
},
(req, res) => {
res.send(req.body)
}
])
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, 'hello world')
})
it('router accepts path as array of middlewares', async () => {
const app = new App()
app.use([
(req, _, n) => {
req.body = 'hello'
n()
},
(req, _, n) => {
req.body += ' '
n()
},
(req, _, n) => {
req.body += 'world'
n()
},
(req, res) => {
res.send(req.body)
}
])
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, 'hello world')
})
it('router accepts list of middlewares', async () => {
const app = new App()
app.use(
(req, _, n) => {
req.body = 'hello'
n()
},
(req, _, n) => {
req.body += ' '
n()
},
(req, _, n) => {
req.body += 'world'
n()
},
(req, res) => {
res.send(req.body)
}
)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, 'hello world')
})
it('router accepts array of wares', async () => {
const app = new App()
app.get(
'/',
[
(req, _, n) => {
req.body = 'hello'
n()
}
],
[
(req, _, n) => {
req.body += ' '
n()
}
],
[
(req, _, n) => {
req.body += 'world'
n()
},
(req, res) => {
res.send(req.body)
}
]
)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, 'hello world')
})
it('router methods do not match loosely', async () => {
const app = new App()
app.get('/route', (_, res) => res.send('found'))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/route/subroute').expect(404)
await fetch('/route').expect(200, 'found')
})
})
describe('Subapps', () => {
it('sub-app mounts on a specific path', () => {
const app = new App()
const subApp = new App()
app.use('/subapp', subApp)
expect(subApp.mountpath).toBe('/subapp')
})
it('sub-app mounts on root', async () => {
const app = new App()
const subApp = new App()
subApp.use((_, res) => void res.send('Hello World!'))
app.use(subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200, 'Hello World!')
})
it('sub-app handles its own path', async () => {
const app = new App()
const subApp = new App()
subApp.use((_, res) => void res.send('Hello World!'))
app.use('/subapp', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/subapp').expect(200, 'Hello World!')
})
it('sub-app paths get prefixed with the mount path', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (_, res) => res.send(`Hello from ${subApp.mountpath}`))
app.use('/subapp', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/subapp/route').expect(200, 'Hello from /subapp')
})
it('sub-app gets mounted via `app.route`', async () => {
const app = new App()
app.route('/path').get((_, res) => res.send('Hello World'))
})
/* it('req.originalUrl does not change', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (req, res) =>
res.send({
origUrl: req.originalUrl,
url: req.url,
path: req.path
})
)
app.use('/subapp', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/subapp/route').expect(200, {
origUrl: '/subapp/route',
url: '/route',
path: '/route'
})
}) */
it('lets other wares handle the URL if subapp doesnt have that path', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (_, res) => res.send(subApp.mountpath))
app.use('/test', subApp)
app.use('/test3', (req, res) => res.send(req.url))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/test/route').expect(200, '/test')
await fetch('/test3/abc').expect(200, '/abc')
})
it('should mount app on a specified path', () => {
const app = new App()
const subapp = new App()
app.use('/subapp', subapp)
expect(subapp.mountpath).toBe('/subapp')
})
it('should mount on "/" if path is not specified', () => {
const app = new App()
const subapp = new App()
app.use(subapp)
expect(subapp.mountpath).toBe('/')
})
it('app.parent should reference to the app it was mounted on', () => {
const app = new App()
const subapp = new App()
app.use(subapp)
expect(subapp.parent).toBe(app)
})
it('app.path() should return the mountpath', () => {
const app = new App()
const subapp = new App()
app.use('/subapp', subapp)
expect(subapp.path()).toBe('/subapp')
})
it('app.path() should nest mountpaths', () => {
const app = new App()
const subapp = new App()
const subsubapp = new App()
subapp.use('/admin', subsubapp)
app.use('/blog', subapp)
expect(subsubapp.path()).toBe('/blog/admin')
})
it('middlewares of a subapp should preserve the path', () => {
const app = new App()
const subapp = new App()
subapp.use('/path', (_req, _res) => void 0)
app.use('/subapp', subapp)
expect(subapp.middleware[0].path).toBe('/path')
})
it('matches when mounted on params', async () => {
const app = new App()
const subApp = new App()
subApp.get('/', (req, res) => res.send(req.params.userID))
app.use('/users/:userID', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/users/123/').expect(200, '123')
})
it('matches when mounted on params and on custom subapp route', async () => {
const app = new App()
const subApp = new App()
subApp.get('/route', (req, res) => res.send(req.params.userID))
app.use('/users/:userID', subApp)
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/users/123/route').expect(200, '123')
})
})
describe('Template engines', () => {
it('works with eta out of the box', async () => {
const app = new App<EtaConfig>()
app.engine('eta', renderFile)
app.use((_, res) => {
res.render(
'index.eta',
{
name: 'Eta'
},
{
viewsFolder: `${process.cwd()}/tests/fixtures/views`
}
)
})
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expectBody('Hello from Eta')
})
it('can render without data passed', async () => {
const pwd = process.cwd()
process.chdir(path.resolve(pwd, 'tests/fixtures'))
const app = new App<EtaConfig>()
app.engine('eta', renderFile)
app.use((_, res) => {
res.render('empty.eta')
process.chdir(pwd)
})
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expectBody('Hello World')
})
})
describe('App settings', () => {
describe('xPoweredBy', () => {
it('is enabled by default', () => {
const app = new App()
expect(app.settings.xPoweredBy).toBe(true)
})
it('should set X-Powered-By to "tinyhttp"', async () => {
const { fetch } = InitAppAndTest((_req, res) => void res.send('hi'))
await fetch('/').expectHeader('X-Powered-By', 'tinyhttp')
})
it('when disabled should not send anything', async () => {
const app = new App({ settings: { xPoweredBy: false } })
app.use((_req, res) => void res.send('hi'))
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expectHeader('X-Powered-By', null)
})
})
describe('bindAppToReqRes', () => {
it('references the current app instance in req.app and res.app', async () => {
const app = new App({
settings: {
bindAppToReqRes: true
}
})
app.locals['hello'] = 'world'
app.use((req, res) => {
expect(req.app).toBeInstanceOf(App)
expect(res.app).toBeInstanceOf(App)
expect(req.app.locals['hello']).toBe('world')
expect(res.app.locals['hello']).toBe('world')
res.end()
})
const server = app.listen()
await makeFetch(server)('/').expect(200)
})
})
describe('enableReqRoute', () => {
it('attach current fn to req.route when enabled', async () => {
const app = new App({ settings: { enableReqRoute: true } })
app.use((req, res) => {
expect(req.route).toEqual(app.middleware[0])
res.end()
})
const server = app.listen()
const fetch = makeFetch(server)
await fetch('/').expect(200)
})
})
}) | the_stack |
import { Spreadsheet, DialogBeforeOpenEventArgs, ICellRenderer, completeAction } from '../index';
import { initiateHyperlink, locale, dialog, click, keyUp, createHyperlinkElement, getUpdateUsingRaf, focus } from '../common/index';
import { editHyperlink, openHyperlink, editAlert, removeHyperlink, } from '../common/index';
import { L10n, isNullOrUndefined, closest } from '@syncfusion/ej2-base';
import { Dialog } from '../services';
import { SheetModel } from '../../workbook/base/sheet-model';
import { getRangeIndexes, getCellIndexes, getRangeAddress } from '../../workbook/common/address';
import { CellModel, HyperlinkModel, BeforeHyperlinkArgs, AfterHyperlinkArgs, getTypeFromFormat, getCell } from '../../workbook/index';
import { beforeHyperlinkClick, afterHyperlinkClick, refreshRibbonIcons, deleteHyperlink, beginAction } from '../../workbook/common/event';
import { isCellReference, DefineNameModel } from '../../workbook/index';
import { Tab, TreeView } from '@syncfusion/ej2-navigations';
import { BeforeOpenEventArgs } from '@syncfusion/ej2-popups';
/**
* `Hyperlink` module
*/
export class SpreadsheetHyperlink {
private parent: Spreadsheet;
/**
* Constructor for Hyperlink module.
*
* @param {Spreadsheet} parent - Constructor for Hyperlink module.
*/
constructor(parent: Spreadsheet) {
this.parent = parent;
this.addEventListener();
}
/**
* To destroy the Hyperlink module.
*
* @returns {void} - To destroy the Hyperlink module.
*/
protected destroy(): void {
this.removeEventListener();
this.parent = null;
}
private addEventListener(): void {
this.parent.on(initiateHyperlink, this.initiateHyperlinkHandler, this);
this.parent.on(editHyperlink, this.editHyperlinkHandler, this);
this.parent.on(openHyperlink, this.openHyperlinkHandler, this);
this.parent.on(click, this.hyperlinkClickHandler, this);
this.parent.on(createHyperlinkElement, this.createHyperlinkElementHandler, this);
this.parent.on(keyUp, this.keyUpHandler, this);
this.parent.on(deleteHyperlink, this.removeHyperlink, this);
this.parent.on(removeHyperlink, this.removeHyperlinkHandler, this);
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(initiateHyperlink, this.initiateHyperlinkHandler);
this.parent.off(editHyperlink, this.editHyperlinkHandler);
this.parent.off(openHyperlink, this.openHyperlinkHandler);
this.parent.off(click, this.hyperlinkClickHandler);
this.parent.off(createHyperlinkElement, this.createHyperlinkElementHandler);
this.parent.off(keyUp, this.keyUpHandler);
this.parent.off(deleteHyperlink, this.removeHyperlink);
this.parent.off(removeHyperlink, this.removeHyperlinkHandler);
}
}
/**
* Gets the module name.
*
* @returns {string} - Gets the module name.
*/
protected getModuleName(): string {
return 'spreadsheetHyperlink';
}
private keyUpHandler(e: MouseEvent): void {
const trgt: Element = e.target as Element;
if (closest(trgt, '.e-document')) {
const hyperlinkText: HTMLInputElement = document.querySelector('.e-hyp-text') as HTMLInputElement;
const hyperlinkSpan: HTMLElement = this.parent.element.querySelector('.e-hyperlink-alert-span');
const dlgElement: Element = closest(trgt, '.e-hyperlink-dlg') || closest(trgt, '.e-edithyperlink-dlg');
const footerEle: HTMLElement = dlgElement.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const insertBut: HTMLElement = footerEle.firstChild as HTMLElement;
if (hyperlinkText && hyperlinkText.value) {
if (!isCellReference(hyperlinkText.value.toUpperCase())) {
this.showDialog();
insertBut.setAttribute('disabled', 'true');
} else if (hyperlinkSpan) {
hyperlinkSpan.remove();
insertBut.removeAttribute('disabled');
}
}
}
if (trgt.classList.contains('e-text') && closest(trgt, '.e-cont')) {
if (closest(trgt, '.e-webpage') && closest(trgt, '.e-webpage').getElementsByClassName('e-cont')[1] === trgt.parentElement) {
const dlgEle: Element = closest(trgt, '.e-hyperlink-dlg') || closest(trgt, '.e-edithyperlink-dlg');
const ftrEle: HTMLElement = dlgEle.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const insertBut: HTMLElement = ftrEle.firstChild as HTMLElement;
if ((trgt as CellModel).value !== '') {
insertBut.removeAttribute('disabled');
} else {
const linkDialog: Element = closest(trgt, '.e-link-dialog');
const webPage: Element = linkDialog.querySelector('.e-webpage');
const isUrl: boolean =
(webPage.querySelectorAll('.e-cont')[1].querySelector('.e-text') as CellModel).value ? true : false;
if (!isUrl) {
insertBut.setAttribute('disabled', 'true');
}
}
}
}
}
private initiateHyperlinkHandler(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const sheet: SheetModel = this.parent.getActiveSheet();
if (sheet.isProtected && !sheet.protectSettings.insertLink) {
this.parent.notify(editAlert, null);
return;
}
if (!this.parent.element.querySelector('.e-hyperlink-dlg')) {
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-hyperlink-dlg',
header: l10n.getConstant('InsertLink'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'InsertLinkDialog',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.hyperlinkContent(); dialogInst.dialogInstance.dataBind();
focus(this.parent.element);
},
open: (): void => {
setTimeout(() => {
focus(dialogInst.dialogInstance.element.querySelectorAll('.e-webpage input')[1] as HTMLElement);
});
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Insert'), isPrimary: true, disabled: true
},
click: (): void => {
this.dlgClickHandler();
dialogInst.hide();
}
}]
});
}
}
private dlgClickHandler(): void {
let value: string;
let address: string;
let sheet: SheetModel = this.parent.getActiveSheet();
let cellAddress: string = sheet.name + '!' + sheet.activeCell;
const item: HTMLElement = this.parent.element.querySelector('.e-link-dialog').
getElementsByClassName('e-content')[0].querySelector('.e-item.e-active') as HTMLElement;
if (item) {
if (item.querySelector('.e-webpage')) {
value = (item.getElementsByClassName('e-cont')[0].querySelector('.e-text') as CellModel).value;
address = (item.getElementsByClassName('e-cont')[1].querySelector('.e-text') as CellModel).value;
const args: HyperlinkModel = { address: address };
this.parent.insertHyperlink(args, cellAddress, value, false);
} else {
value = (item.getElementsByClassName('e-cont')[0].querySelector('.e-text') as CellModel).value;
address = (item.getElementsByClassName('e-cont')[1].querySelector('.e-text') as CellModel).value;
const dlgContent: HTMLElement = item.getElementsByClassName('e-cont')[2] as HTMLElement;
if (dlgContent.getElementsByClassName('e-list-item')[0].querySelector('.e-active')) {
const sheetName: string = item.getElementsByClassName('e-cont')[2].querySelector('.e-active').textContent;
// const sheets: SheetModel[] = spreadsheetInst.sheets;
// for (let idx: number = 0; idx < sheets.length; idx++) {
// if (sheets[idx].name === sheetName) {
// const sheetIdx: number = idx + 1;
// }
// }
address = sheetName + '!' + address.toUpperCase();
const args: HyperlinkModel = { address: address };
this.parent.insertHyperlink(args, cellAddress, value, false);
} else if (dlgContent.querySelector('.e-active')) {
const definedName: string = item.getElementsByClassName('e-cont')[2].querySelector('.e-active').textContent;
for (let idx: number = 0; idx < this.parent.definedNames.length; idx++) {
if (this.parent.definedNames[idx].name === definedName) {
const args: HyperlinkModel = {
address: this.parent.definedNames[idx].name
};
this.parent.insertHyperlink(
args, cellAddress, value, false);
}
}
}
}
}
}
private showDialog(): void {
if (this.parent.element.querySelector('.e-hyperlink-alert-span')) {
this.parent.element.querySelector('.e-hyperlink-alert-span').remove();
}
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const hyperlinkSpan: Element = this.parent.createElement('span', {
className: 'e-hyperlink-alert-span',
innerHTML: l10n.getConstant('HyperlinkAlert')
});
const dlgEle: HTMLElement =
this.parent.element.querySelector('.e-hyperlink-dlg') || this.parent.element.querySelector('.e-edithyperlink-dlg');
(dlgEle.querySelector('.e-dlg-content')).appendChild(hyperlinkSpan);
}
private editHyperlinkHandler(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true, cssClass: 'e-edithyperlink-dlg',
header: l10n.getConstant('EditLink'),
beforeOpen: (args: BeforeOpenEventArgs): void => {
const dlgArgs: DialogBeforeOpenEventArgs = {
dialogName: 'EditLinkDialog',
element: args.element, target: args.target, cancel: args.cancel
};
this.parent.trigger('dialogBeforeOpen', dlgArgs);
if (dlgArgs.cancel) {
args.cancel = true;
}
dialogInst.dialogInstance.content = this.hyperEditContent(); dialogInst.dialogInstance.dataBind();
focus(this.parent.element);
},
open: (): void => {
setTimeout(() => {
if (dialogInst.dialogInstance.element.querySelector('.e-webpage')) {
focus(dialogInst.dialogInstance.element.querySelectorAll('.e-webpage input')[1] as HTMLElement);
} else {
focus(dialogInst.dialogInstance.element.querySelectorAll('.e-document input')[1] as HTMLElement);
}
});
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Update'), isPrimary: true
},
click: (): void => {
this.dlgClickHandler();
dialogInst.hide();
}
}]
});
}
private openHyperlinkHandler(): void {
const cellIndexes: number[] = getCellIndexes(this.parent.getActiveSheet().activeCell);
let trgt: HTMLElement = this.parent.getCell(cellIndexes[0], cellIndexes[1]);
if (trgt.getElementsByClassName('e-hyperlink')[0]) {
trgt = trgt.querySelector('.e-hyperlink') as HTMLElement;
}
this.hlOpenHandler(trgt);
}
private hlOpenHandler(trgt: HTMLElement): void {
if (trgt.classList.contains('e-hyperlink')) {
let range: string[] = ['', ''];
// let selRange: string;
let rangeIndexes: number[];
let isEmpty: boolean = true;
trgt.style.color = '#551A8B';
if (closest(trgt, '.e-cell')) {
(closest(trgt, '.e-cell') as HTMLElement).style.color = '#551A8B';
}
let sheet: SheetModel = this.parent.getActiveSheet();
const colIdx: number = parseInt(trgt.parentElement.getAttribute('aria-colindex'), 10) - 1;
const rowIdx: number = parseInt(trgt.parentElement.parentElement.getAttribute('aria-rowindex'), 10) - 1;
let rangeAddr: string | HyperlinkModel = sheet.rows[rowIdx].cells[colIdx].hyperlink;
let address: string;
const befArgs: BeforeHyperlinkArgs = { hyperlink: rangeAddr, address: sheet.activeCell, target: '_blank', cancel: false };
this.parent.trigger(beforeHyperlinkClick, befArgs);
if (befArgs.cancel) { return; }
rangeAddr = befArgs.hyperlink;
const aftArgs: AfterHyperlinkArgs = { hyperlink: rangeAddr, address: sheet.activeCell };
if (typeof (rangeAddr) === 'string') { address = rangeAddr; }
if (typeof (rangeAddr) === 'object') { address = rangeAddr.address; }
const definedNameCheck: string = address;
if (address.indexOf('http://') === -1 && address.indexOf('https://') === -1 && address.indexOf('ftp://') === -1) {
if (!isNullOrUndefined(address)) {
if (this.parent.definedNames) {
for (let idx: number = 0; idx < this.parent.definedNames.length; idx++) {
if (this.parent.definedNames[idx].name === address) {
address = this.parent.definedNames[idx].refersTo;
address = address.slice(1);
break;
}
}
}
if (address.indexOf('!') !== -1) {
range = address.split('!');
if (range[0].indexOf(' ') !== -1) {
range[0] = range[0].slice(1, range[0].length - 1);
}
} else {
range[0] = this.parent.getActiveSheet().name;
range[1] = address;
}
// selRange = range[1];
let sheetIdx: number;
for (let idx: number = 0; idx < this.parent.sheets.length; idx++) {
if (this.parent.sheets[idx].name === range[0]) {
sheetIdx = idx;
}
}
sheet = this.parent.sheets[sheetIdx];
if (range[1].indexOf(':') !== -1) {
const colIndex: number = range[1].indexOf(':');
let left: string = range[1].substr(0, colIndex);
let right: string = range[1].substr(colIndex + 1, range[1].length);
left = left.replace('$', '');
right = right.replace('$', '');
if (right.match(/\D/g) && !right.match(/[0-9]/g) && left.match(/\D/g) && !left.match(/[0-9]/g)) {
// selRange = left + '1' + ':' + right + sheet.rowCount;
left = left + '1';
right = right + sheet.rowCount;
range[1] = left + ':' + right;
} else if (!right.match(/\D/g) && right.match(/[0-9]/g) && !left.match(/\D/g) && left.match(/[0-9]/g)) {
// selRange = getCellAddress(parseInt(left, 10) - 1, 0) + ':' +
// getCellAddress(parseInt(right, 10) - 1, sheet.colCount - 1);
rangeIndexes = [parseInt(left, 10) - 1, 0, parseInt(right, 10) - 1, sheet.colCount - 1];
isEmpty = false;
}
}
let isDefinedNamed: boolean;
const definedname: DefineNameModel[] = this.parent.definedNames;
if (!isNullOrUndefined(definedname)) {
for (let idx: number = 0; idx < definedname.length; idx++) {
if (definedname[idx].name === definedNameCheck) {
isDefinedNamed = true;
break;
}
}
}
if (isCellReference(range[1]) || isDefinedNamed) {
rangeIndexes = isEmpty ? getRangeIndexes(range[1]) : rangeIndexes;
if (this.parent.scrollSettings.enableVirtualization) {
rangeIndexes[0] = rangeIndexes[0] >= this.parent.viewport.topIndex ?
rangeIndexes[0] - this.parent.viewport.topIndex : rangeIndexes[0];
rangeIndexes[1] = rangeIndexes[1] >= this.parent.viewport.leftIndex ?
rangeIndexes[1] - this.parent.viewport.leftIndex : rangeIndexes[1];
}
if (!isNullOrUndefined(sheet)) {
let rangeAddr: string = getRangeAddress(rangeIndexes);
if (sheet === this.parent.getActiveSheet()) {
getUpdateUsingRaf((): void => { this.parent.goTo(rangeAddr); });
} else {
if (rangeAddr.indexOf(':') >= 0) {
const addArr: string[] = rangeAddr.split(':');
rangeAddr = addArr[0] === addArr[1] ? addArr[0] : rangeAddr;
}
getUpdateUsingRaf((): void => { this.parent.goTo(this.parent.sheets[sheetIdx].name + '!' + rangeAddr); });
}
}
} else {
this.showInvalidHyperlinkDialog();
}
}
} else {
if (this.isValidUrl(address)) {
window.open(address, befArgs.target);
} else {
this.showInvalidHyperlinkDialog();
}
}
this.parent.trigger(afterHyperlinkClick, aftArgs);
}
}
private isValidUrl(url: string): boolean {
// eslint-disable-next-line no-useless-escape
return /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url);
}
private showInvalidHyperlinkDialog(): void {
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
const l10n: L10n = this.parent.serviceLocator.getService(locale);
dialogInst.show({
width: 323, isModal: true, showCloseIcon: true,
header: l10n.getConstant('Hyperlink'),
content: l10n.getConstant('InvalidHyperlinkAlert'),
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'), isPrimary: true
},
click: (): void => {
dialogInst.hide();
}
}]
}, false);
}
private hyperlinkClickHandler(e: MouseEvent): void {
const trgt: HTMLElement = e.target as HTMLElement;
if (closest(trgt, '.e-link-dialog') && closest(trgt, '.e-toolbar-item')) {
const dlgEle: Element = closest(trgt, '.e-hyperlink-dlg') || closest(trgt, '.e-edithyperlink-dlg');
const ftrEle: HTMLElement = dlgEle.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const insertBut: HTMLElement = ftrEle.firstChild as HTMLElement;
const docEle: Element = dlgEle.querySelector('.e-document');
const webEle: Element = dlgEle.querySelector('.e-webpage');
const webEleText: string = webEle ? (webEle.querySelectorAll('.e-cont')[0].querySelector('.e-text') as CellModel).value :
(docEle.querySelectorAll('.e-cont')[0].querySelector('.e-text') as CellModel).value;
const docEleText: string = docEle ? (docEle.querySelectorAll('.e-cont')[0].querySelector('.e-text') as CellModel).value :
webEleText;
const toolbarItems: Element = closest(trgt, '.e-toolbar-items');
if (toolbarItems.getElementsByClassName('e-toolbar-item')[1].classList.contains('e-active')) {
const actEle: Element = docEle.querySelectorAll('.e-cont')[2].querySelector('.e-active');
(docEle.querySelectorAll('.e-cont')[0].querySelector('.e-text') as CellModel).value = webEleText;
if (closest(actEle, '.e-list-item').classList.contains('e-level-2') && insertBut.hasAttribute('disabled')) {
insertBut.removeAttribute('disabled');
} else if (closest(actEle, '.e-list-item').classList.contains('e-level-1') && !insertBut.hasAttribute('disabled')) {
insertBut.setAttribute('disabled', 'true');
}
} else {
const isEmpty: boolean = (webEle.querySelectorAll('.e-cont')[1].querySelector('.e-text') as CellModel).value ? false : true;
(webEle.querySelectorAll('.e-cont')[0].querySelector('.e-text') as CellModel).value = docEleText;
if (isEmpty && !insertBut.hasAttribute('disabled')) {
insertBut.setAttribute('disabled', 'true');
} else if (!isEmpty && insertBut.hasAttribute('disabled')) {
insertBut.removeAttribute('disabled');
}
}
}
if (closest(trgt, '.e-list-item') && trgt.classList.contains('e-fullrow')) {
let item: HTMLElement = this.parent.element.getElementsByClassName('e-link-dialog')[0] as HTMLElement;
if (item) {
item = item.getElementsByClassName('e-content')[0].getElementsByClassName('e-active')[0] as HTMLElement;
} else {
return;
}
const cellRef: HTMLElement = item.getElementsByClassName('e-cont')[1].getElementsByClassName('e-text')[0] as HTMLElement;
const dlgEle: Element = closest(trgt, '.e-hyperlink-dlg') || closest(trgt, '.e-edithyperlink-dlg');
const ftrEle: HTMLElement = dlgEle.getElementsByClassName('e-footer-content')[0] as HTMLElement;
const insertBut: HTMLElement = ftrEle.firstChild as HTMLElement;
if (closest(trgt, '.e-list-item').classList.contains('e-level-2')) {
if (closest(trgt, '.e-list-item').getAttribute('data-uid') === 'defName') {
if (!cellRef.classList.contains('e-disabled') && !cellRef.hasAttribute('readonly')) {
cellRef.setAttribute('readonly', 'true');
cellRef.classList.add('e-disabled');
cellRef.setAttribute('disabled', 'true');
}
} else if (closest(trgt, '.e-list-item').getAttribute('data-uid') === 'sheet') {
if (cellRef.classList.contains('e-disabled') && cellRef.hasAttribute('readonly')) {
cellRef.removeAttribute('readonly');
cellRef.classList.remove('e-disabled');
cellRef.removeAttribute('disabled');
}
}
if (insertBut.hasAttribute('disabled')) {
insertBut.removeAttribute('disabled');
}
} else if (closest(trgt, '.e-list-item').classList.contains('e-level-1')) {
insertBut.setAttribute('disabled', 'true');
}
} else {
this.hlOpenHandler(trgt);
}
}
private createHyperlinkElementHandler(args: { cell: CellModel, td: HTMLElement, rowIdx: number, colIdx: number }): void {
const cell: CellModel = args.cell;
const td: HTMLElement = args.td;
const hyperEle: HTMLElement = this.parent.createElement('a', { className: 'e-hyperlink e-hyperlink-style' });
hyperEle.style.color = '#00e';
if (!isNullOrUndefined(cell.hyperlink)) {
let hyperlink: string | HyperlinkModel = cell.hyperlink;
if (typeof (hyperlink) === 'string') {
if (hyperlink.indexOf('http://') === -1 && hyperlink.indexOf('https://') === -1 &&
hyperlink.indexOf('ftp://') === -1 && hyperlink.indexOf('www.') !== -1) {
hyperlink = 'http://' + hyperlink;
}
if (hyperlink.indexOf('http://') === 0 || hyperlink.indexOf('https://') === 0 || hyperlink.indexOf('ftp://') === 0) {
hyperEle.setAttribute('href', hyperlink as string);
hyperEle.setAttribute('target', '_blank');
} else if (hyperlink.includes('=') || hyperlink.includes('!')) {
hyperEle.setAttribute('ref', hyperlink as string);
}
hyperEle.innerText = td.innerText !== '' ? td.innerText : hyperlink as string;
td.textContent = '';
td.innerText = '';
td.appendChild(hyperEle);
} else if (typeof (hyperlink) === 'object') {
if (hyperlink.address.indexOf('http://') === 0 || hyperlink.address.indexOf('https://') === 0 ||
hyperlink.address.indexOf('ftp://') === 0) {
hyperEle.setAttribute('href', hyperlink.address as string);
hyperEle.setAttribute('target', '_blank');
} else if (hyperlink.address.includes('=') || hyperlink.address.includes('!')) {
hyperEle.setAttribute('ref', hyperlink.address as string);
}
if (getTypeFromFormat(cell.format) === 'Accounting') {
hyperEle.innerHTML = td.innerHTML;
} else {
hyperEle.innerText = td.innerText !== '' ? td.innerText : hyperlink.address as string;
}
td.textContent = '';
td.innerText = '';
td.appendChild(hyperEle);
}
} else if (td.querySelector('a') && cell.hyperlink) {
if (typeof (cell.hyperlink) === 'string') {
td.querySelector('a').setAttribute('href', cell.hyperlink);
}
}
}
private hyperEditContent(): HTMLElement {
let isWeb: boolean = true;
const dialog: HTMLElement = this.hyperlinkContent();
const indexes: number[] = getRangeIndexes(this.parent.getActiveSheet().activeCell);
const cell: CellModel = this.parent.sheets[this.parent.getActiveSheet().id - 1].rows[indexes[0]].cells[indexes[1]];
if (this.parent.scrollSettings.enableVirtualization) {
indexes[0] = indexes[0] - this.parent.viewport.topIndex;
indexes[1] = indexes[1] - this.parent.viewport.leftIndex;
}
let value: string = this.parent.getDisplayText(cell);
let address: string;
const hyperlink: string | HyperlinkModel = cell.hyperlink;
if (typeof (hyperlink) === 'string') {
address = hyperlink;
value = value || address;
if (address.indexOf('http://') === -1 && address.indexOf('https://') === -1 && address.indexOf('ftp://') === -1) {
isWeb = false;
}
} else if (typeof (hyperlink) === 'object') {
address = hyperlink.address;
value = value || address;
if (address.indexOf('http://') === -1 && address.indexOf('https://') === -1 && address.indexOf('ftp://') === -1) {
isWeb = false;
}
}
let definedNamesCount: number = 0;
let rangeCount: number = 0;
const definedNames: DefineNameModel[] = this.parent.definedNames;
const sheets: SheetModel[] = this.parent.sheets;
for (let idx: number = 0, len: number = definedNames.length; idx < len; idx++) {
if (definedNames[idx].name === address) {
definedNamesCount++;
}
}
for (let idx: number = 0, len: number = sheets.length; idx < len; idx++) {
if (address.includes(sheets[idx].name)) {
rangeCount++;
}
}
if (definedNamesCount === 0 && rangeCount === 0) {
isWeb = true;
}
const item: HTMLElement = dialog.querySelector('.e-content') as HTMLElement;
if (isWeb) {
const webContElem: HTMLElement = item.querySelector('.e-webpage') as HTMLElement;
webContElem.getElementsByClassName('e-cont')[0].getElementsByClassName('e-text')[0].setAttribute('value', value);
if (typeof (hyperlink) === 'string') {
webContElem.getElementsByClassName('e-cont')[1].querySelector('.e-text').setAttribute('value', hyperlink);
} else {
const address: HTMLElement = webContElem.getElementsByClassName('e-cont')[1].querySelector('.e-text') as HTMLElement;
address.setAttribute('value', hyperlink.address);
}
} else {
let isDefinedNamed: boolean;
const docContElem: HTMLElement = item.querySelector('.e-document') as HTMLElement;
docContElem.getElementsByClassName('e-cont')[0].getElementsByClassName('e-text')[0].setAttribute('value', value);
let rangeArr: string[];
// let sheet: SheetModel = this.parent.getActiveSheet();
// let sheetIdx: number;
if (this.parent.definedNames) {
for (let idx: number = 0; idx < this.parent.definedNames.length; idx++) {
if (this.parent.definedNames[idx].name === address) {
isDefinedNamed = true;
break;
}
}
}
if (isDefinedNamed) {
const cellRef: HTMLElement = docContElem.getElementsByClassName('e-cont')[1].getElementsByClassName('e-text')[0] as HTMLElement;
cellRef.setAttribute('readonly', 'true');
cellRef.classList.add('e-disabled');
cellRef.setAttribute('disabled', 'true');
const treeCont: HTMLElement = docContElem.getElementsByClassName('e-cont')[2] as HTMLElement;
const listEle: HTMLElement = treeCont.querySelectorAll('.e-list-item.e-level-1')[1] as HTMLElement;
for (let idx: number = 0; idx < listEle.getElementsByTagName('li').length; idx++) {
if ((listEle.getElementsByTagName('li')[idx] as HTMLElement).innerText === address) {
listEle.getElementsByTagName('li')[idx].classList.add('e-active');
}
}
} else {
if (address && address.indexOf('!') !== -1) {
rangeArr = address.split('!');
// sheetIdx = parseInt(rangeArr[0].replace(/\D/g, ''), 10) - 1;
// sheet = this.parent.sheets[sheetIdx];
}
const sheetName: string = rangeArr[0];
docContElem.getElementsByClassName('e-cont')[1].querySelector('.e-text').setAttribute('value', rangeArr[1]);
const treeCont: HTMLElement = docContElem.getElementsByClassName('e-cont')[2] as HTMLElement;
const listEle: HTMLElement = treeCont.querySelectorAll('.e-list-item.e-level-1')[0] as HTMLElement;
for (let idx: number = 0; idx < listEle.getElementsByTagName('li').length; idx++) {
if ((listEle.getElementsByTagName('li')[idx] as HTMLElement).innerText === sheetName) {
if (listEle.getElementsByTagName('li')[idx].classList.contains('e-active')) {
break;
} else {
listEle.getElementsByTagName('li')[idx].classList.add('e-active');
}
} else {
if (listEle.getElementsByTagName('li')[idx].classList.contains('e-active')) {
listEle.getElementsByTagName('li')[idx].classList.remove('e-active');
}
}
}
}
}
return dialog;
}
private hyperlinkContent(): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
let idx: number = 0; let selIdx: number = 0;
let isWeb: boolean = true;
let isDefinedName: boolean;
let isCellRef: boolean = true;
let address: string;
const indexes: number[] = getRangeIndexes(this.parent.getActiveSheet().activeCell);
const sheet: SheetModel = this.parent.getActiveSheet();
const cell: CellModel = getCell(indexes[0], indexes[1], sheet);
let isEnable: boolean = true;
if (cell) {
if ((cell.value && typeof (cell.value) === 'string' && cell.value.match('[A-Za-z]+') !== null) ||
cell.value === '' || isNullOrUndefined(cell.value)) {
isEnable = true;
} else {
isEnable = false;
}
const hyperlink: string | HyperlinkModel = cell.hyperlink;
if (typeof (hyperlink) === 'string') {
const hl: string = hyperlink;
if (hl.indexOf('http://') === -1 && hl.indexOf('https://') === -1 && hl.indexOf('ftp://') === -1) {
address = hyperlink;
isWeb = false;
}
} else if (typeof (hyperlink) === 'object') {
const hl: string = hyperlink.address;
if (hl.indexOf('http://') === -1 && hl.indexOf('https://') === -1 && hl.indexOf('ftp://') === -1) {
address = hyperlink.address;
isWeb = false;
}
}
if (address) {
let defNamesCnt: number = 0;
let rangeCnt: number = 0;
const definedNames: DefineNameModel[] = this.parent.definedNames;
const sheets: SheetModel[] = this.parent.sheets;
for (let idx: number = 0, len: number = sheets.length; idx < len; idx++) {
if (address.includes(sheets[idx].name)) {
rangeCnt++;
}
}
for (let idx: number = 0, len: number = definedNames.length; idx < len; idx++) {
if (definedNames[idx].name === address) {
defNamesCnt++;
}
}
if (defNamesCnt === 0 && rangeCnt === 0) {
isWeb = true;
}
}
if (isWeb) {
selIdx = 0;
} else {
selIdx = 1;
}
if (this.parent.definedNames) {
for (let idx: number = 0; idx < this.parent.definedNames.length; idx++) {
if (this.parent.definedNames[idx].name === address) {
isDefinedName = true;
isCellRef = false;
break;
}
}
}
}
const dialogElem: HTMLElement = this.parent.createElement('div', { className: 'e-link-dialog' });
const webContElem: HTMLElement = this.parent.createElement('div', { className: 'e-webpage' });
const docContElem: HTMLElement = this.parent.createElement('div', { className: 'e-document' });
const headerTabs: Tab = new Tab({
selectedItem: selIdx,
items: [
{
header: { 'text': l10n.getConstant('WebPage') },
content: webContElem
},
{
header: { 'text': l10n.getConstant('ThisDocument') },
content: docContElem
}
]
});
headerTabs.appendTo(dialogElem);
if (isWeb) {
dialogElem.querySelector('.e-toolbar-items').querySelector('.e-indicator').setAttribute('style', 'left: 0; right: 136px');
} else {
dialogElem.querySelector('.e-toolbar-items').querySelector('.e-indicator').setAttribute('style', 'left: 136px; right: 0');
}
const textCont: HTMLElement = this.parent.createElement('div', { className: 'e-cont' });
const urlCont: HTMLElement = this.parent.createElement('div', { className: 'e-cont' });
const textH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('DisplayText') });
const urlH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('Url') });
const textInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'Text' } });
if (!isEnable) {
textInput.classList.add('e-disabled');
textInput.setAttribute('readonly', 'true');
textInput.setAttribute('disabled', 'true');
}
if (cell && isNullOrUndefined(cell.hyperlink)) {
textInput.setAttribute('value', this.parent.getDisplayText(cell));
}
const urlInput: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'Text' } });
textInput.setAttribute('placeholder', l10n.getConstant('EnterTheTextToDisplay'));
urlInput.setAttribute('placeholder', l10n.getConstant('EnterTheUrl'));
textCont.appendChild(textInput);
textCont.insertBefore(textH, textInput);
urlCont.appendChild(urlInput);
urlCont.insertBefore(urlH, urlInput);
webContElem.appendChild(urlCont);
webContElem.insertBefore(textCont, urlCont);
const cellRef: Object[] = [];
const definedName: object[] = [];
const sheets: SheetModel[] = this.parent.sheets;
for (idx; idx < this.parent.sheets.length; idx++) {
const sheetName: string = this.parent.sheets[idx].name;
if (this.parent.sheets[idx].state === 'Visible') {
if (sheets[idx] === this.parent.getActiveSheet()) {
cellRef.push({
nodeId: 'sheet',
nodeText: sheetName.indexOf(' ') !== -1 ? '\'' + sheetName + '\'' : sheetName,
selected: true
});
} else {
cellRef.push({
nodeId: 'sheet',
nodeText: sheetName.indexOf(' ') !== -1 ? '\'' + sheetName + '\'' : sheetName
});
}
}
}
for (idx = 0; idx < this.parent.definedNames.length; idx++) {
definedName.push({
nodeId: 'defName',
nodeText: this.parent.definedNames[idx].name
});
}
const data: { [key: string]: Object }[] = [
{
nodeId: '01', nodeText: l10n.getConstant('CellReference'), expanded: isCellRef,
nodeChild: cellRef
},
{
nodeId: '02', nodeText: l10n.getConstant('DefinedNames'), expanded: isDefinedName,
nodeChild: definedName
}
];
const treeObj: TreeView = new TreeView({
fields: { dataSource: data, id: 'nodeId', text: 'nodeText', child: 'nodeChild' }
});
const cellrefCont: HTMLElement = this.parent.createElement('div', { className: 'e-cont' });
const cellrefH: HTMLElement = this.parent.createElement(
'div', { className: 'e-header', innerHTML: l10n.getConstant('CellReference') });
const cellrefInput: HTMLElement = this.parent.createElement('input', {
className: 'e-input e-text e-hyp-text',
attrs: { 'type': 'Text' }
});
cellrefInput.setAttribute('value', 'A1');
cellrefCont.appendChild(cellrefInput);
cellrefCont.insertBefore(cellrefH, cellrefInput);
const textCont1: HTMLElement = this.parent.createElement('div', { className: 'e-cont' });
const textH1: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('DisplayText') });
const textInput1: HTMLElement = this.parent.createElement('input', { className: 'e-input e-text', attrs: { 'type': 'Text' } });
if (!isEnable) {
textInput1.classList.add('e-disabled');
textInput1.setAttribute('readonly', 'true');
textInput1.setAttribute('disabled', 'true');
}
if (cell && isNullOrUndefined(cell.hyperlink)) {
textInput1.setAttribute('value', this.parent.getDisplayText(cell));
}
textInput1.setAttribute('placeholder', l10n.getConstant('EnterTheTextToDisplay'));
textCont1.appendChild(textInput1);
textCont1.insertBefore(textH1, textInput1);
const sheetCont: HTMLElement = this.parent.createElement('div', { className: 'e-cont' });
const sheetH: HTMLElement = this.parent.createElement('div', { className: 'e-header', innerHTML: l10n.getConstant('Sheet') });
const refCont: HTMLElement = this.parent.createElement('div', { className: 'e-refcont' });
sheetCont.appendChild(refCont);
sheetCont.insertBefore(sheetH, refCont);
docContElem.appendChild(cellrefCont);
docContElem.insertBefore(textCont1, cellrefCont);
treeObj.appendTo(refCont);
docContElem.appendChild(sheetCont);
return dialogElem;
}
private removeHyperlink(args: { sheet: SheetModel, rowIdx: number, colIdx: number, preventRefresh?: boolean }): void {
const cell: CellModel = getCell(args.rowIdx, args.colIdx, args.sheet);
if (cell && cell.hyperlink) {
if (typeof (cell.hyperlink) === 'string') {
cell.value = cell.value ? cell.value : cell.hyperlink;
} else {
cell.value = cell.value ? cell.value : cell.hyperlink.address;
}
delete (cell.hyperlink);
if (cell.style) { delete cell.style.textDecoration; delete cell.style.color; }
if (cell.validation){
if (cell.validation.isHighlighted){
if (cell.style.backgroundColor){
cell.style.color = '#ff0000';
}
}
}
if (args.sheet === this.parent.getActiveSheet()) {
if (cell.style) { this.parent.notify(refreshRibbonIcons, null); }
if (!args.preventRefresh) {
this.parent.serviceLocator.getService<ICellRenderer>('cell').refreshRange(
[args.rowIdx, args.colIdx, args.rowIdx, args.colIdx]);
}
}
}
}
private removeHyperlinkHandler(args: { range: string, preventEventTrigger?: boolean }): void {
let range: string = args.range;
let rangeArr: string[];
let sheet: SheetModel = this.parent.getActiveSheet();
let sheetIdx: number;
if (!args.preventEventTrigger) {
const eventArgs: { address: string, cancel: boolean } = { address: range.indexOf('!') === -1 ? sheet.name + '!' + range : range, cancel: false };
this.parent.notify(beginAction, { action: 'removeHyperlink', eventArgs: eventArgs });
if (eventArgs.cancel) {
return;
}
}
if (range && range.indexOf('!') !== -1) {
rangeArr = range.split('!');
const sheets: SheetModel[] = this.parent.sheets;
for (let idx: number = 0; idx < sheets.length; idx++) {
if (sheets[idx].name === rangeArr[0]) {
sheetIdx = idx;
}
}
sheet = this.parent.sheets[sheetIdx];
range = rangeArr[1];
}
const rangeIndexes: number[] = range ? getRangeIndexes(range) : getRangeIndexes(sheet.activeCell);
for (let rowIdx: number = rangeIndexes[0]; rowIdx <= rangeIndexes[2]; rowIdx++) {
for (let colIdx: number = rangeIndexes[1]; colIdx <= rangeIndexes[3]; colIdx++) {
if (sheet && sheet.rows[rowIdx] && sheet.rows[rowIdx].cells[colIdx]) {
const prevELem: HTMLElement = this.parent.getCell(rowIdx, colIdx);
const classList: string[] = [];
for (let i: number = 0; i < prevELem.classList.length; i++) {
classList.push(prevELem.classList[i]);
}
this.parent.notify(deleteHyperlink, { sheet: sheet, rowIdx: rowIdx, colIdx: colIdx });
for (let i: number = 0; i < classList.length; i++) {
if (!this.parent.getCell(rowIdx, colIdx).classList.contains(classList[i])) {
this.parent.getCell(rowIdx, colIdx).classList.add(classList[i]);
}
}
}
}
}
if (!args.preventEventTrigger) {
this.parent.notify(completeAction, { action: 'removeHyperlink', eventArgs: { address: range.indexOf('!') === -1 ? sheet.name + '!' + range : range } });
}
}
} | the_stack |
import { each, indexOf, curry, assert, map, createHashMap } from 'zrender/src/core/util';
import * as graphic from '../../util/graphic';
import * as brushHelper from './brushHelper';
import {
BrushPanelConfig, BrushControllerEvents, BrushType,
BrushAreaRange, BrushDimensionMinMax
} from './BrushController';
import ExtensionAPI from '../../core/ExtensionAPI';
import GridModel from '../../coord/cartesian/GridModel';
import GeoModel from '../../coord/geo/GeoModel';
import { CoordinateSystemMaster } from '../../coord/CoordinateSystem';
import Cartesian2D from '../../coord/cartesian/Cartesian2D';
import Geo from '../../coord/geo/Geo';
import GlobalModel from '../../model/Global';
import { BrushAreaParam, BrushAreaParamInternal } from '../brush/BrushModel';
import SeriesModel from '../../model/Series';
import { Dictionary } from '../../util/types';
import {
ModelFinderObject, ModelFinder,
parseFinder as modelUtilParseFinder,
ParsedModelFinderKnown
} from '../../util/model';
type COORD_CONVERTS_INDEX = 0 | 1;
// FIXME
// how to genarialize to more coordinate systems.
const INCLUDE_FINDER_MAIN_TYPES = [
'grid', 'xAxis', 'yAxis', 'geo', 'graph',
'polar', 'radiusAxis', 'angleAxis', 'bmap'
];
type BrushableCoordinateSystem = Cartesian2D | Geo;
type BrushTargetBuilderKey = 'grid' | 'geo';
/**
* There can be multiple axes in a single targetInfo. Consider the case
* of `grid` component, a targetInfo represents a grid which contains one or more
* cartesian and one or more axes. And consider the case of parallel system,
* which has multiple axes in a coordinate system.
*/
interface BrushTargetInfo {
panelId: string;
coordSysModel: CoordinateSystemMaster['model'];
// Use the first one as the representitive coordSys.
// A representitive cartesian in grid (first cartesian by default).
coordSys: BrushableCoordinateSystem;
// All cartesians.
coordSyses: BrushableCoordinateSystem[];
getPanelRect: GetPanelRect,
}
export interface BrushTargetInfoCartesian2D extends BrushTargetInfo {
gridModel: GridModel;
coordSys: Cartesian2D;
coordSyses: Cartesian2D[];
xAxisDeclared: boolean;
yAxisDeclared: boolean;
}
export interface BrushTargetInfoGeo extends BrushTargetInfo {
geoModel: GeoModel,
coordSysModel: GeoModel,
coordSys: Geo,
coordSyses: Geo[],
}
type GetPanelRect = () => graphic.BoundingRect;
class BrushTargetManager {
private _targetInfoList: BrushTargetInfo[] = [];
/**
* @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
* Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
* @param opt.include include coordinate system types.
*/
constructor(
finder: ModelFinderObject,
ecModel: GlobalModel,
opt?: {include?: BrushTargetBuilderKey[]}
) {
const foundCpts = parseFinder(ecModel, finder);
each(targetInfoBuilders, (builder, type) => {
if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
builder(foundCpts, this._targetInfoList);
}
});
}
setOutputRanges(
areas: BrushControllerEvents['brush']['areas'],
ecModel: GlobalModel
): BrushAreaParam[] {
this.matchOutputRanges(areas, ecModel, function (
area: BrushAreaParam,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem
) {
(area.coordRanges || (area.coordRanges = [])).push(coordRange);
// area.coordRange is the first of area.coordRanges
if (!area.coordRange) {
area.coordRange = coordRange;
// In 'category' axis, coord to pixel is not reversible, so we can not
// rebuild range by coordRange accrately, which may bring trouble when
// brushing only one item. So we use __rangeOffset to rebuilding range
// by coordRange. And this it only used in brush component so it is no
// need to be adapted to coordRanges.
const result = coordConvert[area.brushType](0, coordSys, coordRange);
area.__rangeOffset = {
offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
xyMinMax: result.xyMinMax
};
}
});
return areas;
}
matchOutputRanges<T extends (
Parameters<BrushTargetManager['findTargetInfo']>[0] & {
brushType: BrushType;
range: BrushAreaRange;
}
)>(
areas: T[],
ecModel: GlobalModel,
cb: (
area: T,
coordRange: ReturnType<ConvertCoord>['values'],
coordSys: BrushableCoordinateSystem,
ecModel: GlobalModel
) => void
) {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (targetInfo && targetInfo !== true) {
each(
targetInfo.coordSyses,
function (coordSys) {
const result = coordConvert[area.brushType](1, coordSys, area.range, true);
cb(area, result.values, coordSys, ecModel);
}
);
}
}, this);
}
/**
* the `areas` is `BrushModel.areas`.
* Called in layout stage.
* convert `area.coordRange` to global range and set panelId to `area.range`.
*/
setInputRanges(
areas: BrushAreaParamInternal[],
ecModel: GlobalModel
): void {
each(areas, function (area) {
const targetInfo = this.findTargetInfo(area, ecModel);
if (__DEV__) {
assert(
!targetInfo || targetInfo === true || area.coordRange,
'coordRange must be specified when coord index specified.'
);
assert(
!targetInfo || targetInfo !== true || area.range,
'range must be specified in global brush.'
);
}
area.range = area.range || [];
// convert coordRange to global range and set panelId.
if (targetInfo && targetInfo !== true) {
area.panelId = targetInfo.panelId;
// (1) area.range shoule always be calculate from coordRange but does
// not keep its original value, for the sake of the dataZoom scenario,
// where area.coordRange remains unchanged but area.range may be changed.
// (2) Only support converting one coordRange to pixel range in brush
// component. So do not consider `coordRanges`.
// (3) About __rangeOffset, see comment above.
const result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
const rangeOffset = area.__rangeOffset;
area.range = rangeOffset
? diffProcessor[area.brushType](
result.values,
rangeOffset.offset,
getScales(result.xyMinMax, rangeOffset.xyMinMax)
)
: result.values;
}
}, this);
}
makePanelOpts(
api: ExtensionAPI,
getDefaultBrushType?: (targetInfo: BrushTargetInfo) => BrushType
): BrushPanelConfig[] {
return map(this._targetInfoList, function (targetInfo) {
const rect = targetInfo.getPanelRect();
return {
panelId: targetInfo.panelId,
defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
clipPath: brushHelper.makeRectPanelClipPath(rect),
isTargetByCursor: brushHelper.makeRectIsTargetByCursor(
rect, api, targetInfo.coordSysModel
),
getLinearBrushOtherExtent: brushHelper.makeLinearBrushOtherExtent(rect)
};
});
}
controlSeries(area: BrushAreaParamInternal, seriesModel: SeriesModel, ecModel: GlobalModel): boolean {
// Check whether area is bound in coord, and series do not belong to that coord.
// If do not do this check, some brush (like lineX) will controll all axes.
const targetInfo = this.findTargetInfo(area, ecModel);
return targetInfo === true || (
targetInfo && indexOf(
targetInfo.coordSyses, seriesModel.coordinateSystem as BrushableCoordinateSystem
) >= 0
);
}
/**
* If return Object, a coord found.
* If reutrn true, global found.
* Otherwise nothing found.
*/
findTargetInfo(
area: ModelFinderObject & {
panelId?: string
},
ecModel: GlobalModel
): BrushTargetInfo | true {
const targetInfoList = this._targetInfoList;
const foundCpts = parseFinder(ecModel, area);
for (let i = 0; i < targetInfoList.length; i++) {
const targetInfo = targetInfoList[i];
const areaPanelId = area.panelId;
if (areaPanelId) {
if (targetInfo.panelId === areaPanelId) {
return targetInfo;
}
}
else {
for (let j = 0; j < targetInfoMatchers.length; j++) {
if (targetInfoMatchers[j](foundCpts, targetInfo)) {
return targetInfo;
}
}
}
}
return true;
}
}
function formatMinMax(minMax: BrushDimensionMinMax): BrushDimensionMinMax {
minMax[0] > minMax[1] && minMax.reverse();
return minMax;
}
function parseFinder(
ecModel: GlobalModel, finder: ModelFinder
): ParsedModelFinderKnown {
return modelUtilParseFinder(
ecModel, finder, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
);
}
type TargetInfoBuilder = (
foundCpts: ParsedModelFinderKnown, targetInfoList: BrushTargetInfo[]
) => void;
const targetInfoBuilders: Record<BrushTargetBuilderKey, TargetInfoBuilder> = {
grid: function (foundCpts, targetInfoList) {
const xAxisModels = foundCpts.xAxisModels;
const yAxisModels = foundCpts.yAxisModels;
const gridModels = foundCpts.gridModels;
// Remove duplicated.
const gridModelMap = createHashMap<GridModel>();
const xAxesHas = {} as Dictionary<boolean>;
const yAxesHas = {} as Dictionary<boolean>;
if (!xAxisModels && !yAxisModels && !gridModels) {
return;
}
each(xAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
});
each(yAxisModels, function (axisModel) {
const gridModel = axisModel.axis.grid.model;
gridModelMap.set(gridModel.id, gridModel);
yAxesHas[gridModel.id] = true;
});
each(gridModels, function (gridModel) {
gridModelMap.set(gridModel.id, gridModel);
xAxesHas[gridModel.id] = true;
yAxesHas[gridModel.id] = true;
});
gridModelMap.each(function (gridModel) {
const grid = gridModel.coordinateSystem;
const cartesians = [] as Cartesian2D[];
each(grid.getCartesians(), function (cartesian, index) {
if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0
|| indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0
) {
cartesians.push(cartesian);
}
});
targetInfoList.push({
panelId: 'grid--' + gridModel.id,
gridModel: gridModel,
coordSysModel: gridModel,
// Use the first one as the representitive coordSys.
coordSys: cartesians[0],
coordSyses: cartesians,
getPanelRect: panelRectBuilders.grid,
xAxisDeclared: xAxesHas[gridModel.id],
yAxisDeclared: yAxesHas[gridModel.id]
} as BrushTargetInfoCartesian2D);
});
},
geo: function (foundCpts, targetInfoList) {
each(foundCpts.geoModels, function (geoModel: GeoModel) {
const coordSys = geoModel.coordinateSystem;
targetInfoList.push({
panelId: 'geo--' + geoModel.id,
geoModel: geoModel,
coordSysModel: geoModel,
coordSys: coordSys,
coordSyses: [coordSys],
getPanelRect: panelRectBuilders.geo
} as BrushTargetInfoGeo);
});
}
};
type TargetInfoMatcher = (
foundCpts: ParsedModelFinderKnown, targetInfo: BrushTargetInfo
) => boolean;
const targetInfoMatchers: TargetInfoMatcher[] = [
// grid
function (foundCpts, targetInfo) {
const xAxisModel = foundCpts.xAxisModel;
const yAxisModel = foundCpts.yAxisModel;
let gridModel = foundCpts.gridModel;
!gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
!gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
return gridModel && gridModel === (targetInfo as BrushTargetInfoCartesian2D).gridModel;
},
// geo
function (foundCpts, targetInfo) {
const geoModel = foundCpts.geoModel;
return geoModel && geoModel === (targetInfo as BrushTargetInfoGeo).geoModel;
}
];
type PanelRectBuilder = (this: BrushTargetInfo) => graphic.BoundingRect;
const panelRectBuilders: Record<BrushTargetBuilderKey, PanelRectBuilder> = {
grid: function (this: BrushTargetInfoCartesian2D) {
// grid is not Transformable.
return this.coordSys.master.getRect().clone();
},
geo: function (this: BrushTargetInfoGeo) {
const coordSys = this.coordSys;
const rect = coordSys.getBoundingRect().clone();
// geo roam and zoom transform
rect.applyTransform(graphic.getTransform(coordSys));
return rect;
}
};
type ConvertCoord = (
to: COORD_CONVERTS_INDEX,
coordSys: BrushableCoordinateSystem,
rangeOrCoordRange: BrushAreaRange,
clamp?: boolean
) => {
values: BrushAreaRange,
xyMinMax: BrushDimensionMinMax[]
};
const coordConvert: Record<BrushType, ConvertCoord> = {
lineX: curry(axisConvert, 0),
lineY: curry(axisConvert, 1),
rect: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xminymin = to
? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
const xmaxymax = to
? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp)
: coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
const values = [
formatMinMax([xminymin[0], xmaxymax[0]]),
formatMinMax([xminymin[1], xmaxymax[1]])
];
return {values: values, xyMinMax: values};
},
polygon: function (to, coordSys, rangeOrCoordRange: BrushDimensionMinMax[], clamp): {
values: BrushDimensionMinMax[],
xyMinMax: BrushDimensionMinMax[]
} {
const xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
const values = map(rangeOrCoordRange, function (item) {
const p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
return p;
});
return {values: values, xyMinMax: xyMinMax};
}
};
function axisConvert(
axisNameIndex: 0 | 1,
to: COORD_CONVERTS_INDEX,
coordSys: Cartesian2D,
rangeOrCoordRange: BrushDimensionMinMax
): {
values: BrushDimensionMinMax,
xyMinMax: BrushDimensionMinMax[]
} {
if (__DEV__) {
assert(
coordSys.type === 'cartesian2d',
'lineX/lineY brush is available only in cartesian2d.'
);
}
const axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
const values = formatMinMax(map([0, 1], function (i) {
return to
? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true)
: axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
}));
const xyMinMax = [];
xyMinMax[axisNameIndex] = values;
xyMinMax[1 - axisNameIndex] = [NaN, NaN];
return {values: values, xyMinMax: xyMinMax};
}
type DiffProcess = (
values: BrushDimensionMinMax | BrushDimensionMinMax[],
refer: BrushDimensionMinMax | BrushDimensionMinMax[],
scales: ReturnType<typeof getScales>
) => BrushDimensionMinMax | BrushDimensionMinMax[];
const diffProcessor: Record<BrushType, DiffProcess> = {
lineX: curry(axisDiffProcessor, 0),
lineY: curry(axisDiffProcessor, 1),
rect: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return [
[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
[values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
];
},
polygon: function (
values: BrushDimensionMinMax[], refer: BrushDimensionMinMax[], scales: ReturnType<typeof getScales>
): BrushDimensionMinMax[] {
return map(values, function (item, idx) {
return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
});
}
};
function axisDiffProcessor(
axisNameIndex: 0 | 1,
values: BrushDimensionMinMax,
refer: BrushDimensionMinMax,
scales: ReturnType<typeof getScales>
): BrushDimensionMinMax {
return [
values[0] - scales[axisNameIndex] * refer[0],
values[1] - scales[axisNameIndex] * refer[1]
];
}
// We have to process scale caused by dataZoom manually,
// although it might be not accurate.
// Return [0~1, 0~1]
function getScales(xyMinMaxCurr: BrushDimensionMinMax[], xyMinMaxOrigin: BrushDimensionMinMax[]): number[] {
const sizeCurr = getSize(xyMinMaxCurr);
const sizeOrigin = getSize(xyMinMaxOrigin);
const scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
isNaN(scales[0]) && (scales[0] = 1);
isNaN(scales[1]) && (scales[1] = 1);
return scales;
}
function getSize(xyMinMax: BrushDimensionMinMax[]): number[] {
return xyMinMax
? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
: [NaN, NaN];
}
export default BrushTargetManager; | the_stack |
import * as React from 'react';
import { DropdownProps, CheckboxProps, GridCellProps } from '@/index.type';
import { GridHead } from './GridHead';
import { GridBody } from './GridBody';
import { sortColumn, pinColumn, hideColumn, moveToIndex, getSchema } from './utility';
import { BaseProps, extractBaseProps } from '@/utils/types';
import { NestedRowProps } from './GridNestedRow';
import classNames from 'classnames';
import { GridProvider } from './GridContext';
import defaultProps from './defaultProps';
export type SortType = 'asc' | 'desc' | 'unsort';
export type Pinned = 'left' | 'right' | 'unpin';
export type Alignment = 'left' | 'right' | 'center';
export type Comparator = (a: RowData, b: RowData) => -1 | 0 | 1;
export type Filter = any[];
export type GridRef = HTMLDivElement | null;
export type PageInfo = { page: number; scrollTop: number };
export interface FetchDataOptions {
page?: number;
pageSize?: number;
filterList?: GridProps['filterList'];
sortingList?: GridProps['sortingList'];
searchTerm?: string;
}
export type fetchDataFunction = (options: FetchDataOptions) => Promise<{
searchTerm?: string;
count: number;
data: Data;
schema: Schema;
}>;
export type updateSortingListFunction = (newSortingList: GridProps['sortingList']) => void;
export type updateFilterListFunction = (newFilterList: GridProps['filterList']) => void;
export type updateSchemaFunction = (newSchema: Schema) => void;
export type updateSelectAllFunction = (attr: GridProps['selectAll']) => void;
export type updateColumnSchemaFunction = (name: ColumnSchema['name'], schemaUpdate: Partial<ColumnSchema>) => void;
export type updateRowDataFunction = (rowIndexes: number[], dataUpdate: Partial<RowData>) => void;
export type sortDataFunction = (comparator: Comparator, type: SortType) => void;
export type reorderColumnFunction = (from: string, to: string) => void;
export type onSelectFn = (rowIndex: number, selected: boolean) => void;
export type onFilterChangeFn = (name: ColumnSchema['name'], selected: any) => void;
export type onSelectAllFunction = (selected: boolean, selectAll?: boolean) => void;
export type onFilterChangeFunction = (data: RowData, filters: Filter) => boolean;
export type onRowClickFunction = (data: RowData, rowIndex?: number) => void;
export type onMenuChangeFn = (name: ColumnSchema['name'], selected: any) => void;
export type updatePrevPageInfoFunction = (value: PageInfo) => void;
export type CellType =
| 'DEFAULT'
| 'WITH_META_LIST'
| 'AVATAR'
| 'AVATAR_WITH_TEXT'
| 'AVATAR_WITH_META_LIST'
| 'STATUS_HINT'
| 'ICON';
export type ColumnSchema = {
/**
* Key value of `Data` object
*/
name: string;
/**
* Header name
*/
displayName: string;
/**
* width of the column(px/%)
*/
width?: React.ReactText;
/**
* min-width of the column(px/%)
* @default 96
*/
minWidth?: React.ReactText;
/**
* max-width of the column(px/%)
* @default 800
*/
maxWidth?: React.ReactText;
/**
* Denotes if column is resizable
*/
resizable?: boolean;
/**
* Enable sorting of the column
* @default true
*/
sorting?: boolean;
/**
* Sorting Function
*/
comparator?: Comparator;
/**
* Show left separator
*/
separator?: boolean;
/**
* Pinned
*/
pinned?: Pinned;
/**
* Hidden
*/
hidden?: boolean;
/**
* Filter list
*/
filters?: DropdownProps['options'];
/**
* Callback onFilterChange
*/
onFilterChange?: onFilterChangeFunction;
/**
* Translate cell data
*/
translate?: (data: RowData) => RowData;
/**
* Cell type
* @default DEFAULT
*/
cellType?: CellType;
/**
* Custom cell renderer
*/
cellRenderer?: React.FC<GridCellProps>;
/**
* Alignment of column
* @default 'left'
*/
align?: Alignment;
/**
* Show tooltip on hover
*/
tooltip?: boolean;
};
export type RowData = Record<string, any> & {
_selected?: boolean;
};
export type GridSize = 'comfortable' | 'standard' | 'compressed' | 'tight';
export type GridType = 'resource' | 'data';
export type Data = RowData[];
export type Schema = ColumnSchema[];
export interface GridProps extends BaseProps {
/**
* Controls spacing of `Grid`
*/
size: GridSize;
/**
* Grid type
*/
type: GridType;
/**
* Callback on Row click in case of `Resource Grid`
*/
onRowClick?: onRowClickFunction;
/**
* Schema used to render `loading` state
*/
loaderSchema: Schema;
/**
* Schema used to render `data` object
*/
schema: Schema;
/**
* Data object
*/
data: Data;
/**
* Total records in grid
*/
totalRecords: number;
/**
* Loading state of Grid
*/
loading: boolean;
/**
* Error state of Grid
*/
error: boolean;
/**
* Callback to be called to get the updated data
*/
updateData?: () => void;
/**
* Callback to be called to get the updated data
*/
updateSchema?: updateSchemaFunction;
/**
* Shows grid head
*/
showHead?: boolean;
/**
* Shows menu in head cell
*/
showMenu?: boolean;
/**
* Allows dragging of column
*/
draggable?: boolean;
/**
* Allows nested rows
*/
nestedRows?: boolean;
/**
* Renderer to be used for nested rows
*/
nestedRowRenderer?: React.FC<NestedRowProps>;
/**
* Shows pagination component
*/
withPagination?: boolean;
/**
* Current page
*/
page: number;
/**
* Number of rows on a page
*/
pageSize: number;
/**
* Shows checkbox in the left most column
*/
withCheckbox?: boolean;
/**
* Callback on row select
*/
onSelect?: onSelectFn;
/**
* Callback on column head select
*/
onSelectAll?: onSelectAllFunction;
/**
* Error Template
* **Functional Component will be deprecated soon**
*/
errorTemplate?: React.FunctionComponent | React.ReactNode;
/**
* Sorting List
*/
sortingList: {
name: ColumnSchema['name'];
type: SortType;
}[];
/**
* update Sorting List Callback
*/
updateSortingList?: updateSortingListFunction;
/**
* Filter List
*/
filterList: Record<ColumnSchema['name'], Filter>;
/**
* update Filter List Callback
*/
updateFilterList?: updateFilterListFunction;
/**
* Select All
*/
selectAll?: {
checked: boolean;
indeterminate: boolean;
};
/**
* Shows tooltip on Head Cell hover
*/
headCellTooltip?: boolean;
/**
* Shows left separator to all columns
*
* **Can be override by Column Schema**
*/
separator?: boolean;
/**
* Show filters in Head Cell
*/
showFilters: boolean;
}
export interface GridState {
init: boolean;
prevPageInfo: PageInfo;
}
export class Grid extends React.Component<GridProps, GridState> {
static defaultProps: GridProps;
gridRef: GridRef = null;
isHeadSyncing = false;
isBodySyncing = false;
constructor(props: GridProps) {
super(props);
const pageInfo = { page: 1, scrollTop: 0 };
this.state = {
init: false,
prevPageInfo: pageInfo,
};
}
componentDidMount() {
this.setState({
init: true,
});
window.addEventListener('resize', this.forceRerender.bind(this));
}
forceRerender() {
this.forceUpdate();
}
componentWillUnmount() {
this.removeScrollListeners();
window.removeEventListener('resize', this.forceRerender.bind(this));
}
componentDidUpdate(prevProps: GridProps, prevState: GridState) {
if (prevState.init !== this.state.init) {
this.addScrollListeners();
}
if (prevProps.page !== this.props.page || prevProps.error !== this.props.error) {
this.removeScrollListeners();
this.addScrollListeners();
}
}
addScrollListeners() {
const gridHeadEl = this.gridRef!.querySelector('.Grid-head');
const gridBodyEl = this.gridRef!.querySelector('.Grid-body');
if (gridHeadEl && gridBodyEl) {
gridHeadEl.addEventListener('scroll', this.syncScroll('head'));
gridBodyEl.addEventListener('scroll', this.syncScroll('body'));
}
}
removeScrollListeners() {
const gridHeadEl = this.gridRef!.querySelector('.Grid-head');
const gridBodyEl = this.gridRef!.querySelector('.Grid-body');
if (gridHeadEl && gridBodyEl) {
gridHeadEl.removeEventListener('scroll', this.syncScroll('head'));
gridBodyEl.removeEventListener('scroll', this.syncScroll('body'));
}
}
syncScroll = (type: string) => () => {
const gridHeadEl = this.gridRef!.querySelector('.Grid-head');
const gridBodyEl = this.gridRef!.querySelector('.Grid-body');
if (type === 'head') {
if (!this.isHeadSyncing) {
this.isBodySyncing = true;
gridBodyEl!.scrollLeft = gridHeadEl!.scrollLeft;
}
this.isHeadSyncing = false;
}
if (type === 'body') {
if (!this.isBodySyncing) {
this.isHeadSyncing = true;
gridHeadEl!.scrollLeft = gridBodyEl!.scrollLeft;
}
this.isBodySyncing = false;
}
};
updateRenderedSchema = (newSchema: Schema) => {
const { updateSchema } = this.props;
if (updateSchema) {
updateSchema(newSchema);
}
};
updateColumnSchema: updateColumnSchemaFunction = (name, schemaUpdate) => {
const { schema } = this.props;
const newSchema = [...schema];
const ind = newSchema.findIndex((s) => s.name === name);
newSchema[ind] = {
...newSchema[ind],
...schemaUpdate,
};
this.updateRenderedSchema(newSchema);
};
reorderColumn: reorderColumnFunction = (from, to) => {
const { schema } = this.props;
const fromInd = schema.findIndex((s) => s.name === from);
const toInd = schema.findIndex((s) => s.name === to);
const newSchema = moveToIndex(schema, fromInd, toInd);
this.updateRenderedSchema(newSchema);
};
updateSortingList = (sortingList: GridProps['sortingList']) => {
const { updateSortingList } = this.props;
if (updateSortingList) {
updateSortingList(sortingList);
}
};
updateFilterList = (filterList: GridProps['filterList']) => {
const { updateFilterList } = this.props;
if (updateFilterList) {
updateFilterList(filterList);
}
};
onMenuChange: onMenuChangeFn = (name, selected) => {
const { sortingList } = this.props;
switch (selected) {
case 'sortAsc':
sortColumn({ sortingList, updateSortingList: this.updateSortingList }, name, 'asc');
break;
case 'sortDesc':
sortColumn({ sortingList, updateSortingList: this.updateSortingList }, name, 'desc');
break;
case 'unsort':
sortColumn({ sortingList, updateSortingList: this.updateSortingList }, name, 'unsort');
break;
case 'pinLeft':
pinColumn({ updateColumnSchema: this.updateColumnSchema }, name, 'left');
break;
case 'pinRight':
pinColumn({ updateColumnSchema: this.updateColumnSchema }, name, 'right');
break;
case 'unpin':
pinColumn({ updateColumnSchema: this.updateColumnSchema }, name, 'unpin');
break;
case 'hide':
hideColumn({ updateColumnSchema: this.updateColumnSchema }, name, true);
break;
}
};
onFilterChange: onFilterChangeFn = (name, selected) => {
const { filterList } = this.props;
const newFilterList = {
...filterList,
[name]: selected,
};
this.updateFilterList(newFilterList);
};
onSelect: onSelectFn = (rowIndex, selected) => {
const { onSelect } = this.props;
if (onSelect) {
onSelect(rowIndex, selected);
}
};
onSelectAll: CheckboxProps['onChange'] = (event) => {
const { onSelectAll } = this.props;
if (onSelectAll) {
onSelectAll(event.target.checked);
}
};
updatePrevPageInfo: updatePrevPageInfoFunction = (value) => {
this.setState({
prevPageInfo: value,
});
};
render() {
const baseProps = extractBaseProps(this.props);
const { init, prevPageInfo } = this.state;
const { type, size, showHead, className, page, loading, loaderSchema } = this.props;
const schema = getSchema(this.props.schema, loading, loaderSchema);
const classes = classNames(
{
Grid: 'true',
[`Grid--${type}`]: type,
[`Grid--${size}`]: size,
},
className
);
return (
<div
className={classes}
{...baseProps}
ref={(el) => {
this.gridRef = el;
}}
>
{init && (
<GridProvider
value={{
...this.props,
ref: this.gridRef,
}}
>
{showHead && (
<GridHead
schema={schema}
onSelectAll={this.onSelectAll?.bind(this)}
onMenuChange={this.onMenuChange.bind(this)}
onFilterChange={this.onFilterChange.bind(this)}
updateColumnSchema={this.updateColumnSchema.bind(this)}
reorderColumn={this.reorderColumn.bind(this)}
/>
)}
<GridBody
key={`${page}`}
schema={schema}
prevPageInfo={prevPageInfo}
updatePrevPageInfo={this.updatePrevPageInfo.bind(this)}
onSelect={this.onSelect.bind(this)}
/>
</GridProvider>
)}
</div>
);
}
}
Grid.defaultProps = defaultProps;
export default Grid; | the_stack |
import getType from 'cache-content-type';
import compressible from 'compressible';
import contentDisposition from 'content-disposition';
import { OutgoingHttpHeaders, ServerResponse } from 'http';
import { extname } from 'path';
import { Stream } from 'stream';
import * as zlib from 'zlib';
import { Container } from '../container';
import { Cookie } from '../cookie';
import { Application } from '../foundation/application';
import { Request } from '../request';
import { Resource } from '../resource/resource';
import { View } from '../view';
import { ViewFactory } from '../view/factory';
import { Statusable } from './statusable';
import { Paginator } from '../pagination';
import { Str } from '../utils/str'
const encodingMethods = {
gzip: zlib.createGzip,
deflate: zlib.createDeflate
};
const defaultContentTypes = {
JSON: 'application/json; charset=utf-8',
PLAIN: 'text/plain; charset=utf-8',
OCTET: 'application/octet-stream'
};
export class Response extends Statusable {
/**
* application
*/
protected app: Application = Container.get('app');
/**
* response statusCode
*/
protected _code: number;
/**
* response Header
*/
protected _header: OutgoingHttpHeaders;
/**
* response data
*/
protected _data: any;
/**
* response cookies
*/
protected cookies: Cookie[] = [];
/**
* need to response force
*/
protected _isForce = false
/**
* 需要加密
*/
protected _needEncrypt = false;
/**
* patched methods
*/
// [key: string]: any;
constructor(data?: any, code = 200, header: OutgoingHttpHeaders = {}) {
super();
/**
* status code
* @type
*/
this._code = code;
/**
* http headers
* @type
*/
this._header = this.parseHeaders(header);
/**
* init data
*/
this.setData(data);
}
/**
* code setter
*/
set code(code) {
this.setCode(code);
}
/**
* code getter
*/
get code() {
return this._code;
}
/**
* data setter
*/
set data(data) {
this.setData(data);
}
/**
* data getter
*/
get data() {
return this._data;
}
/**
* set to force response
*/
force() {
this._isForce = true;
return this;
}
/**
* is force response
*/
isForce() {
return this._isForce;
}
/**
* parse init headers
* @param headers
*/
private parseHeaders(headers: OutgoingHttpHeaders) {
const keys = Object.keys(headers);
const _headers: OutgoingHttpHeaders = {};
for (const key of keys) {
_headers[key.toLocaleLowerCase()] = headers[key];
}
return _headers;
}
/**
* throw http exception with code and message
* @param message exception message
* @param code exception code
*/
error(message: any, code = 404) {
this.setCode(code);
this.setData(message);
return this;
}
/**
* set success data in ctx.body
* @param data data
* @param code http code
*/
success(data: any, code = 200) {
this.setCode(code);
this.setData(data);
return this;
}
/**
* get http header
*/
getHeader(name: string) {
return this._header[name.toLowerCase()];
}
/**
* Set response header
* The original response headers are merged when the name is passed in as object
*
* @param name Response header parameter name
* @param value Response header parameter value
*/
setHeader(name: any, value: any) {
this._header[name.toLowerCase()] = value;
return this;
}
/**
* remove header from response
* @param name
*/
removeHeader(name: any) {
delete this._header[name.toLowerCase()];
return this;
}
/**
* getHeader alias
* @public
*/
getHeaders() {
return this._header;
}
/**
* setHeader alias
* @public
*/
setHeaders(headers: any) {
const keys = Object.keys(headers);
for (const key of keys) {
this.setHeader(key.toLowerCase(), headers[key]);
}
return this;
}
/**
* get http code
* @public
*/
getCode() {
return this.code;
}
/**
* getCode alias
* @public
*/
getStatus() {
return this.getCode();
}
/**
* set code
* @public
* @param code status
*/
setCode(code = 200) {
if (code) this._code = code;
return this;
}
/**
* setCode alias
* @public
* @param code status
*/
setStatus(code: number) {
return this.setCode(code);
}
/**
* get return data
* @public
*/
getData() {
return this._data;
}
/**
* set content-type
* @param type
*/
setType(type: string) {
const _type = getType(type);
if (_type) {
this.setHeader('Content-Type', _type);
}
return this;
}
/**
* get content type
*/
getType() {
const type = this.getHeader('Content-Type') as string;
if (!type) return '';
return type.split(';', 1)[0];
}
/**
* set length header
* @param length
*/
setLength(length: number) {
this.setHeader('Content-Length', length);
return this;
}
/**
* get response data length
*/
getLength() {
const length = this.getHeader('Content-Length') as string;
return length ? parseInt(length, 10) : 0;
}
/**
* set vary header
* @param field
*/
setVary(field: string) {
const varyHeader = this.getHeader('Vary') || '';
const varys = String(varyHeader).split(',');
varys.push(field);
this.setHeader('Vary', varys.filter((v: string) => !!v).join(','));
}
/**
* LastModified
* @public
* @param time time
* @returns this
*/
lastModified(time: string | Date | number) {
if (time instanceof Date) {
this.setHeader('Last-Modified', time.toUTCString());
return this;
}
if (typeof time === 'string' || typeof time === 'number') {
this.setHeader('Last-Modified', (new Date(time)).toUTCString());
return this;
}
return this;
}
/**
* Expires
* @param time time
*/
expires(time: string) {
this.setHeader('Expires', time);
return this;
}
/**
* ETag
* @param eTag eTag
*/
eTag(eTag: string) {
if (!(/^(W\/)?"/.test(eTag))) {
this.setHeader('ETag', `"${eTag}"`);
return this;
}
this.setHeader('ETag', eTag);
return this;
}
/**
* CacheControl
* @param cache cache setting
*/
cacheControl(cache: string) {
this.setHeader('Cache-Control', cache);
return this;
}
/**
* Set the page to do no caching
* @public
*/
noCache() {
this.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
this.setHeader('Pragma', 'no-cache');
return this;
}
/**
* ContentType
* @public
* @param contentType The output type
* @param charset The output of language
*/
contentType(contentType: string, charset = 'utf-8') {
this.setHeader('Content-Type', `${contentType}; charset=${charset}`);
return this;
}
/**
* Contents-dispositions are set as "attachments" to indicate that the client prompts to download.
* Optionally, specify the filename to be downloaded.
* @public
* @param filename
* @returns this
*/
attachment(filename = '', options: any) {
if (filename) this.setType(extname(filename));
this.setHeader('Content-Disposition', contentDisposition(filename, options));
return this;
}
/**
* attachment alias
* @public
* @param filename
*/
download(data: any, filename = '', options: any) {
return this.setData(data).attachment(filename, options);
}
/**
* handle Resource data
*/
transformData(request: any) {
const data = this.getData();
if (!data) return data;
if (data instanceof Resource) {
this.setType('json');
return data.output();
}
if (data instanceof View) {
this.setType('html');
return (new ViewFactory(data)).output(request);
}
if (data instanceof Paginator) {
this.setType('json');
return data.toJSON();
}
return data;
}
/**
* response with cookie instance
* @param _cookie
*/
withCookie(_cookie: any) {
if (_cookie instanceof Cookie) {
this.cookies.push(_cookie);
}
return this;
}
/**
* response with cookie
* @param key
* @param value
* @param options
*/
cookie(key: string, value: any, options: any = {}) {
this.withCookie(new Cookie(key, value, options));
return this;
}
/**
* set json response type
*/
json(data?: any) {
this.setType('json');
if (data) this.setData(data);
return this;
}
/**
* set html response type
*/
html(data?: any) {
this.setType('html');
if (data) this.setData(data);
return this;
}
/**
* set html response type
*/
text(data?: any) {
this.setType('text');
if (data) this.setData(data);
return this;
}
async commitCookies(request: any) {
for (const _cookie of this.cookies) {
request.cookies.set(_cookie.getName(), _cookie.getValue(), _cookie.getOptions());
}
if (this.app.needsSession) {
await request.session().autoCommit();
}
}
/**
* send headers
* @param res
*/
sendHeaders(res: ServerResponse) {
if (res.headersSent) return this;
const code = this.getCode();
const headers = this.getHeaders();
res.writeHead(code, headers);
return this;
}
/**
* Set the returned data
* @public
* @param data Returned data
*/
setData(data: any) {
this._data = data;
return this;
}
/**
* 加密
* @returns
*/
encrypt(encrypt = true) {
this._needEncrypt = encrypt;
return this;
}
/**
* prepare response
* @param request
*/
prepare(request: Request) {
let data = this.transformData(request);
if (this._needEncrypt || request.needEncrypt) {
const config = this.app.get('config')
const key = config.get('app.key', 'dazejs')
const iv = config.get('app.iv', null)
data = Str.aesEncrypt(JSON.stringify(data), key, iv)
this.setHeader('encrypted', true)
this.setHeader('content-type', defaultContentTypes.PLAIN);
}
const shouldSetType = !this.getHeader('content-type');
// if no content
if (data === null || typeof data === 'undefined') {
this.setCode(204);
this.removeHeader('content-type');
this.removeHeader('content-length');
this.removeHeader('transfer-encoding');
return data || '';
}
// string
if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.PLAIN);
this.setHeader('content-length', Buffer.byteLength(data.toString()));
return data.toString();
}
// buffer
if (Buffer.isBuffer(data)) {
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.OCTET);
this.setHeader('content-length', data.length);
return data;
}
// stream
if (typeof data.pipe === 'function') {
this.removeHeader('content-length');
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.OCTET);
return data;
}
// json
this.removeHeader('content-length');
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.JSON);
return data;
}
/**
* send data
* @param request
* @public
*/
async send(request: Request) {
const data = this.prepare(request);
if (this.app.get('config').get('app.compress')) {
return this.endWithCompress(request, data);
}
return this.end(request, data);
}
/**
* end response
* @param request
* @param data
*/
async end(request: Request, data: any) {
const { res } = request;
// commit cookies
await this.commitCookies(request);
// responses
if (typeof data === 'string' || Buffer.isBuffer(data)) {
this.sendHeaders(res);
return res.end(data);
}
if (data instanceof Stream) {
this.sendHeaders(res);
return data.pipe(res);
};
// json
const jsonData = JSON.stringify(data);
if (!res.headersSent) {
this.setHeader('content-length', Buffer.byteLength(jsonData));
}
this.sendHeaders(res);
return res.end(jsonData);
}
/**
* end with compress
* @param request
*/
endWithCompress(request: Request, data: any) {
// if compress is disable
const encoding: string | false = request.acceptsEncodings('gzip', 'deflate', 'identity');
if (!encoding || encoding === 'identity') return this.end(request, data);
if (!compressible(this.getType())) return this.end(request, data);
const threshold = this.app.get('config').get('app.threshold', 1024);
if (threshold > this.getLength()) return this.end(request, data);
this.setHeader('Content-Encoding', encoding);
this.removeHeader('Content-Length');
const stream = encodingMethods[encoding as 'gzip' | 'deflate']({});
if (data instanceof Stream) {
data.pipe(stream);
} else {
stream.end(data);
}
return this.end(request, stream);
}
} | the_stack |
import Sinon = require('sinon');
import * as TestOverrides from '../../test-related-lib/TestOverrides';
import * as TestUtils from '../../TestUtils';
import { RuleCatalog } from '../../../src/lib/services/RuleCatalog';
import { CategoryFilter, EngineFilter, LanguageFilter, RuleFilter, RulesetFilter } from '../../../src/lib/RuleFilter';
import { ENGINE, LANGUAGE } from '../../../src/Constants';
import { Rule, RuleGroup } from '../../../src/types';
import LocalCatalog from '../../../src/lib/services/LocalCatalog';
import { expect } from 'chai';
TestOverrides.initializeTestSetup();
describe('LocalCatalog', () => {
let catalog: RuleCatalog;
beforeEach(async () => {
TestUtils.stubCatalogFixture();
catalog = new LocalCatalog();
await catalog.init();
});
afterEach(() => {
Sinon.restore();
});
describe('getRuleGroupsMatchingFilters', () => {
const LANGUAGE_ECMASCRIPT = 'ecmascript';
/**
* Return a map of key=<engine.name>:<ruleGroup.name>, value=RuleGroup
*/
const mapRuleGroups = (ruleGroups: RuleGroup[]): Map<string, RuleGroup> => {
const map = new Map<string, RuleGroup>();
ruleGroups.forEach(ruleGroup => {
const key = `${ruleGroup.engine}:${ruleGroup.name}`;
expect(map.has(key), key).to.be.false;
map.set(key, ruleGroup);
});
return map;
};
const validatePmdRuleGroup = (mappedRuleGroups: Map<string, RuleGroup>, name: string, languages: string[], type: string): void => {
const ruleGroup = mappedRuleGroups.get(`${ENGINE.PMD}:${name}`);
expect(ruleGroup).to.not.be.undefined;
expect(ruleGroup.name).to.equal(name);
expect(ruleGroup.engine).to.equal(ENGINE.PMD);
expect(ruleGroup.paths, TestUtils.prettyPrint(ruleGroup.paths)).to.be.lengthOf(languages.length);
const paths = [];
for (const language of languages) {
const fileName = name.toLowerCase().replace(' ', '');
paths.push(`${type}/${language}/${fileName}.xml`);
}
// Not concerned about order
expect(ruleGroup.paths, TestUtils.prettyPrint(ruleGroup.paths)).to.have.members(paths);
};
const validatePmdCategory = (mappedRuleGroups: Map<string, RuleGroup>, name: string, languages: string[]): void => {
validatePmdRuleGroup(mappedRuleGroups, name, languages, 'category');
};
const validateEslintBestPractices = (mappedRuleGroups: Map<string, RuleGroup>): void => {
for (const engine of [ENGINE.ESLINT, ENGINE.ESLINT_TYPESCRIPT]) {
const ruleGroup = mappedRuleGroups.get(`${engine}:Best Practices`);
expect(ruleGroup.name).to.equal('Best Practices');
expect(ruleGroup.engine).to.equal(engine);
expect(ruleGroup.paths, TestUtils.prettyPrint(ruleGroup.paths)).to.be.lengthOf(2);
expect(ruleGroup.paths).to.eql(['https://eslint.org/docs/rules/no-implicit-globals', 'https://eslint.org/docs/rules/no-implicit-coercion']);
}
};
const validateEslintPossibleErrors = (mappedRuleGroups: Map<string, RuleGroup>): void => {
for (const engine of [ENGINE.ESLINT, ENGINE.ESLINT_TYPESCRIPT]) {
const ruleGroup = mappedRuleGroups.get(`${engine}:Possible Errors`);
expect(ruleGroup).to.not.be.undefined;
expect(ruleGroup.name).to.equal('Possible Errors');
expect(ruleGroup.engine).to.equal(engine);
expect(ruleGroup.paths, TestUtils.prettyPrint(ruleGroup.paths)).to.be.lengthOf(1);
expect(ruleGroup.paths).to.eql(['https://eslint.org/docs/rules/no-inner-declarations']);
}
};
describe('RulesetFilters', () => {
const validatePmdRuleset = (mappedRuleGroups: Map<string, RuleGroup>, name: string, languages: string[]): void => {
validatePmdRuleGroup(mappedRuleGroups, name, languages, 'rulesets');
};
it('Correctly filters by one value', async () => {
// SETUP
// Create a filter that matches a single ruleset.
const filter: RuleFilter = new RulesetFilter(['Braces']);
// INVOCATION OF TESTED METHOD
// Use the created filter to filter the available rules.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// We expect a single ruleset, corresponding to PMD's "Braces" ruleset.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(1);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validatePmdRuleset(mappedRuleGroups, 'Braces', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
});
it('Correctly filters by multiple values', async () => {
// SETUP
// Create a filter that matches two rulesets.
const filter: RuleFilter = new RulesetFilter(['Security', 'Braces']);
// INVOCATION OF TESTED METHOD
// Use the created filter to filter the available rules.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// We expect two rulesets, corresponding to PMD's "Security" and "Braces" rulesets.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(2);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validatePmdRuleset(mappedRuleGroups, 'Braces', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
validatePmdRuleset(mappedRuleGroups, 'Security', ['apex', 'vf']);
});
});
describe('CategoryFilters', () => {
describe('Positive filters', () => {
it('Correctly filters by one value', async () => {
// SETUP
// Create a filter that matches one category
const filter: RuleFilter = new CategoryFilter(['Best Practices']);
// INVOCATION OF TESTED METHOD
// Use the created filter to filter the available rules.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// There should be three engines with the desired category: Eslint, eslint-typescript, and PMD.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(3);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintBestPractices(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Best Practices', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
});
it('Correctly filters by multiple values', async () => {
// SETUP
// Create a filter that matches two categories
const filter: RuleFilter = new CategoryFilter(['Best Practices', 'Possible Errors']);
// INVOCATION OF TESTED METHOD
// Use the created filter to filter the available rules.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// ESLint and ESLint-typescript should have both categories. PMD should have only one.
expect(ruleGroups, 'Rule Groups').to.be.lengthOf(5);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintPossibleErrors(mappedRuleGroups);
validateEslintBestPractices(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Best Practices', [LANGUAGE.APEX, LANGUAGE_ECMASCRIPT]);
});
});
describe('Negative criteria', () => {
it('Correctly filters by one value', async () => {
// SETUP
// Create a filter that matches every category EXCEPT one.
const filter: RuleFilter = new CategoryFilter(['!Best Practices']);
// INVOCATION OF TESTED METHOD
// Use the filter on our catalog.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// ESLint and ESLint-typescript should both have one category, and PMD should have two.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(4);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintPossibleErrors(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Design', [LANGUAGE.APEX, LANGUAGE_ECMASCRIPT]);
validatePmdCategory(mappedRuleGroups, 'Error Prone', [LANGUAGE.APEX, LANGUAGE_ECMASCRIPT]);
});
it('Correctly filters by multiple values', async () => {
// SETUP
// Create a filter that matches every category EXCEPT two.
const filter: RuleFilter = new CategoryFilter(['!Best Practices', '!Design']);
// INVOCATION OF TESTED METHOD
// Use the filter on our catalog.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([filter]);
// ASSERTIONS
// ESLint, ESLint-Typescript, and PMD should each have one category.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(3);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintPossibleErrors(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Error Prone', [LANGUAGE.APEX, LANGUAGE_ECMASCRIPT]);
});
});
});
describe('Inapplicable Filters', () => {
it('Inapplicable filters are ignored', async () => {
// SETUP
// Create a filter that matches one category, and a filter that matches only PMD.
const catFilter: RuleFilter = new CategoryFilter(['Best Practices']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.PMD]);
// INVOCATION OF TESTED METHOD
// Use the created filters to filter the available rules.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([catFilter, engineFilter]);
// ASSERTIONS
// There should be three engines with the desired category: Eslint, eslint-typescript, and PMD.
// The Engine filter should have been ignored entirely.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(3);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintBestPractices(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Best Practices', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
});
});
describe('Edge Cases', () => {
it('Returns all categories when given no filters', async () => {
// INVOCATION OF TESTED METHOD
// Apply a list of empty filters to the catalog.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([]);
// ASSERTIONS
// All categories for all engines should have been returned.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(7);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintBestPractices(mappedRuleGroups);
validateEslintPossibleErrors(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Best Practices', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
validatePmdCategory(mappedRuleGroups, 'Design', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
validatePmdCategory(mappedRuleGroups, 'Error Prone', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
});
it('Returns all categories when given only inapplicable filters', async () => {
// SETUP
// Create a filter that matches only PMD.
const engineFilter: RuleFilter = new EngineFilter([ENGINE.PMD]);
// INVOCATION OF TESTED METHOD
// Attempt to apply the inapplicable filter to the catalog.
const ruleGroups: RuleGroup[] = catalog.getRuleGroupsMatchingFilters([engineFilter]);
// ASSERTIONS
// Inapplicable filters are skipped entirely, so we should get all categories as though we'd provided an
// empty list.
expect(ruleGroups, TestUtils.prettyPrint(ruleGroups)).to.be.lengthOf(7);
const mappedRuleGroups = mapRuleGroups(ruleGroups);
validateEslintBestPractices(mappedRuleGroups);
validateEslintPossibleErrors(mappedRuleGroups);
validatePmdCategory(mappedRuleGroups, 'Best Practices', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
validatePmdCategory(mappedRuleGroups, 'Design', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
validatePmdCategory(mappedRuleGroups, 'Error Prone', [LANGUAGE_ECMASCRIPT, LANGUAGE.APEX]);
});
});
});
describe ('getRulesMatchingFilters', () => {
const mapRules = (rules: Rule[]): Map<string, Rule> => {
const map = new Map<string, Rule>();
rules.forEach(rule => {
const key = `${rule.engine}:${rule.name}`;
expect(map.has(key), key).to.be.false;
map.set(key, rule);
});
return map;
};
const validateRule = (mappedRules: Map<string, Rule>, names: string[], categories: string[], languages: string[], engines: ENGINE[]): void => {
for (const engine of engines) {
for (const name of names) {
const rule = mappedRules.get(`${engine}:${name}`);
expect(rule).to.not.be.undefined;
expect(rule.name).to.equal(name);
expect(rule.engine).to.equal(engine);
expect(rule.categories).to.have.members(categories);
expect(rule.languages).to.have.members(languages);
}
}
};
const validatePmdRule = (mappedRules: Map<string, Rule>, names: string[], categories: string[], languages: string[]): void => {
validateRule(mappedRules, names, categories, languages, [ENGINE.PMD]);
};
const validateEslintRule = (mappedRules: Map<string, Rule>, names: string[], categories: string[], engines=[ENGINE.ESLINT, ENGINE.ESLINT_TYPESCRIPT]): void => {
for (const engine of engines) {
const languages = engine === ENGINE.ESLINT ? [LANGUAGE.JAVASCRIPT] : [LANGUAGE.TYPESCRIPT];
validateRule(mappedRules, names, categories, languages, [engine]);
}
};
describe('CategoryFilter', () => {
describe ('Positive', () => {
it ('Single Value', async () => {
const filter: RuleFilter = new CategoryFilter(['Possible Errors']);
const rules: Rule[] = catalog.getRulesMatchingFilters([filter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(4);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-unreachable', 'no-inner-declarations'], ['Possible Errors']);
});
it ('Multiple Values', async () => {
const filter: RuleFilter = new CategoryFilter(['Possible Errors', 'Design']);
const rules: Rule[] = catalog.getRulesMatchingFilters([filter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(6);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-unreachable', 'no-inner-declarations'], ['Possible Errors']);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
});
// Multiple Filters: Not tested
// The #getRuleGroupsMatchingFilters method does not prevent the caller from passing multiple
// instances of CategoryFilter. However in practice this does not occur.
});
describe ('Negative', () => {
it ('Single Value', async () => {
const filter: RuleFilter = new CategoryFilter(['!Possible Errors']);
const rules: Rule[] = catalog.getRulesMatchingFilters([filter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(7);
const mappedRules = mapRules(rules);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
validatePmdRule(mappedRules, ['ForLoopsMustUseBraces', 'IfElseStmtsMustUseBraces', 'IfStmtsMustUseBraces'], ['Code Style'], [LANGUAGE.JAVASCRIPT]);
});
it ('Multiple Values', async () => {
const filter: RuleFilter = new CategoryFilter(['!Possible Errors', '!Code Style']);
const rules: Rule[] = catalog.getRulesMatchingFilters([filter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(4);
const mappedRules = mapRules(rules);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
});
});
});
describe('Multiple Heterogenous Filters', () => {
describe('Positive', () => {
/**
* User's can specify multiple filter parameters. A rule must match at least one parameter from each
* filter in order to be returned. The #getRulesMatchingFilters method would accept multiple filters of
* the same type, but in practice this could not happen. Each CLI flag is converted into a single filter.
*
* For example:
* sfdx scanner:rule:list --language 'apex,javascript' --engine 'eslint,pmd' --category 'Best Practices,Security'
*
* Results in the expression:
* (rule.language === 'apex' || rule.language === 'javascript') &&
* (rule.engine === 'eslint' || rule.engine === 'pmd') &&
* (rule.categories.includes('Best Practices') || rule.categories.includes('Security'))
*/
describe('Rules must match a parameter from each filter when multiple filters are specified', () => {
it ('Two Filters - Single Parameter', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['Best Practices']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.PMD]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, engineFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(2);
const mappedRules = mapRules(rules);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
});
it ('Two Filters - Single/Multiple Parameters', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['Best Practices']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.ESLINT, ENGINE.PMD]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, engineFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(4);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-implicit-coercion', 'no-implicit-globals'], ['Best Practices'], [ENGINE.ESLINT]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
});
it ('Two Filters - Multiple/Multiple Parameters', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['Best Practices', 'Design']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.ESLINT, ENGINE.PMD]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, engineFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(6);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-implicit-coercion', 'no-implicit-globals'], ['Best Practices'], [ENGINE.ESLINT]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
});
it ('Three Filters - Multiple/Multiple/Single Parameters', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['Best Practices', 'Design']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.ESLINT, ENGINE.PMD]);
// Missing LANGUAGE.APEX will exclude the PMD Design category
const languageFilter: RuleFilter = new LanguageFilter([LANGUAGE.JAVASCRIPT]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, engineFilter, languageFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(4);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-implicit-coercion', 'no-implicit-globals'], ['Best Practices'], [ENGINE.ESLINT]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
});
it ('Three Filters - Multiple/Multiple/Single Parameters', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['Best Practices', 'Design']);
const engineFilter: RuleFilter = new EngineFilter([ENGINE.ESLINT, ENGINE.PMD]);
// Adding LANGUAGE.APEX will add the PMD Design category
const languageFilter: RuleFilter = new LanguageFilter([LANGUAGE.JAVASCRIPT, LANGUAGE.APEX]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, engineFilter, languageFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(6);
const mappedRules = mapRules(rules);
validateEslintRule(mappedRules, ['no-implicit-coercion', 'no-implicit-globals'], ['Best Practices'], [ENGINE.ESLINT]);
validatePmdRule(mappedRules, ['AvoidWithStatement', 'ConsistentReturn'], ['Best Practices'], [LANGUAGE.JAVASCRIPT]);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
});
});
});
});
describe('Mixed Positive and Negative', () => {
it ('Multiple Positive and Negative Values', async () => {
const categoryFilter: RuleFilter = new CategoryFilter(['!Possible Errors', '!Code Style']);
const languageFilter: RuleFilter = new LanguageFilter([LANGUAGE.APEX]);
const rules: Rule[] = catalog.getRulesMatchingFilters([categoryFilter, languageFilter]);
expect(rules, TestUtils.prettyPrint(rules)).to.be.lengthOf(2);
const mappedRules = mapRules(rules);
validatePmdRule(mappedRules, ['AvoidDeeplyNestedIfStmts', 'ExcessiveClassLength'], ['Design'], [LANGUAGE.APEX]);
});
});
});
}); | the_stack |
import * as path from "path";
import {
commands,
Disposable,
Event,
EventEmitter,
TreeDataProvider,
TreeItem,
TreeItemCollapsibleState,
Uri,
window,
workspace
} from "vscode";
import {
RepositoryChangeEvent,
ISvnLogEntry,
ISvnLogEntryPath
} from "../common/types";
import { exists } from "../fs";
import { SourceControlManager } from "../source_control_manager";
import { IRemoteRepository } from "../remoteRepository";
import { Repository } from "../repository";
import { dispose, unwrap } from "../util";
import {
checkIfFile,
copyCommitToClipboard,
fetchMore,
getCommitIcon,
getCommitLabel,
getCommitToolTip,
getIconObject,
getLimit,
ICachedLog,
ILogTreeItem,
insertBaseMarker,
LogTreeItemKind,
openDiff,
openFileRemote,
SvnPath,
transform,
getCommitDescription
} from "./common";
function getActionIcon(action: string) {
let name: string | undefined;
switch (action) {
case "A":
name = "status-added";
break;
case "D":
name = "status-deleted";
break;
case "M":
name = "status-modified";
break;
case "R":
name = "status-renamed";
break;
}
if (name === undefined) {
return undefined;
}
return getIconObject(name);
}
export class RepoLogProvider
implements TreeDataProvider<ILogTreeItem>, Disposable {
private _onDidChangeTreeData: EventEmitter<
ILogTreeItem | undefined
> = new EventEmitter<ILogTreeItem | undefined>();
public readonly onDidChangeTreeData: Event<ILogTreeItem | undefined> = this
._onDidChangeTreeData.event;
// TODO on-disk cache?
private readonly logCache: Map<string, ICachedLog> = new Map();
private _dispose: Disposable[] = [];
private getCached(maybeItem?: ILogTreeItem): ICachedLog {
const item = unwrap(maybeItem);
if (item.data instanceof SvnPath) {
return unwrap(this.logCache.get(item.data.toString()));
}
return this.getCached(item.parent);
}
constructor(private sourceControlManager: SourceControlManager) {
this.refresh();
this._dispose.push(
window.registerTreeDataProvider("repolog", this),
commands.registerCommand(
"svn.repolog.copymsg",
async (item: ILogTreeItem) => copyCommitToClipboard("msg", item)
),
commands.registerCommand(
"svn.repolog.copyrevision",
async (item: ILogTreeItem) => copyCommitToClipboard("revision", item)
),
commands.registerCommand(
"svn.repolog.addrepolike",
this.addRepolikeGui,
this
),
commands.registerCommand("svn.repolog.remove", this.removeRepo, this),
commands.registerCommand(
"svn.repolog.openFileRemote",
this.openFileRemoteCmd,
this
),
commands.registerCommand("svn.repolog.openDiff", this.openDiffCmd, this),
commands.registerCommand(
"svn.repolog.openFileLocal",
this.openFileLocal,
this
),
commands.registerCommand("svn.repolog.refresh", this.refresh, this),
this.sourceControlManager.onDidChangeRepository(
async (_e: RepositoryChangeEvent) => {
return this.refresh();
// TODO refresh only required repo, need to pass element === getChildren()
}
)
);
}
public dispose() {
dispose(this._dispose);
}
public removeRepo(element: ILogTreeItem) {
this.logCache.delete((element.data as SvnPath).toString());
this.refresh();
}
private async addRepolike(repoLike: string, rev: string) {
// TODO save user's custom repositories
const item: ICachedLog = {
entries: [],
isComplete: false,
svnTarget: {} as Uri, // later
repo: {} as IRemoteRepository, // later
persisted: {
commitFrom: rev,
userAdded: true
},
order: this.logCache.size
};
if (this.logCache.has(repoLike)) {
window.showWarningMessage("This path is already added");
return;
}
const repo = this.sourceControlManager.getRepository(repoLike);
if (repo === null) {
try {
let uri: Uri;
if (repoLike.startsWith("^")) {
const wsrepo = this.sourceControlManager.getRepository(
unwrap(workspace.workspaceFolders)[0].uri
);
if (!wsrepo) {
throw new Error("No repository in workspace root");
}
const info = await wsrepo.getInfo(repoLike);
uri = Uri.parse(info.url);
} else {
uri = Uri.parse(repoLike);
}
if (rev !== "HEAD" && isNaN(parseInt(rev, 10))) {
throw new Error("erroneous revision");
}
const remRepo = await this.sourceControlManager.getRemoteRepository(
uri
);
item.repo = remRepo;
item.svnTarget = uri;
} catch (e) {
window.showWarningMessage(
"Failed to add repo: " + (e instanceof Error ? e.message : "")
);
return;
}
} else {
try {
const svninfo = await repo.getInfo(repoLike, rev);
item.repo = repo;
item.svnTarget = Uri.parse(svninfo.url);
item.persisted.baseRevision = parseInt(svninfo.revision, 10);
} catch (e) {
window.showErrorMessage("Failed to resolve svn path");
return;
}
}
const repoName = item.svnTarget.toString(true);
if (this.logCache.has(repoName)) {
window.showWarningMessage("Repository with this name already exists");
return;
}
this.logCache.set(repoName, item);
this._onDidChangeTreeData.fire();
}
public addRepolikeGui() {
const box = window.createInputBox();
box.prompt = "Enter SVN URL or local path";
box.onDidAccept(async () => {
let repoLike = box.value;
if (
!path.isAbsolute(repoLike) &&
workspace.workspaceFolders &&
!repoLike.startsWith("^") &&
!/^[a-z]+?:\/\//.test(repoLike)
) {
for (const wsf of workspace.workspaceFolders) {
const joined = path.join(wsf.uri.fsPath, repoLike);
if (await exists(joined)) {
repoLike = joined;
break;
}
}
}
box.dispose();
const box2 = window.createInputBox();
box2.prompt = "Enter starting revision (optional)";
box2.onDidAccept(async () => {
const rev = box2.value;
box2.dispose();
return this.addRepolike(repoLike, rev || "HEAD");
}, undefined);
box2.show();
});
box.show();
}
public async openFileRemoteCmd(element: ILogTreeItem) {
const commit = element.data as ISvnLogEntryPath;
const item = this.getCached(element);
const ri = item.repo.getPathNormalizer().parse(commit._);
if ((await checkIfFile(ri, false)) === false) {
return;
}
const parent = (element.parent as ILogTreeItem).data as ISvnLogEntry;
return openFileRemote(item.repo, ri.remoteFullPath, parent.revision);
}
public openFileLocal(element: ILogTreeItem) {
const commit = element.data as ISvnLogEntryPath;
const item = this.getCached(element);
const ri = item.repo.getPathNormalizer().parse(commit._);
if (!checkIfFile(ri, true)) {
return;
}
commands.executeCommand("vscode.open", unwrap(ri.localFullPath));
}
public async openDiffCmd(element: ILogTreeItem) {
const commit = element.data as ISvnLogEntryPath;
const item = this.getCached(element);
const parent = (element.parent as ILogTreeItem).data as ISvnLogEntry;
const remotePath = item.repo.getPathNormalizer().parse(commit._)
.remoteFullPath;
let prevRev: ISvnLogEntry;
const revs = await item.repo.log(parent.revision, "1", 2, remotePath);
if (revs.length === 2) {
prevRev = revs[1];
} else {
window.showWarningMessage("Cannot find previous commit");
return;
}
return openDiff(item.repo, remotePath, prevRev.revision, parent.revision);
}
public async refresh(element?: ILogTreeItem, fetchMoreClick?: boolean) {
if (element === undefined) {
for (const [k, v] of this.logCache) {
// Remove auto-added repositories
if (!v.persisted.userAdded) {
this.logCache.delete(k);
}
}
for (const repo of this.sourceControlManager.repositories) {
const remoteRoot = repo.branchRoot;
const repoUrl = remoteRoot.toString(true);
let persisted: ICachedLog["persisted"] = {
commitFrom: "HEAD",
baseRevision: parseInt(repo.repository.info.revision, 10)
};
const prev = this.logCache.get(repoUrl);
if (prev) {
persisted = prev.persisted;
}
this.logCache.set(repoUrl, {
entries: [],
isComplete: false,
repo,
svnTarget: remoteRoot,
persisted,
order: this.logCache.size
});
}
} else if (element.kind === LogTreeItemKind.Repo) {
const cached = this.getCached(element);
if (fetchMoreClick) {
await fetchMore(cached);
} else {
cached.entries = [];
cached.isComplete = false;
}
}
this._onDidChangeTreeData.fire(element);
}
public async getTreeItem(element: ILogTreeItem): Promise<TreeItem> {
let ti: TreeItem;
if (element.kind === LogTreeItemKind.Repo) {
const svnTarget = element.data as SvnPath;
const cached = this.getCached(element);
ti = new TreeItem(
svnTarget.toString(),
TreeItemCollapsibleState.Collapsed
);
if (cached.persisted.userAdded) {
ti.label = "∘ " + ti.label;
ti.contextValue = "userrepo";
} else {
ti.contextValue = "repo";
}
if (cached.repo instanceof Repository) {
ti.iconPath = getIconObject("folder");
} else {
ti.iconPath = getIconObject("icon-repo");
}
const from = cached.persisted.commitFrom || "HEAD";
ti.tooltip = `${svnTarget} since ${from}`;
} else if (element.kind === LogTreeItemKind.Commit) {
const commit = element.data as ISvnLogEntry;
ti = new TreeItem(
getCommitLabel(commit),
TreeItemCollapsibleState.Collapsed
);
ti.description = getCommitDescription(commit);
ti.tooltip = getCommitToolTip(commit);
ti.iconPath = getCommitIcon(commit.author);
ti.contextValue = "commit";
} else if (element.kind === LogTreeItemKind.CommitDetail) {
// TODO optional tree-view instead of flat
const pathElem = element.data as ISvnLogEntryPath;
const basename = path.basename(pathElem._);
ti = new TreeItem(basename, TreeItemCollapsibleState.None);
ti.description = path.dirname(pathElem._);
const cached = this.getCached(element);
const nm = cached.repo.getPathNormalizer();
ti.tooltip = nm.parse(pathElem._).relativeFromBranch;
ti.iconPath = getActionIcon(pathElem.action);
ti.contextValue = "diffable";
ti.command = {
command: "svn.repolog.openDiff",
title: "Open diff",
arguments: [element]
};
} else if (element.kind === LogTreeItemKind.TItem) {
ti = element.data as TreeItem;
} else {
throw new Error("Unknown tree elem");
}
return ti;
}
public async getChildren(
element: ILogTreeItem | undefined
): Promise<ILogTreeItem[]> {
if (element === undefined) {
return transform(
Array.from(this.logCache.entries())
.sort(([_lk, lv], [_rk, rv]): number => {
if (lv.persisted.userAdded !== rv.persisted.userAdded) {
return lv.persisted.userAdded ? 1 : -1;
}
return lv.order - rv.order;
})
.map(([k, _v]) => new SvnPath(k)),
LogTreeItemKind.Repo
);
} else if (element.kind === LogTreeItemKind.Repo) {
const limit = getLimit();
const cached = this.getCached(element);
const logentries = cached.entries;
if (logentries.length === 0) {
await fetchMore(cached);
}
const result = transform(logentries, LogTreeItemKind.Commit, element);
insertBaseMarker(cached, logentries, result);
if (!cached.isComplete) {
const ti = new TreeItem(`Load another ${limit} revisions`);
ti.tooltip = "Paging size may be adjusted using log.length setting";
ti.command = {
command: "svn.repolog.refresh",
arguments: [element, true],
title: "refresh element"
};
ti.iconPath = getIconObject("icon-unfold");
result.push({ kind: LogTreeItemKind.TItem, data: ti });
}
return result;
} else if (element.kind === LogTreeItemKind.Commit) {
const commit = element.data as ISvnLogEntry;
return transform(commit.paths, LogTreeItemKind.CommitDetail, element);
}
return [];
}
} | the_stack |
import type {Matrix4, Quaternion, Vector3} from '@math.gl/core';
import type {TypedArray, MeshAttribute, TextureLevel} from '@loaders.gl/schema';
export enum DATA_TYPE {
UInt8 = 'UInt8',
UInt16 = 'UInt16',
UInt32 = 'UInt32',
UInt64 = 'UInt64',
Int16 = 'Int16',
Int32 = 'Int32',
Int64 = 'Int64',
Float32 = 'Float32',
Float64 = 'Float64'
}
/**
* spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/3DSceneLayer.cmn.md
*/
// TODO Replace "[key: string]: any" with actual defenition
export interface I3STilesetHeader extends SceneLayer3D {
/** Not in spec, but is necessary for woking */
url?: string;
[key: string]: any;
}
/** https://github.com/Esri/i3s-spec/blob/master/docs/1.8/nodePage.cmn.md */
export type NodePage = {
/** Array of nodes. */
nodes: NodeInPage[];
};
/**
* Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/mesh.cmn.md
*/
type NodeMesh = {
/**
* The material definition.
*/
material: MeshMaterial;
/** The geometry definition. */
geometry: MeshGeometry;
/** The attribute set definition. */
attribute: meshAttribute;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/meshMaterial.cmn.md */
export type MeshMaterial = {
/** The index in layer.materialDefinitions array. */
definition: number;
/** Resource id for the material textures. i.e: layers/0/nodes/{material.resource}/textures/{tex_name}. Is required if material declares any textures. */
resource?: number;
/** Estimated number of texel for the highest resolution base color texture. */
texelCountHint?: number;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/meshGeometry.cmn.md */
export type MeshGeometry = {
/** The index in layer.geometryDefinitions array */
definition: number;
/** The resource locator to be used to query geometry resources: layers/0/nodes/{this.resource}/geometries/{layer.geometryDefinitions[this.definition].geometryBuffers[0 or 1]}. */
resource: number;
/** Number of vertices in the geometry buffer of this mesh for the umcompressed mesh buffer. Please note that Draco compressed meshes may have less vertices due to de-duplication (actual number of vertices is part of the Draco binary blob). Default=0 */
vertexCount?: number;
/** Number of features for this mesh. Default=0. (Must omit or set to 0 if mesh doesn't use features.) */
featureCount?: number;
};
/** https://github.com/Esri/i3s-spec/blob/master/docs/1.8/meshAttribute.cmn.md */
type meshAttribute = {
/** The resource identifier to be used to locate attribute resources of this mesh. i.e. layers/0/nodes/<resource id>/attributes/... */
resource: number;
};
export type I3STextureFormat = 'jpg' | 'png' | 'ktx-etc2' | 'dds' | 'ktx2';
// TODO Replace "[key: string]: any" with actual defenition
export type I3STileHeader = {
isDracoGeometry: boolean;
textureUrl?: string;
url?: string;
textureFormat?: I3STextureFormat;
textureLoaderOptions?: any;
materialDefinition?: I3SMaterialDefinition;
mbs: Mbs;
obb?: Obb;
lodSelection?: LodSelection[];
[key: string]: any;
};
// TODO Replace "[key: string]: any" with actual defenition
export type I3STileContent = {
attributes: I3SMeshAttributes;
indices: TypedArray | null;
featureIds: number[] | TypedArray;
vertexCount: number;
modelMatrix: Matrix4;
coordinateSystem: number;
byteLength: number;
texture: TileContentTexture;
[key: string]: any;
};
export type TileContentTexture =
| ArrayBuffer
| {
compressed: boolean;
mipmaps: boolean;
width: number;
height: number;
data: TextureLevel[];
}
| null;
export type BoundingVolumes = {
mbs: Mbs;
obb: Obb;
};
export type Obb = {
center: number[] | Vector3;
halfSize: number[] | Vector3;
quaternion: Quaternion;
};
export type Mbs = [number, number, number, number];
/** SceneLayer3D based on I3S specification - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/3DSceneLayer.cmn.md */
export type SceneLayer3D = {
/** Unique numeric ID of the layer. */
id: number;
/** The relative URL to the 3DSceneLayerResource. Only present as part of the SceneServiceInfo resource. */
href?: string;
/** The user-visible layer type */
layerType: '3DObject' | 'IntegratedMesh';
/** The spatialReference of the layer including the vertical coordinate reference system (CRS). Well Known Text (WKT) for CRS is included to support custom CRS. */
spatialReference?: SpatialReference;
/** Enables consuming clients to quickly determine whether this layer is compatible (with respect to its horizontal and vertical coordinate system) with existing content. */
heightModelInfo?: HeightModelInfo;
/** The ID of the last update session in which any resource belonging to this layer has been updated. */
version: string;
/** The name of this layer. */
name?: string;
/** The time of the last update. */
serviceUpdateTimeStamp?: {lastUpdate: number};
/** The display alias to be used for this layer. */
alias?: string;
/** Description string for this layer. */
description?: string;
/** Copyright and usage information for the data in this layer. */
copyrightText?: string;
/** Capabilities supported by this layer. */
capabilities: string[];
/** ZFactor to define conversion factor for elevation unit. */
ZFactor?: number;
/** Indicates if any styling information represented as drawingInfo is captured as part of the binary mesh representation. */
cachedDrawingInfo?: CachedDrawingInfo;
/** An object containing drawing information. */
drawingInfo?: DrawingInfo;
/** An object containing elevation drawing information. If absent, any content of the scene layer is drawn at its z coordinate. */
elevationInfo?: ElevationInfo;
/** PopupInfo of the scene layer. */
popupInfo?: PopupInfo;
/** Indicates if client application will show the popup information. Default is FALSE. */
disablePopup: boolean;
/**
* The store object describes the exact physical storage of a layer and
* enables the client to detect when multiple layers are served from
* the same store.
*/
store: Store;
/** A collection of objects that describe each attribute field regarding its field name, datatype, and a user friendly name {name,type,alias}. */
fields?: Field[];
/** Provides the schema and layout used for storing attribute content in binary format in I3S. */
attributeStorageInfo?: AttributeStorageInfo[];
/** Contains the statistical information for a layer. */
statisticsInfo?: StatisticsInfo[];
/** The paged-access index description. */
nodePages?: NodePageDefinition;
/** List of materials classes used in this layer. */
materialDefinitions?: I3SMaterialDefinition[];
/** Defines the set of textures that can be referenced by meshes. */
textureSetDefinitions?: TextureSetDefinition[];
/** Define the layouts of mesh geometry and its attributes */
geometryDefinitions?: GeometryDefinition[];
/** 3D extent. */
fullExtent?: FullExtent;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/cachedDrawingInfo.cmn.md */
export type CachedDrawingInfo = {
/** If true, the drawingInfo is captured as part of the binary scene layer representation. */
color: boolean;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/drawingInfo.cmn.md */
export type DrawingInfo = {
/** An object defining the symbology for the layer. See more information about supported renderer types in ArcGIS clients. */
renderer: any;
/** Scale symbols for the layer. */
scaleSymbols: boolean;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/elevationInfo.cmn.md */
export type ElevationInfo = {
mode: 'relativeToGround' | 'absoluteHeight' | 'onTheGround' | 'relativeToScene';
/** Offset is always added to the result of the above logic except for onTheGround where offset is ignored. */
offset: number;
/** A string value indicating the unit for the values in elevationInfo */
unit: string;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/statisticsInfo.cmn.md */
export type StatisticsInfo = {
/** Key indicating the resource of the statistics. */
key: string;
/** Name of the field of the statistical information. */
name: string;
/** The URL to the statistics information. */
href: string;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/nodePageDefinition.cmn.md */
export type NodePageDefinition = {
/** Number of nodes per page for this layer. Must be a power-of-two less than 4096 */
nodesPerPage: number;
/** Index of the root node. Default = 0. */
rootIndex?: number;
/** Defines the meaning of nodes[].lodThreshold for this layer. */
lodSelectionMetricType: 'maxScreenThresholdSQ';
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/materialDefinitions.cmn.md */
export type I3SMaterialDefinition = {
/** A set of parameter values that are used to define the metallic-roughness material model from Physically-Based Rendering (PBR) methodology. When not specified, all the default values of pbrMetallicRoughness apply. */
pbrMetallicRoughness: I3SPbrMetallicRoughness;
/** The normal texture map. */
normalTexture?: I3SMaterialTexture;
/** The occlusion texture map. */
occlusionTexture?: I3SMaterialTexture;
/** The emissive texture map. */
emissiveTexture?: I3SMaterialTexture;
/** The emissive color of the material. */
emissiveFactor?: [number, number, number];
/** Defines the meaning of the alpha-channel/alpha-mask. */
alphaMode: 'opaque' | 'mask' | 'blend';
/** The alpha cutoff value of the material. */
alphaCutoff?: number;
/** Specifies whether the material is double sided. */
doubleSided?: boolean;
/** Winding order is counterclockwise. */
cullFace?: 'none' | 'front' | 'back';
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/pbrMetallicRoughness.cmn.md */
export type I3SPbrMetallicRoughness = {
/** The material's base color factor. default=[1,1,1,1] */
baseColorFactor?: [number, number, number, number];
/** The base color texture. */
baseColorTexture?: I3SMaterialTexture;
/** the metalness of the material. default=1.0 */
metallicFactor: number;
/** the roughness of the material. default=1.0 */
roughnessFactor: number;
/** the metallic-roughness texture. */
metallicRoughnessTexture?: I3SMaterialTexture;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/materialTexture.cmn.md */
export type I3SMaterialTexture = {
/** The index in layer.textureSetDefinitions. */
textureSetDefinitionId: number;
/** The set index of texture's TEXCOORD attribute used for texture coordinate mapping. Default is 0. Deprecated. */
texCoord?: number;
/** The normal texture: scalar multiplier applied to each normal vector of the normal texture. For occlusion texture,scalar multiplier controlling the amount of occlusion applied. Default=1 */
factor?: number;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/attributeStorageInfo.cmn.md */
export type AttributeStorageInfo = {
key: string;
name: string;
header: {property: string; valueType: string}[];
ordering?: string[];
attributeValues?: AttributeValue;
attributeByteCounts?: AttributeValue;
objectIds?: AttributeValue;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/field.cmn.md */
export type Field = {
name: string;
type: ESRIField;
alias?: string;
domain?: Domain;
};
export type ESRIField =
| 'esriFieldTypeDate'
| 'esriFieldTypeSingle'
| 'esriFieldTypeDouble'
| 'esriFieldTypeGUID'
| 'esriFieldTypeGlobalID'
| 'esriFieldTypeInteger'
| 'esriFieldTypeOID'
| 'esriFieldTypeSmallInteger'
| 'esriFieldTypeString';
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/popupInfo.cmn.md */
export type PopupInfo = {
title?: string;
description?: string;
expressionInfos?: any[];
fieldInfos?: FieldInfo[];
mediaInfos?: any[];
popupElements?: {text?: string; type?: string; fieldInfos?: FieldInfo[]}[];
};
/**
* Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.7/3DNodeIndexDocument.cmn.md
*/
export type Node3DIndexDocument = {
id: string;
version?: string;
path?: string;
level?: number;
mbs?: Mbs;
obb?: Obb;
lodSelection?: LodSelection[];
children?: NodeReference[];
neighbors?: NodeReference[];
parentNode?: NodeReference;
sharedResource?: Resource;
featureData?: Resource[];
geometryData?: Resource[];
textureData?: Resource[];
attributeData?: Resource[];
created?: string;
expires?: string;
};
/**
* Minimal I3S node data is needed for loading
*/
export type I3SMinimalNodeData = {
id: string;
url?: string;
transform?: number[];
lodSelection?: LodSelection[];
obb?: Obb;
mbs?: Mbs;
contentUrl?: string;
textureUrl?: string;
attributeUrls?: string[];
materialDefinition?: I3SMaterialDefinition;
textureFormat?: I3STextureFormat;
textureLoaderOptions?: {[key: string]: any};
children?: NodeReference[];
isDracoGeometry: boolean;
};
export type LodSelection = {
metricType?: string;
maxError: number;
};
export type NodeReference = {
id: string;
version?: string;
mbs?: Mbs;
obb?: Obb;
href?: string;
};
export type Resource = {
href: string;
layerContent?: string[];
featureRange?: number[];
multiTextureBundle?: string;
vertexElements?: number[];
faceElements?: number[];
nodePath?: string;
};
export type MaxScreenThresholdSQ = {
maxError: number;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/node.cmn.md */
export type NodeInPage = {
/**
* The index in the node array. May be different than material, geometry and attribute resource id. See mesh for more information.
*/
index: number;
/**
* The index of the parent node in the node array.
*/
parentIndex?: number;
/**
* When to switch LoD. See https://github.com/Esri/i3s-spec/blob/master/docs/1.8/nodePageDefinition.cmn.md for more information.
*/
lodThreshold?: number;
/**
* Oriented bounding box for this node.
*/
obb: Obb;
/**
* index of the children nodes indices.
*/
children?: number[];
/**
* The mesh for this node. WARNING: only SINGLE mesh is supported at version 1.7 (i.e. length must be 0 or 1).
*/
mesh?: NodeMesh;
};
/**
* https://github.com/Esri/i3s-spec/blob/master/docs/1.8/materialDefinitionInfo.cmn.md
*/
export type MaterialDefinitionInfo = {
/** A name for the material as assigned in the creating application. */
name?: string;
/** Indicates the material type, chosen from the supported values. */
type?: 'standard' | 'water' | 'billboard' | 'leafcard' | 'reference';
/** The href that resolves to the shared resource bundle in which the material definition is contained. */
$ref?: string;
/** Parameter defined for the material.
* https://github.com/Esri/i3s-spec/blob/master/docs/1.8/materialParams.cmn.md
*/
params: {
/** Indicates transparency of this material; 0 = opaque, 1 = fully transparent. */
transparency?: number;
/** Indicates reflectivity of this material. */
reflectivity?: number;
/** Indicates shininess of this material. */
shininess?: number;
/** Ambient color of this material. Ambient color is the color of an object where it is in shadow.
* This color is what the object reflects when illuminated by ambient light rather than direct light. */
ambient?: number[];
/** Diffuse color of this material. Diffuse color is the most instinctive meaning of the color of an object.
* It is that essential color that the object reveals under pure white light. It is perceived as the color
* of the object itself rather than a reflection of the light. */
diffuse?: number[];
/** Specular color of this material. Specular color is the color of the light of a specular reflection
* (specular reflection is the type of reflection that is characteristic of light reflected from a shiny
* surface). */
specular?: number[];
/** Rendering mode. */
renderMode: 'textured' | 'solid' | 'untextured' | 'wireframe';
/** TRUE if features with this material should cast shadows. */
castShadows?: boolean;
/** TRUE if features with this material should receive shadows */
receiveShadows?: boolean;
/** Indicates the material culling options {back, front, none}. */
cullFace?: string;
/** This flag indicates that the vertex color attribute of the geometry should be used to color the geometry
* for rendering. If texture is present, the vertex colors are multiplied by this color.
* e.g. pixel_color = [interpolated]vertex_color * texel_color. Default is false. */
vertexColors?: boolean;
/** This flag indicates that the geometry has uv region vertex attributes. These are used for adressing
* subtextures in a texture atlas. The uv coordinates are relative to this subtexture in this case.
* This is mostly useful for repeated textures in a texture atlas. Default is false. */
vertexRegions?: boolean;
/** Indicates whether Vertex Colors also contain a transparency channel. Default is false. */
useVertexColorAlpha?: boolean;
};
};
/** https://github.com/Esri/i3s-spec/blob/master/docs/1.8/sharedResource.cmn.md */
export type SharedResources = {
/** Materials describe how a Feature or a set of Features is to be rendered. */
materialDefinitions?: {[key: string]: MaterialDefinitionInfo};
/** A Texture is a set of images, with some parameters specific to the texture/uv mapping to geometries. */
textureDefinitions?: {[key: string]: TextureDefinitionInfo};
};
/** https://github.com/Esri/i3s-spec/blob/master/docs/1.8/image.cmn.md */
type TextureImage = {
/** A unique ID for each image. Generated using the BuildID function. */
id: string;
/** width of this image, in pixels. */
size?: number;
/** The maximum size of a single pixel in world units.
* This property is used by the client to pick the image to load and render. */
pixelInWorldUnits?: number;
/** The href to the image(s), one per encoding, in the same order as the encodings. */
href?: string[];
/** The byte offset of this image's encodings. There is one per encoding,
* in the same order as the encodings, in the block in which this texture image resides. */
byteOffset?: string[];
/** The length in bytes of this image's encodings. There is one per encoding,
* in the same order as the encodings. */
length?: number[];
};
export type Attribute = 'OBJECTID' | 'string' | 'double' | 'Int32' | string;
export type Extent = [number, number, number, number];
export type FeatureAttribute = {
id: AttributeValue;
faceRange: AttributeValue;
};
export type BuildingSceneLayerTileset = {
header: BuildingSceneLayer;
sublayers: BuildingSceneSublayer[];
};
export type BuildingSceneLayer = {
id: number;
name: string;
version: string;
alias?: string;
layerType: 'Building';
description?: string;
copyrightText?: string;
fullExtent: FullExtent;
spatialReference: SpatialReference;
heightModelInfo?: HeightModelInfo;
sublayers: BuildingSceneSublayer[];
filters?: Filter[];
activeFilterID?: string;
statisticsHRef?: string;
};
export type BuildingSceneSublayer = {
id: number;
name: string;
alias?: string;
discipline?: 'Mechanical' | 'Architectural' | 'Piping' | 'Electrical' | 'Structural';
modelName?: string;
layerType: 'group' | '3DObject' | 'Point';
visibility?: boolean;
sublayers?: BuildingSceneSublayer[];
isEmpty?: boolean;
url?: string;
};
type Filter = {
id: string;
name: string;
description: string;
isDefaultFilter?: boolean;
isVisible?: boolean;
filterBlocks: FilterBlock[];
filterAuthoringInfo?: FilterAuthoringInfo;
};
type FilterAuthoringInfo = {
type: string;
filterBlocks: FilterBlockAuthoringInfo[];
};
type FilterBlockAuthoringInfo = {
filterTypes: FilterType[];
};
type FilterType = {
filterType: string;
filterValues: string[];
};
type FilterBlock = {
title: string;
filterMode: FilterModeSolid | FilterModeWireFrame;
filterExpression: string;
};
type Edges = {
type: string;
color: number[];
size: number;
transparency: number;
extensionLength: number;
};
type FilterModeSolid = {
type: 'solid';
};
type FilterModeWireFrame = {
type: 'wireFrame';
edges: Edges;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/spatialReference.cmn.md */
export type SpatialReference = {
/** The current WKID value of the vertical coordinate system. */
latestVcsWkid: number;
/** dentifies the current WKID value associated with the same spatial reference. */
latestWkid: number;
/** The WKID value of the vertical coordinate system. */
vcsWkid: number;
/** WKID, or Well-Known ID, of the CRS. Specify either WKID or WKT of the CRS. */
wkid: number;
/** WKT, or Well-Known Text, of the CRS. Specify either WKT or WKID of the CRS but not both. */
wkt?: string;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/fullExtent.cmn.md */
export type FullExtent = {
/** left longitude in decimal degrees */
xmin: number;
/** right longitude in decimal degrees */
xmax: number;
/** bottom latitude in decimal degrees*/
ymin: number;
/** top latitude in decimal degrees*/
ymax: number;
/** lowest elevation in meters */
zmin: number;
/** highest elevation in meters */
zmax: number;
spatialReference?: SpatialReference;
};
/**
* https://github.com/Esri/i3s-spec/blob/master/docs/1.8/textureDefinitionInfo.cmn.md
*/
export type TextureDefinitionInfo = {
/** MIMEtype - The encoding/content type that is used by all images in this map */
encoding?: string[];
/** UV wrapping modes, from {none, repeat, mirror}. */
wrap?: string[];
/** TRUE if the Map represents a texture atlas. */
atlas?: boolean;
/** The name of the UV set to be used as texture coordinates. */
uvSet?: string;
/** Indicates channels description. */
channels?: 'rbg' | 'rgba' | string;
/** An image is a binary resource, containing a single raster that can be used to texture a feature or symbol. */
images: TextureImage[];
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/domain.cmn.md */
type Domain = {
type: string;
name: string;
description?: string;
fieldType?: string;
range?: [number, number];
codedValues?: {name: string; code: string | number}[];
mergePolicy?: string;
splitPolicy?: string;
};
/**
* spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/store.cmn.md
*/
type Store = {
id: string | number;
profile: string;
version: number | string;
resourcePattern: string[];
rootNode: string;
extent: number[];
indexCRS: string;
vertexCRS: string;
normalReferenceFrame: string;
attributeEncoding: string;
textureEncoding: string[];
lodType: string;
lodModel: string;
defaultGeometrySchema: DefaultGeometrySchema;
};
/**
* Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/defaultGeometrySchema.cmn.md
*/
type DefaultGeometrySchema = {
geometryType?: 'triangles';
topology: 'PerAttributeArray' | 'Indexed';
header: HeaderAttribute[];
ordering: string[];
vertexAttributes: VertexAttribute;
faces?: VertexAttribute;
featureAttributeOrder: string[];
featureAttributes: FeatureAttribute;
// TODO Do we realy need this Property?
attributesOrder?: string[];
};
/**
* spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/headerAttribute.cmn.md
*/
export type HeaderAttribute = {
property: HeaderAttributeProperty.vertexCount | HeaderAttributeProperty.featureCount | string;
type:
| DATA_TYPE.UInt8
| DATA_TYPE.UInt16
| DATA_TYPE.UInt32
| DATA_TYPE.UInt64
| DATA_TYPE.Int16
| DATA_TYPE.Int32
| DATA_TYPE.Int64
| DATA_TYPE.Float32
| DATA_TYPE.Float64;
};
export enum HeaderAttributeProperty {
vertexCount = 'vertexCount',
featureCount = 'featureCount'
}
export type VertexAttribute = {
position: GeometryAttribute;
normal: GeometryAttribute;
uv0: GeometryAttribute;
color: GeometryAttribute;
region?: GeometryAttribute;
};
export type GeometryAttribute = {
byteOffset?: number;
valueType:
| DATA_TYPE.UInt8
| DATA_TYPE.UInt16
| DATA_TYPE.Int16
| DATA_TYPE.Int32
| DATA_TYPE.Int64
| DATA_TYPE.Float32
| DATA_TYPE.Float64;
valuesPerElement: number;
};
export type I3SMeshAttributes = {
[key: string]: I3SMeshAttribute;
};
export interface I3SMeshAttribute extends MeshAttribute {
type?: number;
metadata?: any;
}
/** https://github.com/Esri/i3s-spec/blob/master/docs/1.8/heightModelInfo.cmn.md */
type HeightModelInfo = {
heightModel: 'gravity_related_height' | 'ellipsoidal';
vertCRS: string;
heightUnit:
| 'meter'
| 'us-foot'
| 'foot'
| 'clarke-foot'
| 'clarke-yard'
| 'clarke-link'
| 'sears-yard'
| 'sears-foot'
| 'sears-chain'
| 'benoit-1895-b-chain'
| 'indian-yard'
| 'indian-1937-yard'
| 'gold-coast-foot'
| 'sears-1922-truncated-chain'
| 'us-inch'
| 'us-mile'
| 'us-yard'
| 'millimeter'
| 'decimeter'
| 'centimeter'
| 'kilometer';
};
export type TextureSetDefinitionFormats = {name: string; format: I3STextureFormat}[];
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/textureSetDefinition.cmn.md */
type TextureSetDefinition = {
formats: TextureSetDefinitionFormats;
atlas?: boolean;
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/geometryDefinition.cmn.md */
type GeometryDefinition = {
topology: 'triangle' | string;
geometryBuffers: GeometryBuffer[];
};
/** Spec - https://github.com/Esri/i3s-spec/blob/master/docs/1.8/geometryBuffer.cmn.md */
type GeometryBuffer = {
offset?: number;
position?: GeometryBufferItem;
normal?: GeometryBufferItem;
uv0?: GeometryBufferItem;
color?: GeometryBufferItem;
uvRegion?: GeometryBufferItem;
featureId?: GeometryBufferItem;
faceRange?: GeometryBufferItem;
compressedAttributes?: {encoding: string; attributes: string[]};
};
type GeometryBufferItem = {type: string; component: number; encoding?: string; binding: string};
type AttributeValue = {valueType: string; encoding?: string; valuesPerElement?: number};
export type FieldInfo = {
fieldName: string;
visible: boolean;
isEditable: boolean;
label: string;
};
export type ArcGisWebSceneData = {
header: ArcGisWebScene;
layers: OperationalLayer[];
};
/**
* ArcGis WebScene spec - https://developers.arcgis.com/web-scene-specification/objects/webscene/
*/
export type ArcGisWebScene = {
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/applicationProperties/
* Configuration of application and UI elements.
*/
applicationProperties?: any;
/**
* Operational layers contain business data which are used to make thematic scenes.
*/
operationalLayers: OperationalLayer[];
/**
* Basemaps give the web scene a geographic context.
*/
baseMap: BaseMap;
/**
* Ground defines the main surface of the web scene, based on elevation layers.
*/
ground: Ground;
/**
* An object that defines the characteristics of the vertical coordinate system used by the web scene.
*/
heightModelInfo: HeightModelInfo;
/**
* Root element in the web scene specifying a string value indicating the web scene version.
* Valid values: 1.8, 1.9, 1.10, 1.11, 1.12, 1.13, 1.14, 1.15, 1.16, 1.17, 1.18, 1.19, 1.20, 1.21, 1.22, 1.23, 1.24, 1.25, 1.26, 1.27
*/
version: string;
/**
* String value indicating the application which authored the webmap
*/
authoringApp: string;
/**
* String value indicating the authoring App's version number.
*/
authoringAppVersion: string;
/**
* A presentation consists of multiple slides, where each slide is a specific view into the web scene.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/presentation/
* @todo Add presentation type.
*/
presentation: any;
/**
* An object that provides information about the initial environment settings and viewpoint of the web scene.
*/
initialState: InitialState;
/**
* An object used to specify the spatial reference of the given geometry.
*/
spatialReference: SpatialReference;
viewingMode: 'global' | 'local';
/**
* @todo add type.
* Defines area to be clipped for display.
*/
clippingArea?: any;
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/mapFloorInfo/
* Contains floor-awareness information for the web scene.
*/
mapFloorInfo?: any;
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/mapRangeInfo/
* Map Range Information
*/
mapRangeInfo?: any;
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/table/
* An array of table objects.
*/
tables?: any;
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/transportationNetwork/
* Used to specify the transportation networks of the scene.
*/
transportationNetworks?: any;
/**
* @todo add type.
* Spec - https://developers.arcgis.com/web-scene-specification/objects/widgets/
* The widgets object contains widgets that should be exposed to the user.
*/
widgets?: any;
};
/**
* Operational layers contain your data. Usually, a basemap sits beneath your operational layers to give them geographic context.
* Spec- https://developers.arcgis.com/web-scene-specification/objects/operationalLayers/
*/
export type OperationalLayer = {
id: string;
opacity: number;
title: string;
url: string;
visibility: boolean;
itemId: string;
layerType: string;
LayerDefinition: LayerDefinition;
screenSizePerspective: boolean;
showLabels?: boolean;
disablePopup?: boolean;
showLegend?: boolean;
layers?: OperationalLayer[];
};
type LayerDefinition = {
elevationInfo: ElevationInfo;
drawingInfo: DrawingInfo;
};
type BaseMap = {
id: string;
title: string;
baseMapLayers: BaseMapLayer[];
elevationLayers: ElevationLayer[];
};
type BaseMapLayer = {
id: string;
opacity: number;
title: string;
url: string;
visibility: boolean;
layerType: string;
};
type ElevationLayer = {
id: string;
listMode: string;
title: string;
url: string;
visibility: boolean;
layerType: string;
};
type Ground = {
layers: ElevationLayer[];
transparency: number;
navigationConstraint: NavigationConstraint;
};
type NavigationConstraint = {
type: string;
};
type InitialState = {
environment: Enviroment;
viewpoint: ViewPoint;
};
type Enviroment = {
lighting: Lighting;
atmosphereEnabled?: string;
starsEnabled?: string;
};
type Lighting = {
datetime?: number;
displayUTCOffset?: number;
};
type ViewPoint = {
camera: Camera;
};
type Camera = {
position: CameraPosition;
heading: number;
tilt: number;
};
type CameraPosition = {
spatialReference: SpatialReference;
x: number;
y: number;
z: number;
}; | the_stack |
import {
Component,
JSXComponent,
RefObject,
Ref,
Mutable,
Method,
Effect,
InternalState,
} from '@devextreme-generator/declarations';
import { DisposeEffectReturn } from '../../../utils/effect_return.d';
import { BaseWidgetProps } from '../../common/base_props';
import { Scrollbar } from './scrollbar';
import { requestAnimationFrame, cancelAnimationFrame } from '../../../../animation/frame';
import { ScrollableSimulatedProps } from '../common/simulated_strategy_props';
import { inRange } from '../../../../core/utils/math';
import { DxMouseEvent } from '../common/types.d';
import { clampIntoRange } from '../utils/clamp_into_range';
import { AnimatedScrollbarProps } from '../common/animated_scrollbar_props';
import { isDxMouseWheelEvent } from '../../../../events/utils/index';
export const OUT_BOUNDS_ACCELERATION = 0.5;
export const ACCELERATION = 0.92;
export const MIN_VELOCITY_LIMIT = 1;
export const BOUNCE_MIN_VELOCITY_LIMIT = MIN_VELOCITY_LIMIT / 5;
const FRAME_DURATION = 17; // Math.round(1000 / 60)
const BOUNCE_DURATION = 400;
const BOUNCE_FRAMES = BOUNCE_DURATION / FRAME_DURATION;
export const BOUNCE_ACCELERATION_SUM = (1 - ACCELERATION ** BOUNCE_FRAMES) / (1 - ACCELERATION);
export const viewFunction = (viewModel: AnimatedScrollbar): JSX.Element => {
const {
scrollbarRef,
props: {
direction,
contentSize, containerSize,
showScrollbar, scrollByThumb, bounceEnabled,
scrollLocation, scrollLocationChange,
visible, rtlEnabled,
containerHasSizes,
minOffset, maxOffset,
},
} = viewModel;
return (
<Scrollbar
ref={scrollbarRef}
direction={direction}
contentSize={contentSize}
containerSize={containerSize}
containerHasSizes={containerHasSizes}
visible={visible}
minOffset={minOffset}
maxOffset={maxOffset}
scrollLocation={scrollLocation}
scrollLocationChange={scrollLocationChange}
scrollByThumb={scrollByThumb}
bounceEnabled={bounceEnabled}
showScrollbar={showScrollbar}
// Horizontal
rtlEnabled={rtlEnabled}
/>
);
};
type AnimatedScrollbarPropsType = AnimatedScrollbarProps
// eslint-disable-next-line @typescript-eslint/no-type-alias
& Pick<BaseWidgetProps, 'rtlEnabled'>
// eslint-disable-next-line @typescript-eslint/no-type-alias
& Pick<ScrollableSimulatedProps, 'pullDownEnabled' | 'reachBottomEnabled' | 'forceGeneratePockets'
| 'inertiaEnabled' | 'showScrollbar' | 'scrollByThumb' | 'bounceEnabled' | 'scrollLocationChange'>;
@Component({
defaultOptionRules: null,
view: viewFunction,
})
export class AnimatedScrollbar extends JSXComponent<AnimatedScrollbarPropsType>() {
@Ref() scrollbarRef!: RefObject<Scrollbar>;
@Mutable() thumbScrolling = false;
@Mutable() crossThumbScrolling = false;
@Mutable() stepAnimationFrame = 0;
@Mutable() finished = true;
@Mutable() stopped = false;
@Mutable() velocity = 0;
@Mutable() animator = 'inertia';
@Mutable() refreshing = false;
@Mutable() loading = false;
@InternalState() forceAnimationToBottomBound = false;
@InternalState() pendingRefreshing = false;
@InternalState() pendingLoading = false;
@InternalState() pendingBounceAnimator = false;
@InternalState() pendingInertiaAnimator = false;
@InternalState() needRiseEnd = false;
@InternalState() wasRelease = false;
@Method()
isThumb(element: EventTarget | null): boolean {
return this.scrollbarRef.current!.isThumb(element);
}
@Method()
isScrollbar(element: EventTarget | null): boolean {
return this.scrollbarRef.current!.isScrollbar(element);
}
@Method()
reachedMin(): boolean {
return this.props.scrollLocation <= this.maxOffset;
}
@Method()
reachedMax(): boolean {
return this.props.scrollLocation >= this.props.minOffset;
}
@Method()
initHandler(
event: DxMouseEvent,
crossThumbScrolling: boolean,
offset: number,
): void {
this.cancel();
this.refreshing = false;
this.loading = false;
if (!isDxMouseWheelEvent(event.originalEvent)) {
this.calcThumbScrolling(event, crossThumbScrolling);
this.scrollbarRef.current!.initHandler(event, this.thumbScrolling, offset);
}
}
@Method()
moveHandler(delta: number): void {
if (this.crossThumbScrolling) {
return;
}
this.scrollbarRef.current!.moveHandler(delta,
this.props.minOffset, this.maxOffset, this.thumbScrolling);
}
@Method()
endHandler(velocity: number, needRiseEnd: boolean): void {
this.start('inertia', velocity, this.thumbScrolling, this.crossThumbScrolling);
this.needRiseEnd = needRiseEnd;
this.resetThumbScrolling();
}
@Method()
stopHandler(): void {
if (this.thumbScrolling) {
this.needRiseEnd = true;
}
this.resetThumbScrolling();
}
@Method()
scrollTo(value: number): void {
this.loading = false;
this.refreshing = false;
this.scrollbarRef.current!.moveTo(-clampIntoRange(value, -this.maxOffset, 0));
this.needRiseEnd = true;
}
@Method()
releaseHandler(): void {
if (this.props.forceGeneratePockets && this.props.reachBottomEnabled
&& inRange(this.props.scrollLocation, this.maxOffset, this.props.maxOffset)) {
this.forceAnimationToBottomBound = true;
}
this.wasRelease = true;
this.needRiseEnd = true;
this.resetThumbScrolling();
this.pendingRefreshing = false;
this.pendingLoading = false;
}
@Effect({ run: 'once' })
disposeAnimationFrame(): DisposeEffectReturn {
return (): void => { this.cancel(); };
}
@Effect()
/* istanbul ignore next */
risePullDown(): void {
if (
this.props.forceGeneratePockets
&& this.needRiseEnd
&& this.inRange
&& !(this.pendingBounceAnimator || this.pendingInertiaAnimator)
&& this.props.pulledDown
&& !this.pendingRefreshing
&& !this.refreshing
&& -this.props.maxOffset > 0
) {
this.refreshing = true;
this.pendingRefreshing = true;
this.props.onPullDown?.();
}
}
@Effect()
/* istanbul ignore next */
riseEnd(): void {
if (
this.inBounds
&& this.needRiseEnd
&& this.finished
&& !(this.pendingBounceAnimator || this.pendingInertiaAnimator)
&& !this.pendingRelease
&& !(this.pendingRefreshing || this.pendingLoading)
) {
this.needRiseEnd = false;
this.wasRelease = false;
this.props.onUnlock?.();
this.forceAnimationToBottomBound = false;
this.props.onEnd?.(this.props.direction);
}
}
@Effect()
/* istanbul ignore next */
riseReachBottom(): void {
if (
this.props.forceGeneratePockets
&& this.needRiseEnd
&& this.inRange
&& !(this.pendingBounceAnimator || this.pendingInertiaAnimator)
&& this.isReachBottom
&& !this.pendingLoading
&& !this.loading
&& -this.props.maxOffset > 0
) {
this.loading = true;
this.pendingLoading = true;
this.props.onReachBottom?.();
}
}
@Effect()
/* istanbul ignore next */
bounceAnimatorStart(): void {
if (
!this.inRange
&& this.needRiseEnd
&& !(this.pendingBounceAnimator || this.pendingInertiaAnimator)
&& !(this.pendingRefreshing || this.pendingLoading)
&& -this.props.maxOffset > 0
) {
this.start('bounce');
}
}
@Effect()
updateLockedState(): void {
if (this.pendingBounceAnimator || this.pendingRefreshing || this.pendingLoading) {
this.props.onLock?.();
}
}
get pendingRelease(): boolean {
return ((this.props.pulledDown && this.props.pullDownEnabled)
|| (this.isReachBottom && this.props.reachBottomEnabled)) && !this.wasRelease;
}
resetThumbScrolling(): void {
this.thumbScrolling = false;
this.crossThumbScrolling = false;
}
get inRange(): boolean {
return inRange(this.props.scrollLocation, this.maxOffset, this.props.minOffset);
}
/* istanbul ignore next */
get inBounds(): boolean {
return inRange(this.props.scrollLocation, this.props.maxOffset, 0);
}
get isReachBottom(): boolean {
// T1032842
// when sizes is decimal and a rounding error of about 1px
// scrollLocation = 72.3422123432px | maxOffset = 73px
return this.props.reachBottomEnabled
&& Math.round(this.props.scrollLocation - this.props.maxOffset) <= 1;
}
start(animatorName: 'inertia' | 'bounce', receivedVelocity?: number, thumbScrolling?: boolean, crossThumbScrolling?: boolean): void {
this.animator = animatorName;
if (this.isBounceAnimator) {
this.pendingBounceAnimator = true;
this.props.onBounce?.();
this.setupBounce();
} else {
this.pendingInertiaAnimator = true;
if (!thumbScrolling && crossThumbScrolling) {
this.velocity = 0;
} else {
this.velocity = receivedVelocity ?? 0;
}
this.suppressInertia(thumbScrolling);
}
this.stopped = false;
this.finished = false;
this.stepCore();
}
cancel(): void {
this.pendingBounceAnimator = false;
this.pendingInertiaAnimator = false;
this.stopped = true;
cancelAnimationFrame(this.stepAnimationFrame);
}
stepCore(): void {
if (this.stopped) {
return;
}
if (this.isFinished) {
this.finished = true;
this.complete();
return;
}
this.step();
this.stepAnimationFrame = this.getStepAnimationFrame();
}
/* istanbul ignore next */
getStepAnimationFrame(): number {
return requestAnimationFrame(this.stepCore.bind(this));
}
step(): void {
if (!this.props.bounceEnabled && (this.reachedMin() || this.reachedMax())) {
this.velocity = 0;
}
this.scrollStep(this.velocity, this.props.minOffset, this.maxOffset);
this.velocity *= this.acceleration;
}
setupBounce(): void {
const { scrollLocation } = this.props;
const bounceDistance = clampIntoRange(
scrollLocation, this.props.minOffset, this.maxOffset,
) - scrollLocation;
this.velocity = bounceDistance / BOUNCE_ACCELERATION_SUM;
}
complete(): void {
if (this.isBounceAnimator) {
const boundaryLocation = clampIntoRange(
this.props.scrollLocation, this.props.minOffset, this.maxOffset,
);
this.moveTo(boundaryLocation);
}
this.stopAnimator();
}
get isBounceAnimator(): boolean {
return this.animator === 'bounce';
}
get isFinished(): boolean {
if (this.isBounceAnimator) {
return this.crossBoundOnNextStep()
|| Math.abs(this.velocity) <= BOUNCE_MIN_VELOCITY_LIMIT;
}
return Math.abs(this.velocity) <= MIN_VELOCITY_LIMIT;
}
get inProgress(): boolean {
return !(this.stopped || this.finished);
}
get acceleration(): number {
return this.isBounceAnimator || this.inRange
? ACCELERATION
: OUT_BOUNDS_ACCELERATION;
}
get maxOffset(): number {
if (this.props.forceGeneratePockets
&& this.props.reachBottomEnabled && !this.forceAnimationToBottomBound) {
return this.props.maxOffset - this.props.bottomPocketSize - this.props.contentPaddingBottom;
}
return this.props.maxOffset;
}
suppressInertia(thumbScrolling?: boolean): void {
if (!this.props.inertiaEnabled || thumbScrolling) {
this.velocity = 0;
}
}
/* istanbul ignore next */
crossBoundOnNextStep(): boolean {
const location = this.props.scrollLocation;
const nextLocation = location + this.velocity;
return (location <= this.maxOffset && nextLocation >= this.maxOffset)
|| (location >= this.props.minOffset && nextLocation <= this.props.minOffset);
}
scrollStep(delta: number, minOffset: number, maxOffset: number): void {
this.scrollbarRef.current!.scrollStep(delta, minOffset, maxOffset) as undefined;
}
moveTo(location: number): void {
this.scrollbarRef.current!.moveTo(location);
}
stopAnimator(): void {
// May be animator is single
this.pendingBounceAnimator = false;
this.pendingInertiaAnimator = false;
}
calcThumbScrolling(event: DxMouseEvent, currentCrossThumbScrolling: boolean): void {
const { target } = event.originalEvent;
const scrollbarClicked = this.props.scrollByThumb && this.isScrollbar(target);
this.thumbScrolling = scrollbarClicked || (this.props.scrollByThumb && this.isThumb(target));
this.crossThumbScrolling = !this.thumbScrolling && currentCrossThumbScrolling;
}
// https://trello.com/c/6TBHZulk/2672-renovation-cannot-use-getter-to-get-access-to-components-methods-react
// get scrollbar(): any { // set Scrollbar type is technical limitation in the generator
// return this.scrollbarRef.current!;
// }
} | the_stack |
import {
BuiltinTypes, createRefToElmWithValue, CORE_ANNOTATIONS, ElemID, ObjectType, createRestriction, ListType,
} from '@salto-io/adapter-api'
import * as constants from '../../../constants'
import { enums } from '../enums'
export const suiteletInnerTypes: ObjectType[] = []
const suiteletElemID = new ElemID(constants.NETSUITE, 'suitelet')
const suitelet_customplugintypes_plugintypeElemID = new ElemID(constants.NETSUITE, 'suitelet_customplugintypes_plugintype')
const suitelet_customplugintypes_plugintype = new ObjectType({
elemID: suitelet_customplugintypes_plugintypeElemID,
annotations: {
},
fields: {
plugintype: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the plugintype custom type. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_customplugintypes_plugintype)
const suitelet_customplugintypesElemID = new ElemID(constants.NETSUITE, 'suitelet_customplugintypes')
const suitelet_customplugintypes = new ObjectType({
elemID: suitelet_customplugintypesElemID,
annotations: {
},
fields: {
plugintype: {
refType: createRefToElmWithValue(new ListType(suitelet_customplugintypes_plugintype)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_customplugintypes)
const suitelet_libraries_libraryElemID = new ElemID(constants.NETSUITE, 'suitelet_libraries_library')
const suitelet_libraries_library = new ObjectType({
elemID: suitelet_libraries_libraryElemID,
annotations: {
},
fields: {
scriptfile: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was filereference */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field must reference a .js file. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_libraries_library)
const suitelet_librariesElemID = new ElemID(constants.NETSUITE, 'suitelet_libraries')
const suitelet_libraries = new ObjectType({
elemID: suitelet_librariesElemID,
annotations: {
},
fields: {
library: {
refType: createRefToElmWithValue(new ListType(suitelet_libraries_library)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_libraries)
const suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilterElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter')
const suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter = new ObjectType({
elemID: suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilterElemID,
annotations: {
},
fields: {
fldfilter: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the following custom types: transactioncolumncustomfield transactionbodycustomfield othercustomfield itemoptioncustomfield itemnumbercustomfield itemcustomfield entitycustomfield customrecordcustomfield crmcustomfield For information about other possible values, see generic_standard_field. */
fldfilterchecked: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldfiltercomparetype: {
refType: createRefToElmWithValue(enums.generic_customfield_fldfiltercomparetype),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_fldfiltercomparetype. The default value is 'EQ'. */
fldfiltersel: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. This field accepts references to the following custom types: scriptdeployment workflowactionscript workflowstatecustomfield workflowcustomfield workflow scriptdeployment usereventscript transactioncolumncustomfield transactionbodycustomfield transactionForm scriptdeployment suitelet scriptdeployment scheduledscript savedsearch role scriptdeployment restlet scriptdeployment portlet othercustomfield scriptdeployment massupdatescript scriptdeployment mapreducescript itemoptioncustomfield itemnumbercustomfield itemcustomfield entryForm entitycustomfield statuses customtransactiontype instance customrecordcustomfield customrecordtype customvalue crmcustomfield scriptdeployment clientscript scriptdeployment bundleinstallationscript advancedpdftemplate addressForm */
fldfilterval: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
fldfilternotnull: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldfilternull: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
fldcomparefield: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the following custom types: transactioncolumncustomfield transactionbodycustomfield othercustomfield itemoptioncustomfield itemnumbercustomfield itemcustomfield entitycustomfield customrecordcustomfield crmcustomfield For information about other possible values, see generic_standard_field. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter)
const suitelet_scriptcustomfields_scriptcustomfield_customfieldfiltersElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters')
const suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters = new ObjectType({
elemID: suitelet_scriptcustomfields_scriptcustomfield_customfieldfiltersElemID,
annotations: {
},
fields: {
customfieldfilter: {
refType: createRefToElmWithValue(new ListType(suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters_customfieldfilter)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters)
const suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccessElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess')
const suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess = new ObjectType({
elemID: suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccessElemID,
annotations: {
},
fields: {
role: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field accepts references to the role custom type. For information about other possible values, see customrecordtype_permittedrole. */
accesslevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '0'. */
searchlevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '0'. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess)
const suitelet_scriptcustomfields_scriptcustomfield_roleaccessesElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields_scriptcustomfield_roleaccesses')
const suitelet_scriptcustomfields_scriptcustomfield_roleaccesses = new ObjectType({
elemID: suitelet_scriptcustomfields_scriptcustomfield_roleaccessesElemID,
annotations: {
},
fields: {
roleaccess: {
refType: createRefToElmWithValue(new ListType(suitelet_scriptcustomfields_scriptcustomfield_roleaccesses_roleaccess)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields_scriptcustomfield_roleaccesses)
const suitelet_scriptcustomfields_scriptcustomfieldElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields_scriptcustomfield')
const suitelet_scriptcustomfields_scriptcustomfield = new ObjectType({
elemID: suitelet_scriptcustomfields_scriptcustomfieldElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘custscript’. */
fieldtype: {
refType: createRefToElmWithValue(enums.generic_customfield_fieldtype),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_customfield_fieldtype. The default value is 'TEXT'. */
label: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 200 }),
},
}, /* Original description: This field value can be up to 200 characters long. This field accepts references to the string custom type. */
selectrecordtype: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field is mandatory when the fieldtype value is equal to any of the following lists or values: SELECT, MULTISELECT. This field accepts references to the following custom types: customrecordtype customlist For information about other possible values, see generic_customfield_selectrecordtype. */
applyformatting: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
defaultchecked: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
defaultselection: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the following custom types: scriptdeployment workflowactionscript workflowstatecustomfield workflowcustomfield workflow scriptdeployment usereventscript transactioncolumncustomfield transactionbodycustomfield transactionForm scriptdeployment suitelet scriptdeployment scheduledscript savedsearch role scriptdeployment restlet scriptdeployment portlet othercustomfield scriptdeployment massupdatescript scriptdeployment mapreducescript itemoptioncustomfield itemnumbercustomfield itemcustomfield entryForm entitycustomfield statuses customtransactiontype instance customrecordcustomfield customrecordtype customvalue crmcustomfield scriptdeployment clientscript scriptdeployment bundleinstallationscript advancedpdftemplate addressForm */
defaultvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
description: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
displaytype: {
refType: createRefToElmWithValue(enums.generic_customfield_displaytype),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_displaytype. The default value is 'NORMAL'. */
dynamicdefault: {
refType: createRefToElmWithValue(enums.generic_customfield_dynamicdefault),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_dynamicdefault. */
help: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the string custom type. */
linktext: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
minvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
maxvalue: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
storevalue: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
accesslevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '2'. */
checkspelling: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
displayheight: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
},
}, /* Original description: This field value must be greater than or equal to 0. */
displaywidth: {
refType: createRefToElmWithValue(BuiltinTypes.NUMBER),
annotations: {
},
}, /* Original description: This field value must be greater than or equal to 0. */
isformula: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
ismandatory: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
maxlength: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
onparentdelete: {
refType: createRefToElmWithValue(enums.generic_customfield_onparentdelete),
annotations: {
},
}, /* Original description: For information about possible values, see generic_customfield_onparentdelete. */
searchcomparefield: {
refType: createRefToElmWithValue(enums.generic_standard_field),
annotations: {
},
}, /* Original description: For information about possible values, see generic_standard_field. */
searchdefault: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the savedsearch custom type. */
searchlevel: {
refType: createRefToElmWithValue(enums.generic_accesslevel_searchlevel),
annotations: {
},
}, /* Original description: For information about possible values, see generic_accesslevel_searchlevel. The default value is '2'. */
setting: {
refType: createRefToElmWithValue(enums.script_setting),
annotations: {
},
}, /* Original description: For information about possible values, see script_setting. */
customfieldfilters: {
refType: createRefToElmWithValue(suitelet_scriptcustomfields_scriptcustomfield_customfieldfilters),
annotations: {
},
},
roleaccesses: {
refType: createRefToElmWithValue(suitelet_scriptcustomfields_scriptcustomfield_roleaccesses),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields_scriptcustomfield)
const suitelet_scriptcustomfieldsElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptcustomfields')
const suitelet_scriptcustomfields = new ObjectType({
elemID: suitelet_scriptcustomfieldsElemID,
annotations: {
},
fields: {
scriptcustomfield: {
refType: createRefToElmWithValue(new ListType(suitelet_scriptcustomfields_scriptcustomfield)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptcustomfields)
const suitelet_scriptdeployments_scriptdeployment_links_linkElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptdeployments_scriptdeployment_links_link')
const suitelet_scriptdeployments_scriptdeployment_links_link = new ObjectType({
elemID: suitelet_scriptdeployments_scriptdeployment_links_linkElemID,
annotations: {
},
fields: {
linkcategory: {
refType: createRefToElmWithValue(enums.generic_centercategory),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see generic_centercategory. */
linktasktype: {
refType: createRefToElmWithValue(enums.suiteletdeployment_tasktype),
annotations: {
},
}, /* Original description: For information about possible values, see suiteletdeployment_tasktype. */
linklabel: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the string custom type. */
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptdeployments_scriptdeployment_links_link)
const suitelet_scriptdeployments_scriptdeployment_linksElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptdeployments_scriptdeployment_links')
const suitelet_scriptdeployments_scriptdeployment_links = new ObjectType({
elemID: suitelet_scriptdeployments_scriptdeployment_linksElemID,
annotations: {
},
fields: {
link: {
refType: createRefToElmWithValue(new ListType(suitelet_scriptdeployments_scriptdeployment_links_link)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptdeployments_scriptdeployment_links)
const suitelet_scriptdeployments_scriptdeploymentElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptdeployments_scriptdeployment')
const suitelet_scriptdeployments_scriptdeployment = new ObjectType({
elemID: suitelet_scriptdeployments_scriptdeploymentElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘customdeploy’. */
status: {
refType: createRefToElmWithValue(enums.script_status),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: For information about possible values, see script_status. The default value is 'TESTING'. */
title: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
},
allemployees: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
allpartners: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. If this field appears in the project, you must reference the CRM feature in the manifest file to avoid project warnings. In the manifest file, you can specify whether this feature is required in your account. CRM must be enabled for this field to appear in your account. */
allroles: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
auddepartment: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. If this field appears in the project, you must reference the DEPARTMENTS feature in the manifest file to avoid project warnings. In the manifest file, you can specify whether this feature is required in your account. DEPARTMENTS must be enabled for this field to appear in your account. Note Account-specific values are not supported by SDF. */
audemployee: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. Note Account-specific values are not supported by SDF. */
audgroup: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. Note Account-specific values are not supported by SDF. */
audpartner: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. If this field appears in the project, you must reference the CRM feature in the manifest file to avoid project warnings. In the manifest file, you can specify whether this feature is required in your account. CRM must be enabled for this field to appear in your account. Note Account-specific values are not supported by SDF. */
audslctrole: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. This field accepts references to the role custom type. For information about other possible values, see generic_role. */
audsubsidiary: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was multi-select list */),
annotations: {
},
}, /* Original description: You can specify multiple values by separating each value with a pipe (|) symbol. If this field appears in the project, you must reference the SUBSIDIARIES feature in the manifest file to avoid project warnings. In the manifest file, you can specify whether this feature is required in your account. SUBSIDIARIES must be enabled for this field to appear in your account. Note Account-specific values are not supported by SDF. */
eventtype: {
refType: createRefToElmWithValue(enums.script_eventtype),
annotations: {
},
}, /* Original description: For information about possible values, see script_eventtype. */
isdeployed: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
isonline: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
loglevel: {
refType: createRefToElmWithValue(enums.script_loglevel),
annotations: {
},
}, /* Original description: For information about possible values, see script_loglevel. The default value is 'DEBUG'. */
runasrole: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
},
}, /* Original description: This field accepts references to the role custom type. For information about other possible values, see generic_role. */
links: {
refType: createRefToElmWithValue(suitelet_scriptdeployments_scriptdeployment_links),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptdeployments_scriptdeployment)
const suitelet_scriptdeploymentsElemID = new ElemID(constants.NETSUITE, 'suitelet_scriptdeployments')
export const suitelet_scriptdeployments = new ObjectType({
elemID: suitelet_scriptdeploymentsElemID,
annotations: {
},
fields: {
scriptdeployment: {
refType: createRefToElmWithValue(new ListType(suitelet_scriptdeployments_scriptdeployment)),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
})
suiteletInnerTypes.push(suitelet_scriptdeployments)
export const suitelet = new ObjectType({
elemID: suiteletElemID,
annotations: {
},
fields: {
scriptid: {
refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[constants.IS_ATTRIBUTE]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ regex: '^customscript[0-9a-z_]+' }),
},
}, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘customscript’. */
name: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 40 }),
},
}, /* Original description: This field value can be up to 40 characters long. This field accepts references to the string custom type. */
scriptfile: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was filereference */),
annotations: {
[CORE_ANNOTATIONS.REQUIRED]: true,
},
}, /* Original description: This field must reference a .js file. */
defaultfunction: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
},
description: {
refType: createRefToElmWithValue(BuiltinTypes.STRING /* Original type was single-select list */),
annotations: {
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 999 }),
},
}, /* Original description: This field value can be up to 999 characters long. This field accepts references to the string custom type. */
isinactive: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
notifyadmins: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
notifyemails: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
[CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ max_length: 999 }),
},
}, /* Original description: This field value can be up to 999 characters long. */
notifygroup: {
refType: createRefToElmWithValue(BuiltinTypes.STRING),
annotations: {
},
}, /* Original description: Note Account-specific values are not supported by SDF. */
notifyowner: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is T. */
notifyuser: {
refType: createRefToElmWithValue(BuiltinTypes.BOOLEAN),
annotations: {
},
}, /* Original description: The default value is F. */
customplugintypes: {
refType: createRefToElmWithValue(suitelet_customplugintypes),
annotations: {
},
},
libraries: {
refType: createRefToElmWithValue(suitelet_libraries),
annotations: {
},
},
scriptcustomfields: {
refType: createRefToElmWithValue(suitelet_scriptcustomfields),
annotations: {
},
},
scriptdeployments: {
refType: createRefToElmWithValue(suitelet_scriptdeployments),
annotations: {
},
},
},
path: [constants.NETSUITE, constants.TYPES_PATH, suiteletElemID.name],
}) | the_stack |
import { addComponent, addEntity, IComponent, removeComponent } from "bitecs";
import { vec3, quat, mat4 } from "gl-matrix";
import { maxEntities, NOOP } from "../config.common";
import { GameState, World } from "../GameTypes";
import { registerEditorComponent } from "../editor/editor.game";
import { ComponentPropertyType } from "./types";
import { createObjectBufferView } from "../allocator/ObjectBufferView";
import { hierarchyObjectBufferSchema, worldMatrixObjectBufferSchema } from "./transform.common";
export interface Transform extends IComponent {
position: Float32Array[];
rotation: Float32Array[];
quaternion: Float32Array[];
scale: Float32Array[];
localMatrix: Float32Array[];
worldMatrix: Float32Array[];
static: Uint8Array;
worldMatrixNeedsUpdate: Uint8Array;
parent: Uint32Array;
firstChild: Uint32Array;
prevSibling: Uint32Array;
nextSibling: Uint32Array;
hierarchyUpdated: Uint8Array;
}
export const gameObjectBuffer = createObjectBufferView(
{
position: [Float32Array, maxEntities, 3],
scale: [Float32Array, maxEntities, 3],
rotation: [Float32Array, maxEntities, 3],
quaternion: [Float32Array, maxEntities, 4],
localMatrix: [Float32Array, maxEntities, 16],
static: [Uint8Array, maxEntities],
},
ArrayBuffer
);
export const worldMatrixObjectBuffer = createObjectBufferView(worldMatrixObjectBufferSchema, ArrayBuffer);
export const hierarchyObjectBuffer = createObjectBufferView(hierarchyObjectBufferSchema, ArrayBuffer);
export const Transform: Transform = {
position: gameObjectBuffer.position,
scale: gameObjectBuffer.scale,
rotation: gameObjectBuffer.rotation,
quaternion: gameObjectBuffer.quaternion,
localMatrix: gameObjectBuffer.localMatrix,
static: gameObjectBuffer.static,
worldMatrix: worldMatrixObjectBuffer.worldMatrix,
worldMatrixNeedsUpdate: worldMatrixObjectBuffer.worldMatrixNeedsUpdate,
parent: hierarchyObjectBuffer.parent,
firstChild: hierarchyObjectBuffer.firstChild,
prevSibling: hierarchyObjectBuffer.prevSibling,
nextSibling: hierarchyObjectBuffer.nextSibling,
hierarchyUpdated: hierarchyObjectBuffer.hierarchyUpdated,
};
export function registerTransformComponent(state: GameState) {
registerEditorComponent(state, Transform, {
name: "Transform",
props: {
position: {
type: ComponentPropertyType.vec3,
store: Transform.position,
},
},
add(state, eid, props) {
addTransformComponent(state.world, eid);
if (props && props.position) {
Transform.position[eid].set(props.position);
}
},
remove(state, eid) {
removeComponent(state.world, Transform, eid);
},
});
}
export function addTransformComponent(world: World, eid: number) {
addComponent(world, Transform, eid);
vec3.set(Transform.scale[eid], 1, 1, 1);
quat.identity(Transform.quaternion[eid]);
mat4.identity(Transform.localMatrix[eid]);
mat4.identity(Transform.worldMatrix[eid]);
Transform.worldMatrixNeedsUpdate[eid] = 1;
Transform.hierarchyUpdated[eid] = 1;
}
export function createTransformEntity(world: World) {
const eid = addEntity(world);
addTransformComponent(world, eid);
return eid;
}
export function getLastChild(eid: number): number {
let cursor = Transform.firstChild[eid];
let last = cursor;
while (cursor) {
last = cursor;
cursor = Transform.nextSibling[cursor];
}
return last;
}
export function getChildAt(eid: number, index: number): number {
let cursor = Transform.firstChild[eid];
if (cursor) {
for (let i = 1; i <= index; i++) {
cursor = Transform.nextSibling[cursor];
if (!cursor) {
return 0;
}
}
}
return cursor;
}
export function addChild(parent: number, child: number) {
Transform.parent[child] = parent;
const lastChild = getLastChild(parent);
if (lastChild) {
Transform.nextSibling[lastChild] = child;
Transform.prevSibling[child] = lastChild;
Transform.nextSibling[child] = NOOP;
} else {
Transform.firstChild[parent] = child;
Transform.prevSibling[child] = NOOP;
Transform.nextSibling[child] = NOOP;
}
}
export function removeChild(parent: number, child: number) {
const prevSibling = Transform.prevSibling[child];
const nextSibling = Transform.nextSibling[child];
const firstChild = Transform.firstChild[parent];
if (firstChild === child) {
Transform.firstChild[parent] = NOOP;
}
// [prev, child, next]
if (prevSibling !== NOOP && nextSibling !== NOOP) {
Transform.nextSibling[prevSibling] = nextSibling;
Transform.prevSibling[nextSibling] = prevSibling;
}
// [prev, child]
if (prevSibling !== NOOP && nextSibling === NOOP) {
Transform.nextSibling[prevSibling] = NOOP;
}
// [child, next]
if (nextSibling !== NOOP && prevSibling === NOOP) {
Transform.prevSibling[nextSibling] = NOOP;
Transform.firstChild[parent] = nextSibling;
}
Transform.parent[child] = NOOP;
Transform.nextSibling[child] = NOOP;
Transform.prevSibling[child] = NOOP;
}
export const updateWorldMatrix = (eid: number, updateParents: boolean, updateChildren: boolean) => {
const parent = Transform.parent[eid];
if (updateParents === true && parent !== NOOP) {
updateWorldMatrix(parent, true, false);
}
if (!Transform.static[eid]) updateMatrix(eid);
if (parent === NOOP) {
Transform.worldMatrix[eid].set(Transform.localMatrix[eid]);
} else {
mat4.multiply(Transform.worldMatrix[eid], Transform.worldMatrix[parent], Transform.localMatrix[eid]);
}
// update children
if (updateChildren) {
let nextChild = Transform.firstChild[eid];
while (nextChild) {
updateWorldMatrix(nextChild, false, true);
nextChild = Transform.nextSibling[nextChild];
}
}
};
export const updateMatrixWorld = (eid: number, force = false) => {
if (!Transform.static[eid]) updateMatrix(eid);
if (Transform.worldMatrixNeedsUpdate[eid] || force) {
const parent = Transform.parent[eid];
if (parent === NOOP) {
Transform.worldMatrix[eid].set(Transform.localMatrix[eid]);
} else {
mat4.multiply(Transform.worldMatrix[eid], Transform.worldMatrix[parent], Transform.localMatrix[eid]);
}
// Transform.worldMatrixNeedsUpdate[eid] = 0;
force = true;
}
let nextChild = Transform.firstChild[eid];
while (nextChild) {
updateMatrixWorld(nextChild, force);
nextChild = Transform.nextSibling[nextChild];
}
};
export const updateMatrix = (eid: number) => {
const position = Transform.position[eid];
const quaternion = Transform.quaternion[eid];
const scale = Transform.scale[eid];
mat4.fromRotationTranslationScale(Transform.localMatrix[eid], quaternion, position, scale);
Transform.worldMatrixNeedsUpdate[eid] = 1;
};
const { sin, cos } = Math;
const EulerOrder = ["XYZ", "YZX", "ZXY", "XZY", "YXZ", "ZYX"];
export const setQuaternionFromEuler = (quaternion: quat, rotation: vec3) => {
const [x, y, z, o] = rotation;
const order = EulerOrder[o] || "XYZ";
const c1 = cos(x / 2);
const c2 = cos(y / 2);
const c3 = cos(z / 2);
const s1 = sin(x / 2);
const s2 = sin(y / 2);
const s3 = sin(z / 2);
switch (order) {
case "XYZ":
quaternion[0] = s1 * c2 * c3 + c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 - s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 + s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "YXZ":
quaternion[0] = s1 * c2 * c3 + c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 - s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 - s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case "ZXY":
quaternion[0] = s1 * c2 * c3 - c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 + s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 + s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "ZYX":
quaternion[0] = s1 * c2 * c3 - c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 + s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 - s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
case "YZX":
quaternion[0] = s1 * c2 * c3 + c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 + s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 - s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 - s1 * s2 * s3;
break;
case "XZY":
quaternion[0] = s1 * c2 * c3 - c1 * s2 * s3;
quaternion[1] = c1 * s2 * c3 - s1 * c2 * s3;
quaternion[2] = c1 * c2 * s3 + s1 * s2 * c3;
quaternion[3] = c1 * c2 * c3 + s1 * s2 * s3;
break;
}
};
export function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(max, value));
}
export function setEulerFromTransformMatrix(rotation: vec3, matrix: mat4) {
const order = EulerOrder[rotation[3]] || "XYZ";
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
const te = matrix;
const m11 = te[0];
const m12 = te[4];
const m13 = te[8];
const m21 = te[1];
const m22 = te[5];
const m23 = te[9];
const m31 = te[2];
const m32 = te[6];
const m33 = te[10];
switch (order) {
case "XYZ":
rotation[1] = Math.asin(clamp(m13, -1, 1));
if (Math.abs(m13) < 0.9999999) {
rotation[0] = Math.atan2(-m23, m33);
rotation[2] = Math.atan2(-m12, m11);
} else {
rotation[0] = Math.atan2(m32, m22);
rotation[2] = 0;
}
break;
case "YXZ":
rotation[0] = Math.asin(-clamp(m23, -1, 1));
if (Math.abs(m23) < 0.9999999) {
rotation[1] = Math.atan2(m13, m33);
rotation[2] = Math.atan2(m21, m22);
} else {
rotation[1] = Math.atan2(-m31, m11);
rotation[2] = 0;
}
break;
case "ZXY":
rotation[0] = Math.asin(clamp(m32, -1, 1));
if (Math.abs(m32) < 0.9999999) {
rotation[1] = Math.atan2(-m31, m33);
rotation[2] = Math.atan2(-m12, m22);
} else {
rotation[1] = 0;
rotation[2] = Math.atan2(m21, m11);
}
break;
case "ZYX":
rotation[1] = Math.asin(-clamp(m31, -1, 1));
if (Math.abs(m31) < 0.9999999) {
rotation[0] = Math.atan2(m32, m33);
rotation[2] = Math.atan2(m21, m11);
} else {
rotation[0] = 0;
rotation[2] = Math.atan2(-m12, m22);
}
break;
case "YZX":
rotation[2] = Math.asin(clamp(m21, -1, 1));
if (Math.abs(m21) < 0.9999999) {
rotation[0] = Math.atan2(-m23, m22);
rotation[1] = Math.atan2(-m31, m11);
} else {
rotation[0] = 0;
rotation[1] = Math.atan2(m13, m33);
}
break;
case "XZY":
rotation[2] = Math.asin(-clamp(m12, -1, 1));
if (Math.abs(m12) < 0.9999999) {
rotation[0] = Math.atan2(m32, m22);
rotation[1] = Math.atan2(m13, m11);
} else {
rotation[0] = Math.atan2(-m23, m33);
rotation[1] = 0;
}
break;
}
}
const tempMat4 = mat4.create();
const tempVec3 = vec3.create();
const tempQuat = quat.create();
const defaultUp = vec3.set(vec3.create(), 0, 1, 0);
export function setEulerFromQuaternion(rotation: Float32Array, quaternion: Float32Array) {
mat4.fromQuat(tempMat4, quaternion);
setEulerFromTransformMatrix(rotation, tempMat4);
}
export function lookAt(eid: number, targetVec: vec3, upVec: vec3 = defaultUp) {
updateWorldMatrix(eid, true, false);
mat4.getTranslation(tempVec3, Transform.worldMatrix[eid]);
mat4.lookAt(tempMat4, tempVec3, targetVec, upVec);
const parent = Transform.parent[eid];
mat4.getRotation(Transform.quaternion[eid], tempMat4);
if (parent !== NOOP) {
mat4.getRotation(tempQuat, Transform.worldMatrix[parent]);
quat.invert(tempQuat, tempQuat);
quat.mul(Transform.quaternion[eid], tempQuat, Transform.quaternion[eid]);
setEulerFromQuaternion(Transform.rotation[eid], Transform.quaternion[eid]);
} else {
setEulerFromTransformMatrix(Transform.rotation[eid], tempMat4);
}
}
export function traverse(rootEid: number, callback: (eid: number) => void) {
let eid = rootEid;
// eslint-disable-next-line no-constant-condition
while (true) {
callback(eid);
const firstChild = Transform.firstChild[eid];
if (firstChild) {
eid = firstChild;
} else {
while (!Transform.nextSibling[eid]) {
if (eid === rootEid) {
return;
}
eid = Transform.parent[eid];
}
eid = Transform.nextSibling[eid];
}
}
}
export function* getChildren(parentEid: number): Generator<number, number> {
let eid = Transform.firstChild[parentEid];
while (eid) {
yield eid;
eid = Transform.nextSibling[eid];
}
return 0;
}
export function getDirection(out: vec3, matrix: mat4): vec3 {
vec3.set(out, matrix[8], matrix[9], matrix[10]);
return vec3.normalize(out, out);
} | the_stack |
import { computeDifference } from '@meetalva/util';
import { isEqual, flatMap } from 'lodash';
import * as Mobx from 'mobx';
import { Pattern, PatternSlot } from '../pattern';
import { ElementContent } from '../element';
import {
AnyPatternProperty,
PatternEnumProperty,
PatternProperty,
PatternPropertyBase,
EnumValue
} from '../pattern-property';
import { Project } from '../project';
import * as Types from '@meetalva/types';
import * as uuid from 'uuid';
const md5 = require('md5');
export interface PatternLibraryInit {
builtin: boolean;
bundleId: string;
bundle: string;
id: string;
installType: Types.PatternLibraryInstallType;
origin: Types.PatternLibraryOrigin;
packageFile: {
name: string;
version: string;
[key: string]: unknown;
};
patternProperties: AnyPatternProperty[];
patterns: Pattern[];
state: Types.PatternLibraryState;
}
export interface BuiltInContext {
options: PatternLibraryCreateOptions;
patternLibrary: PatternLibrary;
}
export interface BuiltInResult {
pattern: Pattern;
properties: AnyPatternProperty[];
}
export interface PatternLibraryCreateOptions {
getGlobalEnumOptionId(enumId: string, contextId: string): string;
getGlobalPatternId(contextId: string): string;
getGlobalPropertyId(patternId: string, contextId: string): string;
getGlobalSlotId(patternId: string, contextId: string): string;
}
export class PatternLibrary {
public readonly model = Types.ModelName.PatternLibrary;
public readonly builtin: boolean;
private readonly id: string;
@Mobx.observable private bundleId: string;
@Mobx.observable private bundle: string;
@Mobx.observable private installType: Types.PatternLibraryInstallType;
@Mobx.observable private origin: Types.PatternLibraryOrigin;
@Mobx.observable
private packageFile: {
name: string;
version: string;
[key: string]: unknown;
};
@Mobx.observable private patternProperties: Map<string, AnyPatternProperty> = new Map();
@Mobx.observable private patterns: Map<string, Pattern> = new Map();
@Mobx.observable private state: Types.PatternLibraryState;
@Mobx.computed
private get version(): string {
return this.packageFile.version;
}
@Mobx.computed
private get name(): string {
return this.packageFile.name;
}
@Mobx.computed
private get alvaMeta(): { [key: string]: unknown } {
return typeof this.packageFile.alva === 'object' && this.packageFile.alva !== null
? this.packageFile.alva
: {};
}
@Mobx.computed
private get slots(): PatternSlot[] {
return this.getPatterns().reduce<PatternSlot[]>(
(acc, pattern) => [...acc, ...pattern.getSlots()],
[]
);
}
@Mobx.computed
public get contextId(): string {
return [this.name, this.version].join('@');
}
public constructor(init: PatternLibraryInit) {
this.builtin = init.builtin;
this.bundleId = init.bundleId;
this.bundle = init.bundle;
this.id = init.id || uuid.v4();
this.installType = init.installType;
this.origin = init.origin;
this.packageFile = init.packageFile;
init.patterns.forEach(pattern => this.patterns.set(pattern.getId(), pattern));
init.patternProperties.forEach(prop => this.patternProperties.set(prop.getId(), prop));
this.state = init.state;
}
public static Defaults() {
return {
builtin: false,
bundleId: uuid.v4(),
bundle: '',
id: uuid.v4(),
installType: Types.PatternLibraryInstallType.Local,
origin: Types.PatternLibraryOrigin.UserProvided,
packageFile: {
name: 'component-library',
version: '1.0.0'
},
patterns: [],
patternProperties: [],
state: Types.PatternLibraryState.Connected
};
}
public static create(init: PatternLibraryInit): PatternLibrary {
return new PatternLibrary(init);
}
public static fromAnalysis(
analysis: Types.LibraryAnalysis,
opts: {
analyzeBuiltins: boolean;
project?: Project;
installType: Types.PatternLibraryInstallType;
}
): PatternLibrary {
const library = PatternLibrary.create({
builtin: opts.analyzeBuiltins,
bundle: analysis.bundle,
bundleId: analysis.id,
id: uuid.v4(),
installType: opts.installType,
origin: opts.analyzeBuiltins
? Types.PatternLibraryOrigin.BuiltIn
: Types.PatternLibraryOrigin.UserProvided,
packageFile: analysis.packageFile,
patternProperties: [],
patterns: [],
state: Types.PatternLibraryState.Connected
});
library.import(analysis, { project: opts.project });
return library;
}
public static from(serialized: Types.SerializedPatternLibrary): PatternLibrary {
const state = deserializeState(serialized.state);
const builtin =
typeof serialized.builtin === 'undefined'
? serialized.patterns.some(p => p.type === Types.PatternType.SyntheticPage)
: serialized.builtin;
const patternLibrary = new PatternLibrary({
builtin,
bundleId: serialized.bundleId,
bundle: serialized.bundle,
id: serialized.id,
installType: serialized.installType,
origin: deserializeOrigin(serialized.origin),
packageFile: serialized.packageFile,
patterns: [],
patternProperties: serialized.patternProperties.map(p => PatternProperty.from(p)),
state
});
serialized.patterns.forEach(pattern => {
patternLibrary.addPattern(Pattern.from(pattern, { patternLibrary }));
});
return patternLibrary;
}
public static fromDefaults(): PatternLibrary {
return new PatternLibrary(PatternLibrary.Defaults());
}
@Mobx.action
public import(analysis: Types.LibraryAnalysis, { project }: { project?: Project }): void {
this.packageFile = analysis.packageFile;
const patternsBefore = this.getPatterns();
const patternsAfter = analysis.patterns.map(item =>
Pattern.from(item.pattern, { patternLibrary: this })
);
const patternChanges = computeDifference({
before: patternsBefore,
after: patternsAfter
});
patternChanges.removed.map(change => {
this.removePattern(change.before);
});
patternChanges.added.map(change => {
this.addPattern(change.after);
});
patternChanges.changed.map(change => {
change.before.update(change.after, { patternLibrary: this });
});
const propMap: Map<string, Pattern> = new Map();
const props = analysis.patterns.reduce((p: AnyPatternProperty[], patternAnalysis) => {
const pattern = Pattern.from(patternAnalysis.pattern, { patternLibrary: this });
patternAnalysis.properties.forEach(prop => {
const patternProperty = PatternProperty.from(prop);
p.push(patternProperty);
propMap.set(patternProperty.getId(), pattern);
});
return p;
}, []);
const propChanges = computeDifference({
before: this.getPatternProperties(),
after: props
});
propChanges.removed.map(change => {
this.removeProperty(change.before);
});
propChanges.added.map(change => {
const pattern = propMap.get(change.after.getId());
const p = pattern ? this.getPatternById(pattern.getId()) : undefined;
this.addProperty(change.after);
if (p) {
p.addProperty(change.after);
}
});
propChanges.changed.map(change => change.before.update(change.after));
if (project) {
const touchedPatterns = [...patternChanges.added, ...patternChanges.changed].map(
change => change.after
);
// TODO: This might be solved via a bigger refactoring that
// computes available element contents from pattern slots directly
touchedPatterns.forEach(pattern => {
project.getElementsByPattern(pattern).forEach(element => {
const contents = element.getContents();
pattern
.getSlots()
// Check if there is a corresponding element content for each pattern slot
.filter(slot => !contents.some(content => content.getSlotId() === slot.getId()))
.forEach(slot => {
// No element content, create a new one and add it to element
const content = ElementContent.fromSlot(slot, { project });
content.setParentElement(element);
element.addContent(content);
project.addElementContent(content);
});
});
});
}
this.setState(Types.PatternLibraryState.Connected);
this.setBundle(analysis.bundle);
this.setBundleId(analysis.id);
}
public equals(b: PatternLibrary): boolean {
return isEqual(this.toJSON(), b.toJSON());
}
@Mobx.action
public addPattern(pattern: Pattern): void {
this.patterns.set(pattern.getId(), pattern);
}
@Mobx.action
public addProperty(property: AnyPatternProperty): void {
this.patternProperties.set(property.getId(), property);
}
public getPatternByProperty(property: AnyPatternProperty): Pattern | undefined {
return this.getPatterns().find(p =>
p.getProperties().some(p => p.getId() === property.getId())
);
}
public getPatternBySlot(slot: PatternSlot): Pattern | undefined {
return this.getPatterns().find(p => p.getSlots().some(s => s.getId() === slot.getId()));
}
public getDescription(): string | undefined {
return typeof this.packageFile.description === 'string'
? this.packageFile.description
: undefined;
}
public getBundle(): string {
return this.bundle;
}
public getBundleId(): string {
return this.bundleId;
}
public getBundleHash(): string {
return md5(this.bundle);
}
public getColor(): string | undefined {
return typeof this.alvaMeta.color === 'string' ? this.alvaMeta.color : undefined;
}
public getCapabilites(): Types.LibraryCapability[] {
const isUserProvided = this.origin === Types.PatternLibraryOrigin.UserProvided;
if (!isUserProvided) {
return [];
}
const isConnected = this.state === Types.PatternLibraryState.Connected;
return [
isConnected && Types.LibraryCapability.Disconnect,
isConnected && Types.LibraryCapability.Update,
isConnected && Types.LibraryCapability.SetPath,
Types.LibraryCapability.Reconnect
].filter(
(capability): capability is Types.LibraryCapability => typeof capability !== 'undefined'
);
}
public getId(): string {
return this.id;
}
public getName(): string {
return this.name;
}
public getDisplayName(): string | undefined {
return typeof this.alvaMeta.name === 'string' ? this.alvaMeta.name : this.name;
}
public getPackageName(): string {
return this.name;
}
public getVersion(): string {
return this.version;
}
public getHomepage(): string | undefined {
return typeof this.packageFile.homepage === 'string' ? this.packageFile.homepage : undefined;
}
public getOrigin(): Types.PatternLibraryOrigin {
return this.origin;
}
public getPatternByContextId(contextId: string): Pattern | undefined {
return this.getPatterns().find(pattern => pattern.getContextId() === contextId);
}
public getPatternById(id: string): Pattern | undefined {
return this.patterns.get(id);
}
public getPatternByType(type: Types.PatternType): Pattern {
return this.getPatterns().find(pattern => pattern.getType() === type)!;
}
public getPatternProperties(): AnyPatternProperty[] {
return [...this.patternProperties.values()];
}
public getPatternPropertyById(id: string): AnyPatternProperty | undefined {
return this.patternProperties.get(id);
}
public getPatternSlotById(id: string): PatternSlot | undefined {
return this.getSlots().find(slot => slot.getId() === id);
}
public getPatterns(ids?: string[]): Pattern[] {
if (typeof ids === 'undefined') {
return [...this.patterns.values()];
}
return ids
.map(id => this.getPatternById(id))
.filter((pattern): pattern is Pattern => typeof pattern !== 'undefined');
}
public getSlots(): PatternSlot[] {
return this.slots;
}
public getState(): Types.PatternLibraryState {
return this.state;
}
public getImage(): string | undefined {
return typeof this.alvaMeta.image === 'string' ? this.alvaMeta.image : undefined;
}
public getInstallType(): Types.PatternLibraryInstallType {
if (this.origin === Types.PatternLibraryOrigin.BuiltIn) {
return Types.PatternLibraryInstallType.Remote;
}
return this.installType;
}
@Mobx.action
public removePattern(pattern: Pattern): void {
this.patterns.delete(pattern.getId());
}
@Mobx.action
public removeProperty(property: AnyPatternProperty): void {
this.patternProperties.delete(property.getId());
}
@Mobx.action
public setBundle(bundle: string): void {
this.bundle = bundle;
}
@Mobx.action
public setBundleId(bundleId: string): void {
this.bundleId = bundleId;
}
@Mobx.action
public setState(state: Types.PatternLibraryState): void {
this.state = state;
}
@Mobx.action
public setInstallType(installType: Types.PatternLibraryInstallType): void {
this.installType = installType;
}
public toJSON(): Types.SerializedPatternLibrary {
return {
bundleId: this.bundleId,
bundle: this.bundle,
id: this.id,
installType: this.installType,
model: this.model,
origin: serializeOrigin(this.origin),
packageFile: this.packageFile,
patternProperties: this.getPatternProperties().map(p => p.toJSON()),
patterns: this.getPatterns().map(p => p.toJSON()),
state: this.state
};
}
@Mobx.action
public update(b: PatternLibrary): void {
this.bundleId = b.bundleId;
this.bundle = b.bundle;
this.origin = b.origin;
this.installType = b.installType;
this.packageFile = b.packageFile;
const patternChanges = computeDifference<Pattern>({
before: this.getPatterns(),
after: b.getPatterns()
});
patternChanges.added.forEach(change => this.addPattern(change.after));
patternChanges.changed.forEach(change =>
change.before.update(change.after, { patternLibrary: this })
);
patternChanges.removed.forEach(change => this.removePattern(change.before));
const propertyChanges = computeDifference<AnyPatternProperty>({
before: this.getPatternProperties(),
after: b.getPatternProperties()
});
propertyChanges.added.forEach(change => this.addProperty(change.after));
propertyChanges.changed.forEach(change => change.before.update(change.after));
propertyChanges.removed.forEach(change => this.removeProperty(change.before));
}
}
function deserializeState(
input: 'pristine' | 'connected' | 'disconnected' | 'connecting'
): Types.PatternLibraryState {
switch (input) {
case 'pristine':
return Types.PatternLibraryState.Pristine;
case 'connecting':
return Types.PatternLibraryState.Connecting;
case 'connected':
return Types.PatternLibraryState.Connected;
case 'disconnected':
return Types.PatternLibraryState.Disconnected;
}
}
function deserializeOrigin(
input: Types.SerializedPatternLibraryOrigin
): Types.PatternLibraryOrigin {
switch (input) {
case 'built-in':
return Types.PatternLibraryOrigin.BuiltIn;
case 'user-provided':
return Types.PatternLibraryOrigin.UserProvided;
}
throw new Error(`Unknown pattern library origin: ${input}`);
}
function serializeOrigin(input: Types.PatternLibraryOrigin): Types.SerializedPatternLibraryOrigin {
switch (input) {
case Types.PatternLibraryOrigin.BuiltIn:
return 'built-in';
case Types.PatternLibraryOrigin.UserProvided:
return 'user-provided';
}
throw new Error(`Unknown pattern library origin: ${input}`);
} | the_stack |
import React from 'react';
import Link from '@docusaurus/Link';
import Translate, {translate} from '@docusaurus/Translate';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import Image from '@theme/IdealImage';
import Layout from '@theme/Layout';
import clsx from 'clsx';
import styles from './styles.module.css';
const QUOTES = [
{
thumbnail: require('../data/quotes/christopher-chedeau.jpg'),
name: 'Christopher "vjeux" Chedeau',
title: translate({
id: 'homepage.quotes.christopher-chedeau.title',
message: 'Lead Prettier Developer',
description: 'Title of quote of Christopher Chedeau on the home page',
}),
text: (
<Translate
id="homepage.quotes.christopher-chedeau"
description="Quote of Christopher Chedeau on the home page">
I've helped open source many projects at Facebook and every one
needed a website. They all had very similar constraints: the
documentation should be written in markdown and be deployed via GitHub
pages. I’m so glad that Docusaurus now exists so that I don’t have to
spend a week each time spinning up a new one.
</Translate>
),
},
{
thumbnail: require('../data/quotes/hector-ramos.jpg'),
name: 'Hector Ramos',
title: translate({
id: 'homepage.quotes.hector-ramos.title',
message: 'Lead React Native Advocate',
description: 'Title of quote of Hector Ramos on the home page',
}),
text: (
<Translate
id="homepage.quotes.hector-ramos"
description="Quote of Hector Ramos on the home page">
Open source contributions to the React Native docs have skyrocketed
after our move to Docusaurus. The docs are now hosted on a small repo in
plain markdown, with none of the clutter that a typical static site
generator would require. Thanks Slash!
</Translate>
),
},
{
thumbnail: require('../data/quotes/ricky-vetter.jpg'),
name: 'Ricky Vetter',
title: translate({
id: 'homepage.quotes.risky-vetter.title',
message: 'ReasonReact Developer',
description: 'Title of quote of Ricky Vetter on the home page',
}),
text: (
<Translate
id="homepage.quotes.risky-vetter"
description="Quote of Ricky Vetter on the home page">
Docusaurus has been a great choice for the ReasonML family of projects.
It makes our documentation consistent, i18n-friendly, easy to maintain,
and friendly for new contributors.
</Translate>
),
},
];
function Home() {
const {
siteConfig: {
customFields: {description},
tagline,
},
} = useDocusaurusContext();
return (
<Layout title={tagline} description={description as string}>
<main>
<div className={styles.hero}>
<div className={styles.heroInner}>
<h1 className={styles.heroProjectTagline}>
<img
alt={translate({message: 'Docusaurus with Keytar'})}
className={styles.heroLogo}
src={useBaseUrl('/img/docusaurus_keytar.svg')}
/>
<span
className={styles.heroTitleTextHtml}
dangerouslySetInnerHTML={{
__html: translate({
id: 'homepage.hero.title',
message:
'Build <b>optimized</b> websites <b>quickly</b>, focus on your <b>content</b>',
description:
'Home page hero title, can contain simple html tags',
}),
}}
/>
</h1>
<div className={styles.indexCtas}>
<Link className="button button--primary" to="/docs">
<Translate>Get Started</Translate>
</Link>
<Link className="button button--info" to="https://docusaurus.new">
<Translate>Playground</Translate>
</Link>
<span className={styles.indexCtasGitHubButtonWrapper}>
<iframe
className={styles.indexCtasGitHubButton}
src="https://ghbtns.com/github-btn.html?user=facebook&repo=docusaurus&type=star&count=true&size=large"
width={160}
height={30}
title="GitHub Stars"
/>
</span>
</div>
</div>
</div>
<div className={clsx(styles.announcement, styles.announcementDark)}>
<div className={styles.announcementInner}>
<Translate
values={{
docusaurusV1Link: (
<Link to="https://v1.docusaurus.io/">
<Translate>Docusaurus v1</Translate>
</Link>
),
migrationGuideLink: (
<Link to="/docs/migration">
<Translate>v1 to v2 migration guide</Translate>
</Link>
),
}}>
{`Coming from {docusaurusV1Link}? Check out our {migrationGuideLink}`}
</Translate>
.
</div>
</div>
<div className={styles.section}>
<div className="container text--center margin-bottom--xl">
<div className="row">
<div className="col">
<img
className={styles.featureImage}
alt="Powered by MDX"
src={useBaseUrl('/img/undraw_typewriter.svg')}
/>
<h2 className={clsx(styles.featureHeading)}>
<Translate>Powered by Markdown</Translate>
</h2>
<p className="padding-horiz--md">
<Translate>
Save time and focus on your project's documentation. Simply
write docs and blog posts with Markdown/MDX and Docusaurus
will publish a set of static HTML files ready to serve. You
can even embed JSX components into your Markdown thanks to
MDX.
</Translate>
</p>
</div>
<div className="col">
<img
alt="Built Using React"
className={styles.featureImage}
src={useBaseUrl('/img/undraw_react.svg')}
/>
<h2 className={clsx(styles.featureHeading)}>
<Translate>Built Using React</Translate>
</h2>
<p className="padding-horiz--md">
<Translate>
Extend or customize your project's layout by reusing React.
Docusaurus can be extended while reusing the same header and
footer.
</Translate>
</p>
</div>
<div className="col">
<img
alt="Ready for Translations"
className={styles.featureImage}
src={useBaseUrl('/img/undraw_around_the_world.svg')}
/>
<h2 className={clsx(styles.featureHeading)}>
<Translate>Ready for Translations</Translate>
</h2>
<p className="padding-horiz--md">
<Translate>
Localization comes pre-configured. Use Crowdin to translate
your docs into over 70 languages.
</Translate>
</p>
</div>
</div>
</div>
<div className="container text--center">
<div className="row">
<div className="col col--4 col--offset-2">
<img
alt="Document Versioning"
className={styles.featureImage}
src={useBaseUrl('/img/undraw_version_control.svg')}
/>
<h2 className={clsx(styles.featureHeading)}>
<Translate>Document Versioning</Translate>
</h2>
<p className="padding-horiz--md">
<Translate>
Support users on all versions of your project. Document
versioning helps you keep documentation in sync with project
releases.
</Translate>
</p>
</div>
<div className="col col--4">
<img
alt="Document Search"
className={styles.featureImage}
src={useBaseUrl('/img/undraw_algolia.svg')}
/>
<h2 className={clsx(styles.featureHeading)}>
<Translate>Content Search</Translate>
</h2>
<p className="padding-horiz--md">
<Translate>
Make it easy for your community to find what they need in
your documentation. We proudly support Algolia documentation
search.
</Translate>
</p>
</div>
</div>
</div>
</div>
<div className={clsx(styles.section, styles.sectionAlt)}>
<div className="container">
<div className="row">
{QUOTES.map((quote) => (
<div className="col" key={quote.name}>
<div className="avatar avatar--vertical margin-bottom--sm">
<Image
alt={quote.name}
className="avatar__photo avatar__photo--xl"
img={quote.thumbnail}
style={{overflow: 'hidden'}}
/>
<div className="avatar__intro padding-top--sm">
<div className="avatar__name">{quote.name}</div>
<small className="avatar__subtitle">{quote.title}</small>
</div>
</div>
<p className="text--center text--italic padding-horiz--md">
{quote.text}
</p>
</div>
))}
</div>
</div>
</div>
</main>
</Layout>
);
}
export default Home; | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://www.googleapis.com/discovery/v1/apis/games/v1/rest
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Play Game Services API v1 */
function load(name: "games", version: "v1"): PromiseLike<void>;
function load(name: "games", version: "v1", callback: () => any): void;
const achievementDefinitions: games.AchievementDefinitionsResource;
const achievements: games.AchievementsResource;
const applications: games.ApplicationsResource;
const events: games.EventsResource;
const leaderboards: games.LeaderboardsResource;
const metagame: games.MetagameResource;
const players: games.PlayersResource;
const pushtokens: games.PushtokensResource;
const questMilestones: games.QuestMilestonesResource;
const quests: games.QuestsResource;
const revisions: games.RevisionsResource;
const rooms: games.RoomsResource;
const scores: games.ScoresResource;
const snapshots: games.SnapshotsResource;
const turnBasedMatches: games.TurnBasedMatchesResource;
namespace games {
interface AchievementDefinition {
/**
* The type of the achievement.
* Possible values are:
* - "STANDARD" - Achievement is either locked or unlocked.
* - "INCREMENTAL" - Achievement is incremental.
*/
achievementType?: string;
/** The description of the achievement. */
description?: string;
/** Experience points which will be earned when unlocking this achievement. */
experiencePoints?: string;
/** The total steps for an incremental achievement as a string. */
formattedTotalSteps?: string;
/** The ID of the achievement. */
id?: string;
/**
* The initial state of the achievement.
* Possible values are:
* - "HIDDEN" - Achievement is hidden.
* - "REVEALED" - Achievement is revealed.
* - "UNLOCKED" - Achievement is unlocked.
*/
initialState?: string;
/** Indicates whether the revealed icon image being returned is a default image, or is provided by the game. */
isRevealedIconUrlDefault?: boolean;
/** Indicates whether the unlocked icon image being returned is a default image, or is game-provided. */
isUnlockedIconUrlDefault?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementDefinition. */
kind?: string;
/** The name of the achievement. */
name?: string;
/** The image URL for the revealed achievement icon. */
revealedIconUrl?: string;
/** The total steps for an incremental achievement. */
totalSteps?: number;
/** The image URL for the unlocked achievement icon. */
unlockedIconUrl?: string;
}
interface AchievementDefinitionsListResponse {
/** The achievement definitions. */
items?: AchievementDefinition[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementDefinitionsListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface AchievementIncrementResponse {
/** The current steps recorded for this incremental achievement. */
currentSteps?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementIncrementResponse. */
kind?: string;
/** Whether the current steps for the achievement has reached the number of steps required to unlock. */
newlyUnlocked?: boolean;
}
interface AchievementRevealResponse {
/**
* The current state of the achievement for which a reveal was attempted. This might be UNLOCKED if the achievement was already unlocked.
* Possible values are:
* - "REVEALED" - Achievement is revealed.
* - "UNLOCKED" - Achievement is unlocked.
*/
currentState?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementRevealResponse. */
kind?: string;
}
interface AchievementSetStepsAtLeastResponse {
/** The current steps recorded for this incremental achievement. */
currentSteps?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementSetStepsAtLeastResponse. */
kind?: string;
/** Whether the the current steps for the achievement has reached the number of steps required to unlock. */
newlyUnlocked?: boolean;
}
interface AchievementUnlockResponse {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementUnlockResponse. */
kind?: string;
/** Whether this achievement was newly unlocked (that is, whether the unlock request for the achievement was the first for the player). */
newlyUnlocked?: boolean;
}
interface AchievementUpdateMultipleRequest {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementUpdateMultipleRequest. */
kind?: string;
/** The individual achievement update requests. */
updates?: AchievementUpdateRequest[];
}
interface AchievementUpdateMultipleResponse {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementUpdateListResponse. */
kind?: string;
/** The updated state of the achievements. */
updatedAchievements?: AchievementUpdateResponse[];
}
interface AchievementUpdateRequest {
/** The achievement this update is being applied to. */
achievementId?: string;
/** The payload if an update of type INCREMENT was requested for the achievement. */
incrementPayload?: GamesAchievementIncrement;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementUpdateRequest. */
kind?: string;
/** The payload if an update of type SET_STEPS_AT_LEAST was requested for the achievement. */
setStepsAtLeastPayload?: GamesAchievementSetStepsAtLeast;
/**
* The type of update being applied.
* Possible values are:
* - "REVEAL" - Achievement is revealed.
* - "UNLOCK" - Achievement is unlocked.
* - "INCREMENT" - Achievement is incremented.
* - "SET_STEPS_AT_LEAST" - Achievement progress is set to at least the passed value.
*/
updateType?: string;
}
interface AchievementUpdateResponse {
/** The achievement this update is was applied to. */
achievementId?: string;
/**
* The current state of the achievement.
* Possible values are:
* - "HIDDEN" - Achievement is hidden.
* - "REVEALED" - Achievement is revealed.
* - "UNLOCKED" - Achievement is unlocked.
*/
currentState?: string;
/** The current steps recorded for this achievement if it is incremental. */
currentSteps?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#achievementUpdateResponse. */
kind?: string;
/** Whether this achievement was newly unlocked (that is, whether the unlock request for the achievement was the first for the player). */
newlyUnlocked?: boolean;
/** Whether the requested updates actually affected the achievement. */
updateOccurred?: boolean;
}
interface AggregateStats {
/** The number of messages sent between a pair of peers. */
count?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#aggregateStats. */
kind?: string;
/** The maximum amount. */
max?: string;
/** The minimum amount. */
min?: string;
/** The total number of bytes sent for messages between a pair of peers. */
sum?: string;
}
interface AnonymousPlayer {
/** The base URL for the image to display for the anonymous player. */
avatarImageUrl?: string;
/** The name to display for the anonymous player. */
displayName?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#anonymousPlayer. */
kind?: string;
}
interface Application {
/** The number of achievements visible to the currently authenticated player. */
achievement_count?: number;
/** The assets of the application. */
assets?: ImageAsset[];
/** The author of the application. */
author?: string;
/** The category of the application. */
category?: ApplicationCategory;
/** The description of the application. */
description?: string;
/**
* A list of features that have been enabled for the application.
* Possible values are:
* - "SNAPSHOTS" - Snapshots has been enabled
*/
enabledFeatures?: string[];
/** The ID of the application. */
id?: string;
/** The instances of the application. */
instances?: Instance[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#application. */
kind?: string;
/** The last updated timestamp of the application. */
lastUpdatedTimestamp?: string;
/** The number of leaderboards visible to the currently authenticated player. */
leaderboard_count?: number;
/** The name of the application. */
name?: string;
/** A hint to the client UI for what color to use as an app-themed color. The color is given as an RGB triplet (e.g. "E0E0E0"). */
themeColor?: string;
}
interface ApplicationCategory {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#applicationCategory. */
kind?: string;
/** The primary category. */
primary?: string;
/** The secondary category. */
secondary?: string;
}
interface ApplicationVerifyResponse {
/** An alternate ID that was once used for the player that was issued the auth token used in this request. (This field is not normally populated.) */
alternate_player_id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#applicationVerifyResponse. */
kind?: string;
/** The ID of the player that was issued the auth token used in this request. */
player_id?: string;
}
interface Category {
/** The category name. */
category?: string;
/** Experience points earned in this category. */
experiencePoints?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#category. */
kind?: string;
}
interface CategoryListResponse {
/** The list of categories with usage data. */
items?: Category[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#categoryListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface EventBatchRecordFailure {
/**
* The cause for the update failure.
* Possible values are:
* - "TOO_LARGE": A batch request was issued with more events than are allowed in a single batch.
* - "TIME_PERIOD_EXPIRED": A batch was sent with data too far in the past to record.
* - "TIME_PERIOD_SHORT": A batch was sent with a time range that was too short.
* - "TIME_PERIOD_LONG": A batch was sent with a time range that was too long.
* - "ALREADY_UPDATED": An attempt was made to record a batch of data which was already seen.
* - "RECORD_RATE_HIGH": An attempt was made to record data faster than the server will apply updates.
*/
failureCause?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventBatchRecordFailure. */
kind?: string;
/** The time range which was rejected; empty for a request-wide failure. */
range?: EventPeriodRange;
}
interface EventChild {
/** The ID of the child event. */
childId?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventChild. */
kind?: string;
}
interface EventDefinition {
/** A list of events that are a child of this event. */
childEvents?: EventChild[];
/** Description of what this event represents. */
description?: string;
/** The name to display for the event. */
displayName?: string;
/** The ID of the event. */
id?: string;
/** The base URL for the image that represents the event. */
imageUrl?: string;
/** Indicates whether the icon image being returned is a default image, or is game-provided. */
isDefaultImageUrl?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventDefinition. */
kind?: string;
/**
* The visibility of event being tracked in this definition.
* Possible values are:
* - "REVEALED": This event should be visible to all users.
* - "HIDDEN": This event should only be shown to users that have recorded this event at least once.
*/
visibility?: string;
}
interface EventDefinitionListResponse {
/** The event definitions. */
items?: EventDefinition[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventDefinitionListResponse. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
}
interface EventPeriodRange {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventPeriodRange. */
kind?: string;
/** The time when this update period ends, in millis, since 1970 UTC (Unix Epoch). */
periodEndMillis?: string;
/** The time when this update period begins, in millis, since 1970 UTC (Unix Epoch). */
periodStartMillis?: string;
}
interface EventPeriodUpdate {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventPeriodUpdate. */
kind?: string;
/** The time period being covered by this update. */
timePeriod?: EventPeriodRange;
/** The updates being made for this time period. */
updates?: EventUpdateRequest[];
}
interface EventRecordFailure {
/** The ID of the event that was not updated. */
eventId?: string;
/**
* The cause for the update failure.
* Possible values are:
* - "NOT_FOUND" - An attempt was made to set an event that was not defined.
* - "INVALID_UPDATE_VALUE" - An attempt was made to increment an event by a non-positive value.
*/
failureCause?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventRecordFailure. */
kind?: string;
}
interface EventRecordRequest {
/** The current time when this update was sent, in milliseconds, since 1970 UTC (Unix Epoch). */
currentTimeMillis?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventRecordRequest. */
kind?: string;
/** The request ID used to identify this attempt to record events. */
requestId?: string;
/** A list of the time period updates being made in this request. */
timePeriods?: EventPeriodUpdate[];
}
interface EventUpdateRequest {
/** The ID of the event being modified in this update. */
definitionId?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventUpdateRequest. */
kind?: string;
/** The number of times this event occurred in this time period. */
updateCount?: string;
}
interface EventUpdateResponse {
/** Any batch-wide failures which occurred applying updates. */
batchFailures?: EventBatchRecordFailure[];
/** Any failures updating a particular event. */
eventFailures?: EventRecordFailure[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#eventUpdateResponse. */
kind?: string;
/** The current status of any updated events */
playerEvents?: PlayerEvent[];
}
interface GamesAchievementIncrement {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#GamesAchievementIncrement. */
kind?: string;
/** The requestId associated with an increment to an achievement. */
requestId?: string;
/** The number of steps to be incremented. */
steps?: number;
}
interface GamesAchievementSetStepsAtLeast {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#GamesAchievementSetStepsAtLeast. */
kind?: string;
/** The minimum number of steps for the achievement to be set to. */
steps?: number;
}
interface ImageAsset {
/** The height of the asset. */
height?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#imageAsset. */
kind?: string;
/** The name of the asset. */
name?: string;
/** The URL of the asset. */
url?: string;
/** The width of the asset. */
width?: number;
}
interface Instance {
/** URI which shows where a user can acquire this instance. */
acquisitionUri?: string;
/** Platform dependent details for Android. */
androidInstance?: InstanceAndroidDetails;
/** Platform dependent details for iOS. */
iosInstance?: InstanceIosDetails;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#instance. */
kind?: string;
/** Localized display name. */
name?: string;
/**
* The platform type.
* Possible values are:
* - "ANDROID" - Instance is for Android.
* - "IOS" - Instance is for iOS
* - "WEB_APP" - Instance is for Web App.
*/
platformType?: string;
/** Flag to show if this game instance supports realtime play. */
realtimePlay?: boolean;
/** Flag to show if this game instance supports turn based play. */
turnBasedPlay?: boolean;
/** Platform dependent details for Web. */
webInstance?: InstanceWebDetails;
}
interface InstanceAndroidDetails {
/** Flag indicating whether the anti-piracy check is enabled. */
enablePiracyCheck?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#instanceAndroidDetails. */
kind?: string;
/** Android package name which maps to Google Play URL. */
packageName?: string;
/** Indicates that this instance is the default for new installations. */
preferred?: boolean;
}
interface InstanceIosDetails {
/** Bundle identifier. */
bundleIdentifier?: string;
/** iTunes App ID. */
itunesAppId?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#instanceIosDetails. */
kind?: string;
/** Indicates that this instance is the default for new installations on iPad devices. */
preferredForIpad?: boolean;
/** Indicates that this instance is the default for new installations on iPhone devices. */
preferredForIphone?: boolean;
/** Flag to indicate if this instance supports iPad. */
supportIpad?: boolean;
/** Flag to indicate if this instance supports iPhone. */
supportIphone?: boolean;
}
interface InstanceWebDetails {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#instanceWebDetails. */
kind?: string;
/** Launch URL for the game. */
launchUrl?: string;
/** Indicates that this instance is the default for new installations. */
preferred?: boolean;
}
interface Leaderboard {
/** The icon for the leaderboard. */
iconUrl?: string;
/** The leaderboard ID. */
id?: string;
/** Indicates whether the icon image being returned is a default image, or is game-provided. */
isIconUrlDefault?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboard. */
kind?: string;
/** The name of the leaderboard. */
name?: string;
/**
* How scores are ordered.
* Possible values are:
* - "LARGER_IS_BETTER" - Larger values are better; scores are sorted in descending order.
* - "SMALLER_IS_BETTER" - Smaller values are better; scores are sorted in ascending order.
*/
order?: string;
}
interface LeaderboardEntry {
/** The localized string for the numerical value of this score. */
formattedScore?: string;
/** The localized string for the rank of this score for this leaderboard. */
formattedScoreRank?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardEntry. */
kind?: string;
/** The player who holds this score. */
player?: Player;
/** The rank of this score for this leaderboard. */
scoreRank?: string;
/** Additional information about the score. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. */
scoreTag?: string;
/** The numerical value of this score. */
scoreValue?: string;
/**
* The time span of this high score.
* Possible values are:
* - "ALL_TIME" - The score is an all-time high score.
* - "WEEKLY" - The score is a weekly high score.
* - "DAILY" - The score is a daily high score.
*/
timeSpan?: string;
/** The timestamp at which this score was recorded, in milliseconds since the epoch in UTC. */
writeTimestampMillis?: string;
}
interface LeaderboardListResponse {
/** The leaderboards. */
items?: Leaderboard[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface LeaderboardScoreRank {
/** The number of scores in the leaderboard as a string. */
formattedNumScores?: string;
/** The rank in the leaderboard as a string. */
formattedRank?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardScoreRank. */
kind?: string;
/** The number of scores in the leaderboard. */
numScores?: string;
/** The rank in the leaderboard. */
rank?: string;
}
interface LeaderboardScores {
/** The scores in the leaderboard. */
items?: LeaderboardEntry[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#leaderboardScores. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
/** The total number of scores in the leaderboard. */
numScores?: string;
/**
* The score of the requesting player on the leaderboard. The player's score may appear both here and in the list of scores above. If you are viewing a
* public leaderboard and the player is not sharing their gameplay information publicly, the scoreRank and formattedScoreRank values will not be present.
*/
playerScore?: LeaderboardEntry;
/** The pagination token for the previous page of results. */
prevPageToken?: string;
}
interface MetagameConfig {
/** Current version of the metagame configuration data. When this data is updated, the version number will be increased by one. */
currentVersion?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#metagameConfig. */
kind?: string;
/** The list of player levels. */
playerLevels?: PlayerLevel[];
}
interface NetworkDiagnostics {
/** The Android network subtype. */
androidNetworkSubtype?: number;
/** The Android network type. */
androidNetworkType?: number;
/** iOS network type as defined in Reachability.h. */
iosNetworkType?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#networkDiagnostics. */
kind?: string;
/**
* The MCC+MNC code for the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html
*/
networkOperatorCode?: string;
/**
* The name of the carrier of the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
*/
networkOperatorName?: string;
/** The amount of time in milliseconds it took for the client to establish a connection with the XMPP server. */
registrationLatencyMillis?: number;
}
interface ParticipantResult {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#participantResult. */
kind?: string;
/** The ID of the participant. */
participantId?: string;
/**
* The placement or ranking of the participant in the match results; a number from one to the number of participants in the match. Multiple participants
* may have the same placing value in case of a type.
*/
placing?: number;
/**
* The result of the participant for this match.
* Possible values are:
* - "MATCH_RESULT_WIN" - The participant won the match.
* - "MATCH_RESULT_LOSS" - The participant lost the match.
* - "MATCH_RESULT_TIE" - The participant tied the match.
* - "MATCH_RESULT_NONE" - There was no winner for the match (nobody wins or loses this kind of game.)
* - "MATCH_RESULT_DISCONNECT" - The participant disconnected / left during the match.
* - "MATCH_RESULT_DISAGREED" - Different clients reported different results for this participant.
*/
result?: string;
}
interface PeerChannelDiagnostics {
/** Number of bytes received. */
bytesReceived?: AggregateStats;
/** Number of bytes sent. */
bytesSent?: AggregateStats;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#peerChannelDiagnostics. */
kind?: string;
/** Number of messages lost. */
numMessagesLost?: number;
/** Number of messages received. */
numMessagesReceived?: number;
/** Number of messages sent. */
numMessagesSent?: number;
/** Number of send failures. */
numSendFailures?: number;
/** Roundtrip latency stats in milliseconds. */
roundtripLatencyMillis?: AggregateStats;
}
interface PeerSessionDiagnostics {
/** Connected time in milliseconds. */
connectedTimestampMillis?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#peerSessionDiagnostics. */
kind?: string;
/** The participant ID of the peer. */
participantId?: string;
/** Reliable channel diagnostics. */
reliableChannel?: PeerChannelDiagnostics;
/** Unreliable channel diagnostics. */
unreliableChannel?: PeerChannelDiagnostics;
}
interface Played {
/** True if the player was auto-matched with the currently authenticated user. */
autoMatched?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#played. */
kind?: string;
/** The last time the player played the game in milliseconds since the epoch in UTC. */
timeMillis?: string;
}
interface Player {
/** The base URL for the image that represents the player. */
avatarImageUrl?: string;
/** The url to the landscape mode player banner image. */
bannerUrlLandscape?: string;
/** The url to the portrait mode player banner image. */
bannerUrlPortrait?: string;
/** The name to display for the player. */
displayName?: string;
/** An object to represent Play Game experience information for the player. */
experienceInfo?: PlayerExperienceInfo;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#player. */
kind?: string;
/**
* Details about the last time this player played a multiplayer game with the currently authenticated player. Populated for PLAYED_WITH player collection
* members.
*/
lastPlayedWith?: Played;
/** An object representation of the individual components of the player's name. For some players, these fields may not be present. */
name?: {
/** The family name of this player. In some places, this is known as the last name. */
familyName?: string;
/** The given name of this player. In some places, this is known as the first name. */
givenName?: string;
};
/**
* The player ID that was used for this player the first time they signed into the game in question. This is only populated for calls to player.get for
* the requesting player, only if the player ID has subsequently changed, and only to clients that support remapping player IDs.
*/
originalPlayerId?: string;
/** The ID of the player. */
playerId?: string;
/** The player's profile settings. Controls whether or not the player's profile is visible to other players. */
profileSettings?: ProfileSettings;
/** The player's title rewarded for their game activities. */
title?: string;
}
interface PlayerAchievement {
/**
* The state of the achievement.
* Possible values are:
* - "HIDDEN" - Achievement is hidden.
* - "REVEALED" - Achievement is revealed.
* - "UNLOCKED" - Achievement is unlocked.
*/
achievementState?: string;
/** The current steps for an incremental achievement. */
currentSteps?: number;
/**
* Experience points earned for the achievement. This field is absent for achievements that have not yet been unlocked and 0 for achievements that have
* been unlocked by testers but that are unpublished.
*/
experiencePoints?: string;
/** The current steps for an incremental achievement as a string. */
formattedCurrentStepsString?: string;
/** The ID of the achievement. */
id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerAchievement. */
kind?: string;
/** The timestamp of the last modification to this achievement's state. */
lastUpdatedTimestamp?: string;
}
interface PlayerAchievementListResponse {
/** The achievements. */
items?: PlayerAchievement[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerAchievementListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface PlayerEvent {
/** The ID of the event definition. */
definitionId?: string;
/**
* The current number of times this event has occurred, as a string. The formatting of this string depends on the configuration of your event in the Play
* Games Developer Console.
*/
formattedNumEvents?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerEvent. */
kind?: string;
/** The current number of times this event has occurred. */
numEvents?: string;
/** The ID of the player. */
playerId?: string;
}
interface PlayerEventListResponse {
/** The player events. */
items?: PlayerEvent[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerEventListResponse. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
}
interface PlayerExperienceInfo {
/** The current number of experience points for the player. */
currentExperiencePoints?: string;
/** The current level of the player. */
currentLevel?: PlayerLevel;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerExperienceInfo. */
kind?: string;
/** The timestamp when the player was leveled up, in millis since Unix epoch UTC. */
lastLevelUpTimestampMillis?: string;
/** The next level of the player. If the current level is the maximum level, this should be same as the current level. */
nextLevel?: PlayerLevel;
}
interface PlayerLeaderboardScore {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerLeaderboardScore. */
kind?: string;
/** The ID of the leaderboard this score is in. */
leaderboard_id?: string;
/** The public rank of the score in this leaderboard. This object will not be present if the user is not sharing their scores publicly. */
publicRank?: LeaderboardScoreRank;
/** The formatted value of this score. */
scoreString?: string;
/** Additional information about the score. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. */
scoreTag?: string;
/** The numerical value of this score. */
scoreValue?: string;
/** The social rank of the score in this leaderboard. */
socialRank?: LeaderboardScoreRank;
/**
* The time span of this score.
* Possible values are:
* - "ALL_TIME" - The score is an all-time score.
* - "WEEKLY" - The score is a weekly score.
* - "DAILY" - The score is a daily score.
*/
timeSpan?: string;
/** The timestamp at which this score was recorded, in milliseconds since the epoch in UTC. */
writeTimestamp?: string;
}
interface PlayerLeaderboardScoreListResponse {
/** The leaderboard scores. */
items?: PlayerLeaderboardScore[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerLeaderboardScoreListResponse. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
/** The Player resources for the owner of this score. */
player?: Player;
}
interface PlayerLevel {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerLevel. */
kind?: string;
/** The level for the user. */
level?: number;
/** The maximum experience points for this level. */
maxExperiencePoints?: string;
/** The minimum experience points for this level. */
minExperiencePoints?: string;
}
interface PlayerListResponse {
/** The players. */
items?: Player[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface PlayerScore {
/** The formatted score for this player score. */
formattedScore?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerScore. */
kind?: string;
/** The numerical value for this player score. */
score?: string;
/** Additional information about this score. Values will contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. */
scoreTag?: string;
/**
* The time span for this player score.
* Possible values are:
* - "ALL_TIME" - The score is an all-time score.
* - "WEEKLY" - The score is a weekly score.
* - "DAILY" - The score is a daily score.
*/
timeSpan?: string;
}
interface PlayerScoreListResponse {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerScoreListResponse. */
kind?: string;
/** The score submissions statuses. */
submittedScores?: PlayerScoreResponse[];
}
interface PlayerScoreResponse {
/**
* The time spans where the submitted score is better than the existing score for that time span.
* Possible values are:
* - "ALL_TIME" - The score is an all-time score.
* - "WEEKLY" - The score is a weekly score.
* - "DAILY" - The score is a daily score.
*/
beatenScoreTimeSpans?: string[];
/** The formatted value of the submitted score. */
formattedScore?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerScoreResponse. */
kind?: string;
/** The leaderboard ID that this score was submitted to. */
leaderboardId?: string;
/** Additional information about this score. Values will contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. */
scoreTag?: string;
/**
* The scores in time spans that have not been beaten. As an example, the submitted score may be better than the player's DAILY score, but not better than
* the player's scores for the WEEKLY or ALL_TIME time spans.
*/
unbeatenScores?: PlayerScore[];
}
interface PlayerScoreSubmissionList {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#playerScoreSubmissionList. */
kind?: string;
/** The score submissions. */
scores?: ScoreSubmission[];
}
interface ProfileSettings {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#profileSettings. */
kind?: string;
/** The player's current profile visibility. This field is visible to both 1P and 3P APIs. */
profileVisible?: boolean;
}
interface PushToken {
/**
* The revision of the client SDK used by your application, in the same format that's used by revisions.check. Used to send backward compatible messages.
* Format: [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are:
* - IOS - Push token is for iOS
*/
clientRevision?: string;
/** Unique identifier for this push token. */
id?: PushTokenId;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#pushToken. */
kind?: string;
/** The preferred language for notifications that are sent using this token. */
language?: string;
}
interface PushTokenId {
/** A push token ID for iOS devices. */
ios?: {
/** Device token supplied by an iOS system call to register for remote notifications. Encode this field as web-safe base64. */
apns_device_token?: string;
/** Indicates whether this token should be used for the production or sandbox APNS server. */
apns_environment?: string;
};
/** Uniquely identifies the type of this resource. Value is always the fixed string games#pushTokenId. */
kind?: string;
}
interface Quest {
/** The timestamp at which the user accepted the quest in milliseconds since the epoch in UTC. Only present if the player has accepted the quest. */
acceptedTimestampMillis?: string;
/** The ID of the application this quest is part of. */
applicationId?: string;
/** The banner image URL for the quest. */
bannerUrl?: string;
/** The description of the quest. */
description?: string;
/** The timestamp at which the quest ceases to be active in milliseconds since the epoch in UTC. */
endTimestampMillis?: string;
/** The icon image URL for the quest. */
iconUrl?: string;
/** The ID of the quest. */
id?: string;
/** Indicates whether the banner image being returned is a default image, or is game-provided. */
isDefaultBannerUrl?: boolean;
/** Indicates whether the icon image being returned is a default image, or is game-provided. */
isDefaultIconUrl?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#quest. */
kind?: string;
/**
* The timestamp at which the quest was last updated by the user in milliseconds since the epoch in UTC. Only present if the player has accepted the
* quest.
*/
lastUpdatedTimestampMillis?: string;
/** The quest milestones. */
milestones?: QuestMilestone[];
/** The name of the quest. */
name?: string;
/** The timestamp at which the user should be notified that the quest will end soon in milliseconds since the epoch in UTC. */
notifyTimestampMillis?: string;
/** The timestamp at which the quest becomes active in milliseconds since the epoch in UTC. */
startTimestampMillis?: string;
/**
* The state of the quest.
* Possible values are:
* - "UPCOMING": The quest is upcoming. The user can see the quest, but cannot accept it until it is open.
* - "OPEN": The quest is currently open and may be accepted at this time.
* - "ACCEPTED": The user is currently participating in this quest.
* - "COMPLETED": The user has completed the quest.
* - "FAILED": The quest was attempted but was not completed before the deadline expired.
* - "EXPIRED": The quest has expired and was not accepted.
* - "DELETED": The quest should be deleted from the local database.
*/
state?: string;
}
interface QuestContribution {
/**
* The formatted value of the contribution as a string. Format depends on the configuration for the associated event definition in the Play Games
* Developer Console.
*/
formattedValue?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#questContribution. */
kind?: string;
/** The value of the contribution. */
value?: string;
}
interface QuestCriterion {
/** The total number of times the associated event must be incremented for the player to complete this quest. */
completionContribution?: QuestContribution;
/**
* The number of increments the player has made toward the completion count event increments required to complete the quest. This value will not exceed
* the completion contribution.
* There will be no currentContribution until the player has accepted the quest.
*/
currentContribution?: QuestContribution;
/** The ID of the event the criterion corresponds to. */
eventId?: string;
/**
* The value of the event associated with this quest at the time that the quest was accepted. This value may change if event increments that took place
* before the start of quest are uploaded after the quest starts.
* There will be no initialPlayerProgress until the player has accepted the quest.
*/
initialPlayerProgress?: QuestContribution;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#questCriterion. */
kind?: string;
}
interface QuestListResponse {
/** The quests. */
items?: Quest[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#questListResponse. */
kind?: string;
/** Token corresponding to the next page of results. */
nextPageToken?: string;
}
interface QuestMilestone {
/**
* The completion reward data of the milestone, represented as a Base64-encoded string. This is a developer-specified binary blob with size between 0 and
* 2 KB before encoding.
*/
completionRewardData?: string;
/** The criteria of the milestone. */
criteria?: QuestCriterion[];
/** The milestone ID. */
id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#questMilestone. */
kind?: string;
/**
* The current state of the milestone.
* Possible values are:
* - "COMPLETED_NOT_CLAIMED" - The milestone is complete, but has not yet been claimed.
* - "CLAIMED" - The milestone is complete and has been claimed.
* - "NOT_COMPLETED" - The milestone has not yet been completed.
* - "NOT_STARTED" - The milestone is for a quest that has not yet been accepted.
*/
state?: string;
}
interface RevisionCheckResponse {
/** The version of the API this client revision should use when calling API methods. */
apiVersion?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#revisionCheckResponse. */
kind?: string;
/**
* The result of the revision check.
* Possible values are:
* - "OK" - The revision being used is current.
* - "DEPRECATED" - There is currently a newer version available, but the revision being used still works.
* - "INVALID" - The revision being used is not supported in any released version.
*/
revisionStatus?: string;
}
interface Room {
/** The ID of the application being played. */
applicationId?: string;
/** Criteria for auto-matching players into this room. */
autoMatchingCriteria?: RoomAutoMatchingCriteria;
/** Auto-matching status for this room. Not set if the room is not currently in the auto-matching queue. */
autoMatchingStatus?: RoomAutoMatchStatus;
/** Details about the room creation. */
creationDetails?: RoomModification;
/**
* This short description is generated by our servers and worded relative to the player requesting the room. It is intended to be displayed when the room
* is shown in a list (that is, an invitation to a room.)
*/
description?: string;
/** The ID of the participant that invited the user to the room. Not set if the user was not invited to the room. */
inviterId?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#room. */
kind?: string;
/** Details about the last update to the room. */
lastUpdateDetails?: RoomModification;
/** The participants involved in the room, along with their statuses. Includes participants who have left or declined invitations. */
participants?: RoomParticipant[];
/** Globally unique ID for a room. */
roomId?: string;
/** The version of the room status: an increasing counter, used by the client to ignore out-of-order updates to room status. */
roomStatusVersion?: number;
/**
* The status of the room.
* Possible values are:
* - "ROOM_INVITING" - One or more players have been invited and not responded.
* - "ROOM_AUTO_MATCHING" - One or more slots need to be filled by auto-matching.
* - "ROOM_CONNECTING" - Players have joined and are connecting to each other (either before or after auto-matching).
* - "ROOM_ACTIVE" - All players have joined and connected to each other.
* - "ROOM_DELETED" - The room should no longer be shown on the client. Returned in sync calls when a player joins a room (as a tombstone), or for rooms
* where all joined participants have left.
*/
status?: string;
/** The variant / mode of the application being played; can be any integer value, or left blank. */
variant?: number;
}
interface RoomAutoMatchStatus {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomAutoMatchStatus. */
kind?: string;
/** An estimate for the amount of time (in seconds) that auto-matching is expected to take to complete. */
waitEstimateSeconds?: number;
}
interface RoomAutoMatchingCriteria {
/**
* A bitmask indicating when auto-matches are valid. When ANDed with other exclusive bitmasks, the result must be zero. Can be used to support exclusive
* roles within a game.
*/
exclusiveBitmask?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomAutoMatchingCriteria. */
kind?: string;
/** The maximum number of players that should be added to the room by auto-matching. */
maxAutoMatchingPlayers?: number;
/** The minimum number of players that should be added to the room by auto-matching. */
minAutoMatchingPlayers?: number;
}
interface RoomClientAddress {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomClientAddress. */
kind?: string;
/** The XMPP address of the client on the Google Games XMPP network. */
xmppAddress?: string;
}
interface RoomCreateRequest {
/** Criteria for auto-matching players into this room. */
autoMatchingCriteria?: RoomAutoMatchingCriteria;
/** The capabilities that this client supports for realtime communication. */
capabilities?: string[];
/** Client address for the player creating the room. */
clientAddress?: RoomClientAddress;
/** The player IDs to invite to the room. */
invitedPlayerIds?: string[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomCreateRequest. */
kind?: string;
/** Network diagnostics for the client creating the room. */
networkDiagnostics?: NetworkDiagnostics;
/** A randomly generated numeric ID. This number is used at the server to ensure that the request is handled correctly across retries. */
requestId?: string;
/**
* The variant / mode of the application to be played. This can be any integer value, or left blank. You should use a small number of variants to keep the
* auto-matching pool as large as possible.
*/
variant?: number;
}
interface RoomJoinRequest {
/** The capabilities that this client supports for realtime communication. */
capabilities?: string[];
/** Client address for the player joining the room. */
clientAddress?: RoomClientAddress;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomJoinRequest. */
kind?: string;
/** Network diagnostics for the client joining the room. */
networkDiagnostics?: NetworkDiagnostics;
}
interface RoomLeaveDiagnostics {
/** Android network subtype. http://developer.android.com/reference/android/net/NetworkInfo.html#getSubtype() */
androidNetworkSubtype?: number;
/** Android network type. http://developer.android.com/reference/android/net/NetworkInfo.html#getType() */
androidNetworkType?: number;
/** iOS network type as defined in Reachability.h. */
iosNetworkType?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomLeaveDiagnostics. */
kind?: string;
/**
* The MCC+MNC code for the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperator() On iOS, see:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html
*/
networkOperatorCode?: string;
/**
* The name of the carrier of the client's network connection. On Android:
* http://developer.android.com/reference/android/telephony/TelephonyManager.html#getNetworkOperatorName() On iOS:
* https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html#//apple_ref/occ/instp/CTCarrier/carrierName
*/
networkOperatorName?: string;
/** Diagnostics about all peer sessions. */
peerSession?: PeerSessionDiagnostics[];
/** Whether or not sockets were used. */
socketsUsed?: boolean;
}
interface RoomLeaveRequest {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomLeaveRequest. */
kind?: string;
/** Diagnostics for a player leaving the room. */
leaveDiagnostics?: RoomLeaveDiagnostics;
/**
* Reason for leaving the match.
* Possible values are:
* - "PLAYER_LEFT" - The player chose to leave the room..
* - "GAME_LEFT" - The game chose to remove the player from the room.
* - "REALTIME_ABANDONED" - The player switched to another application and abandoned the room.
* - "REALTIME_PEER_CONNECTION_FAILURE" - The client was unable to establish a connection to other peer(s).
* - "REALTIME_SERVER_CONNECTION_FAILURE" - The client was unable to communicate with the server.
* - "REALTIME_SERVER_ERROR" - The client received an error response when it tried to communicate with the server.
* - "REALTIME_TIMEOUT" - The client timed out while waiting for a room.
* - "REALTIME_CLIENT_DISCONNECTING" - The client disconnects without first calling Leave.
* - "REALTIME_SIGN_OUT" - The user signed out of G+ while in the room.
* - "REALTIME_GAME_CRASHED" - The game crashed.
* - "REALTIME_ROOM_SERVICE_CRASHED" - RoomAndroidService crashed.
* - "REALTIME_DIFFERENT_CLIENT_ROOM_OPERATION" - Another client is trying to enter a room.
* - "REALTIME_SAME_CLIENT_ROOM_OPERATION" - The same client is trying to enter a new room.
*/
reason?: string;
}
interface RoomList {
/** The rooms. */
items?: Room[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomList. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
}
interface RoomModification {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomModification. */
kind?: string;
/** The timestamp at which they modified the room, in milliseconds since the epoch in UTC. */
modifiedTimestampMillis?: string;
/** The ID of the participant that modified the room. */
participantId?: string;
}
interface RoomP2PStatus {
/** The amount of time in milliseconds it took to establish connections with this peer. */
connectionSetupLatencyMillis?: number;
/**
* The error code in event of a failure.
* Possible values are:
* - "P2P_FAILED" - The client failed to establish a P2P connection with the peer.
* - "PRESENCE_FAILED" - The client failed to register to receive P2P connections.
* - "RELAY_SERVER_FAILED" - The client received an error when trying to use the relay server to establish a P2P connection with the peer.
*/
error?: string;
/** More detailed diagnostic message returned in event of a failure. */
error_reason?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomP2PStatus. */
kind?: string;
/** The ID of the participant. */
participantId?: string;
/**
* The status of the peer in the room.
* Possible values are:
* - "CONNECTION_ESTABLISHED" - The client established a P2P connection with the peer.
* - "CONNECTION_FAILED" - The client failed to establish directed presence with the peer.
*/
status?: string;
/** The amount of time in milliseconds it took to send packets back and forth on the unreliable channel with this peer. */
unreliableRoundtripLatencyMillis?: number;
}
interface RoomP2PStatuses {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomP2PStatuses. */
kind?: string;
/** The updates for the peers. */
updates?: RoomP2PStatus[];
}
interface RoomParticipant {
/** True if this participant was auto-matched with the requesting player. */
autoMatched?: boolean;
/** Information about a player that has been anonymously auto-matched against the requesting player. (Either player or autoMatchedPlayer will be set.) */
autoMatchedPlayer?: AnonymousPlayer;
/** The capabilities which can be used when communicating with this participant. */
capabilities?: string[];
/** Client address for the participant. */
clientAddress?: RoomClientAddress;
/** True if this participant is in the fully connected set of peers in the room. */
connected?: boolean;
/** An identifier for the participant in the scope of the room. Cannot be used to identify a player across rooms or in other contexts. */
id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomParticipant. */
kind?: string;
/**
* The reason the participant left the room; populated if the participant status is PARTICIPANT_LEFT.
* Possible values are:
* - "PLAYER_LEFT" - The player explicitly chose to leave the room.
* - "GAME_LEFT" - The game chose to remove the player from the room.
* - "ABANDONED" - The player switched to another application and abandoned the room.
* - "PEER_CONNECTION_FAILURE" - The client was unable to establish or maintain a connection to other peer(s) in the room.
* - "SERVER_ERROR" - The client received an error response when it tried to communicate with the server.
* - "TIMEOUT" - The client timed out while waiting for players to join and connect.
* - "PRESENCE_FAILURE" - The client's XMPP connection ended abruptly.
*/
leaveReason?: string;
/**
* Information about the player. Not populated if this player was anonymously auto-matched against the requesting player. (Either player or
* autoMatchedPlayer will be set.)
*/
player?: Player;
/**
* The status of the participant with respect to the room.
* Possible values are:
* - "PARTICIPANT_INVITED" - The participant has been invited to join the room, but has not yet responded.
* - "PARTICIPANT_JOINED" - The participant has joined the room (either after creating it or accepting an invitation.)
* - "PARTICIPANT_DECLINED" - The participant declined an invitation to join the room.
* - "PARTICIPANT_LEFT" - The participant joined the room and then left it.
*/
status?: string;
}
interface RoomStatus {
/** Auto-matching status for this room. Not set if the room is not currently in the automatching queue. */
autoMatchingStatus?: RoomAutoMatchStatus;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#roomStatus. */
kind?: string;
/** The participants involved in the room, along with their statuses. Includes participants who have left or declined invitations. */
participants?: RoomParticipant[];
/** Globally unique ID for a room. */
roomId?: string;
/**
* The status of the room.
* Possible values are:
* - "ROOM_INVITING" - One or more players have been invited and not responded.
* - "ROOM_AUTO_MATCHING" - One or more slots need to be filled by auto-matching.
* - "ROOM_CONNECTING" - Players have joined are connecting to each other (either before or after auto-matching).
* - "ROOM_ACTIVE" - All players have joined and connected to each other.
* - "ROOM_DELETED" - All joined players have left.
*/
status?: string;
/** The version of the status for the room: an increasing counter, used by the client to ignore out-of-order updates to room status. */
statusVersion?: number;
}
interface ScoreSubmission {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#scoreSubmission. */
kind?: string;
/** The leaderboard this score is being submitted to. */
leaderboardId?: string;
/** The new score being submitted. */
score?: string;
/** Additional information about this score. Values will contain no more than 64 URI-safe characters as defined by section 2.3 of RFC 3986. */
scoreTag?: string;
/** Signature Values will contain URI-safe characters as defined by section 2.3 of RFC 3986. */
signature?: string;
}
interface Snapshot {
/** The cover image of this snapshot. May be absent if there is no image. */
coverImage?: SnapshotImage;
/** The description of this snapshot. */
description?: string;
/**
* The ID of the file underlying this snapshot in the Drive API. Only present if the snapshot is a view on a Drive file and the file is owned by the
* caller.
*/
driveId?: string;
/** The duration associated with this snapshot, in millis. */
durationMillis?: string;
/** The ID of the snapshot. */
id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#snapshot. */
kind?: string;
/** The timestamp (in millis since Unix epoch) of the last modification to this snapshot. */
lastModifiedMillis?: string;
/** The progress value (64-bit integer set by developer) associated with this snapshot. */
progressValue?: string;
/** The title of this snapshot. */
title?: string;
/**
* The type of this snapshot.
* Possible values are:
* - "SAVE_GAME" - A snapshot representing a save game.
*/
type?: string;
/** The unique name provided when the snapshot was created. */
uniqueName?: string;
}
interface SnapshotImage {
/** The height of the image. */
height?: number;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#snapshotImage. */
kind?: string;
/** The MIME type of the image. */
mime_type?: string;
/** The URL of the image. This URL may be invalidated at any time and should not be cached. */
url?: string;
/** The width of the image. */
width?: number;
}
interface SnapshotListResponse {
/** The snapshots. */
items?: Snapshot[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#snapshotListResponse. */
kind?: string;
/** Token corresponding to the next page of results. If there are no more results, the token is omitted. */
nextPageToken?: string;
}
interface TurnBasedAutoMatchingCriteria {
/**
* A bitmask indicating when auto-matches are valid. When ANDed with other exclusive bitmasks, the result must be zero. Can be used to support exclusive
* roles within a game.
*/
exclusiveBitmask?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedAutoMatchingCriteria. */
kind?: string;
/** The maximum number of players that should be added to the match by auto-matching. */
maxAutoMatchingPlayers?: number;
/** The minimum number of players that should be added to the match by auto-matching. */
minAutoMatchingPlayers?: number;
}
interface TurnBasedMatch {
/** The ID of the application being played. */
applicationId?: string;
/** Criteria for auto-matching players into this match. */
autoMatchingCriteria?: TurnBasedAutoMatchingCriteria;
/** Details about the match creation. */
creationDetails?: TurnBasedMatchModification;
/** The data / game state for this match. */
data?: TurnBasedMatchData;
/**
* This short description is generated by our servers based on turn state and is localized and worded relative to the player requesting the match. It is
* intended to be displayed when the match is shown in a list.
*/
description?: string;
/** The ID of the participant that invited the user to the match. Not set if the user was not invited to the match. */
inviterId?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatch. */
kind?: string;
/** Details about the last update to the match. */
lastUpdateDetails?: TurnBasedMatchModification;
/** Globally unique ID for a turn-based match. */
matchId?: string;
/** The number of the match in a chain of rematches. Will be set to 1 for the first match and incremented by 1 for each rematch. */
matchNumber?: number;
/** The version of this match: an increasing counter, used to avoid out-of-date updates to the match. */
matchVersion?: number;
/** The participants involved in the match, along with their statuses. Includes participants who have left or declined invitations. */
participants?: TurnBasedMatchParticipant[];
/** The ID of the participant that is taking a turn. */
pendingParticipantId?: string;
/** The data / game state for the previous match; set for the first turn of rematches only. */
previousMatchData?: TurnBasedMatchData;
/** The ID of a rematch of this match. Only set for completed matches that have been rematched. */
rematchId?: string;
/** The results reported for this match. */
results?: ParticipantResult[];
/**
* The status of the match.
* Possible values are:
* - "MATCH_AUTO_MATCHING" - One or more slots need to be filled by auto-matching; the match cannot be established until they are filled.
* - "MATCH_ACTIVE" - The match has started.
* - "MATCH_COMPLETE" - The match has finished.
* - "MATCH_CANCELED" - The match was canceled.
* - "MATCH_EXPIRED" - The match expired due to inactivity.
* - "MATCH_DELETED" - The match should no longer be shown on the client. Returned only for tombstones for matches when sync is called.
*/
status?: string;
/**
* The status of the current user in the match. Derived from the match type, match status, the user's participant status, and the pending participant for
* the match.
* Possible values are:
* - "USER_INVITED" - The user has been invited to join the match and has not responded yet.
* - "USER_AWAITING_TURN" - The user is waiting for their turn.
* - "USER_TURN" - The user has an action to take in the match.
* - "USER_MATCH_COMPLETED" - The match has ended (it is completed, canceled, or expired.)
*/
userMatchStatus?: string;
/** The variant / mode of the application being played; can be any integer value, or left blank. */
variant?: number;
/** The ID of another participant in the match that can be used when describing the participants the user is playing with. */
withParticipantId?: string;
}
interface TurnBasedMatchCreateRequest {
/** Criteria for auto-matching players into this match. */
autoMatchingCriteria?: TurnBasedAutoMatchingCriteria;
/** The player ids to invite to the match. */
invitedPlayerIds?: string[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchCreateRequest. */
kind?: string;
/** A randomly generated numeric ID. This number is used at the server to ensure that the request is handled correctly across retries. */
requestId?: string;
/**
* The variant / mode of the application to be played. This can be any integer value, or left blank. You should use a small number of variants to keep the
* auto-matching pool as large as possible.
*/
variant?: number;
}
interface TurnBasedMatchData {
/** The byte representation of the data (limited to 128 kB), as a Base64-encoded string with the URL_SAFE encoding option. */
data?: string;
/** True if this match has data available but it wasn't returned in a list response; fetching the match individually will retrieve this data. */
dataAvailable?: boolean;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchData. */
kind?: string;
}
interface TurnBasedMatchDataRequest {
/** The byte representation of the data (limited to 128 kB), as a Base64-encoded string with the URL_SAFE encoding option. */
data?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchDataRequest. */
kind?: string;
}
interface TurnBasedMatchList {
/** The matches. */
items?: TurnBasedMatch[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchList. */
kind?: string;
/** The pagination token for the next page of results. */
nextPageToken?: string;
}
interface TurnBasedMatchModification {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchModification. */
kind?: string;
/** The timestamp at which they modified the match, in milliseconds since the epoch in UTC. */
modifiedTimestampMillis?: string;
/** The ID of the participant that modified the match. */
participantId?: string;
}
interface TurnBasedMatchParticipant {
/** True if this participant was auto-matched with the requesting player. */
autoMatched?: boolean;
/** Information about a player that has been anonymously auto-matched against the requesting player. (Either player or autoMatchedPlayer will be set.) */
autoMatchedPlayer?: AnonymousPlayer;
/** An identifier for the participant in the scope of the match. Cannot be used to identify a player across matches or in other contexts. */
id?: string;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchParticipant. */
kind?: string;
/**
* Information about the player. Not populated if this player was anonymously auto-matched against the requesting player. (Either player or
* autoMatchedPlayer will be set.)
*/
player?: Player;
/**
* The status of the participant with respect to the match.
* Possible values are:
* - "PARTICIPANT_NOT_INVITED_YET" - The participant is slated to be invited to the match, but the invitation has not been sent; the invite will be sent
* when it becomes their turn.
* - "PARTICIPANT_INVITED" - The participant has been invited to join the match, but has not yet responded.
* - "PARTICIPANT_JOINED" - The participant has joined the match (either after creating it or accepting an invitation.)
* - "PARTICIPANT_DECLINED" - The participant declined an invitation to join the match.
* - "PARTICIPANT_LEFT" - The participant joined the match and then left it.
* - "PARTICIPANT_FINISHED" - The participant finished playing in the match.
* - "PARTICIPANT_UNRESPONSIVE" - The participant did not take their turn in the allotted time.
*/
status?: string;
}
interface TurnBasedMatchRematch {
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchRematch. */
kind?: string;
/** The old match that the rematch was created from; will be updated such that the rematchId field will point at the new match. */
previousMatch?: TurnBasedMatch;
/** The newly created match; a rematch of the old match with the same participants. */
rematch?: TurnBasedMatch;
}
interface TurnBasedMatchResults {
/** The final match data. */
data?: TurnBasedMatchDataRequest;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchResults. */
kind?: string;
/** The version of the match being updated. */
matchVersion?: number;
/** The match results for the participants in the match. */
results?: ParticipantResult[];
}
interface TurnBasedMatchSync {
/** The matches. */
items?: TurnBasedMatch[];
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchSync. */
kind?: string;
/** True if there were more matches available to fetch at the time the response was generated (which were not returned due to page size limits.) */
moreAvailable?: boolean;
/** The pagination token for the next page of results. */
nextPageToken?: string;
}
interface TurnBasedMatchTurn {
/** The shared game state data after the turn is over. */
data?: TurnBasedMatchDataRequest;
/** Uniquely identifies the type of this resource. Value is always the fixed string games#turnBasedMatchTurn. */
kind?: string;
/** The version of this match: an increasing counter, used to avoid out-of-date updates to the match. */
matchVersion?: number;
/**
* The ID of the participant who should take their turn next. May be set to the current player's participant ID to update match state without changing the
* turn. If not set, the match will wait for other player(s) to join via automatching; this is only valid if automatch criteria is set on the match with
* remaining slots for automatched players.
*/
pendingParticipantId?: string;
/** The match results for the participants in the match. */
results?: ParticipantResult[];
}
interface AchievementDefinitionsResource {
/** Lists all the achievement definitions for your application. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of achievement resources to return in the response, used for paging. For any response, the actual number of achievement resources
* returned may be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementDefinitionsListResponse>;
}
interface AchievementsResource {
/** Increments the steps of the achievement with the given ID for the currently authenticated player. */
increment(request: {
/** The ID of the achievement used by this method. */
achievementId: string;
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A randomly generated numeric ID for each request specified by the caller. This number is used at the server to ensure that the request is handled
* correctly across retries.
*/
requestId?: string;
/** The number of steps to increment. */
stepsToIncrement: number;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementIncrementResponse>;
/** Lists the progress for all your application's achievements for the currently authenticated player. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of achievement resources to return in the response, used for paging. For any response, the actual number of achievement resources
* returned may be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** Tells the server to return only achievements with the specified state. If this parameter isn't specified, all achievements are returned. */
state?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerAchievementListResponse>;
/** Sets the state of the achievement with the given ID to REVEALED for the currently authenticated player. */
reveal(request: {
/** The ID of the achievement used by this method. */
achievementId: string;
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementRevealResponse>;
/**
* Sets the steps for the currently authenticated player towards unlocking an achievement. If the steps parameter is less than the current number of steps
* that the player already gained for the achievement, the achievement is not modified.
*/
setStepsAtLeast(request: {
/** The ID of the achievement used by this method. */
achievementId: string;
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The minimum value to set the steps to. */
steps: number;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementSetStepsAtLeastResponse>;
/** Unlocks this achievement for the currently authenticated player. */
unlock(request: {
/** The ID of the achievement used by this method. */
achievementId: string;
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementUnlockResponse>;
/** Updates multiple achievements for the currently authenticated player. */
updateMultiple(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AchievementUpdateMultipleResponse>;
}
interface ApplicationsResource {
/**
* Retrieves the metadata of the application with the given ID. If the requested application is not available for the specified platformType, the returned
* response will not include any instance data.
*/
get(request: {
/** Data format for the response. */
alt?: string;
/** The application ID from the Google Play developer console. */
applicationId: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Restrict application details returned to the specific platform. */
platformType?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Application>;
/** Indicate that the the currently authenticated user is playing your application. */
played(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Verifies the auth token provided with this request is for the application with the specified ID, and returns the ID of the player it was granted for. */
verify(request: {
/** Data format for the response. */
alt?: string;
/** The application ID from the Google Play developer console. */
applicationId: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ApplicationVerifyResponse>;
}
interface EventsResource {
/** Returns a list showing the current progress on events in this application for the currently authenticated user. */
listByPlayer(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of events to return in the response, used for paging. For any response, the actual number of events to return may be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerEventListResponse>;
/** Returns a list of the event definitions in this application. */
listDefinitions(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of event definitions to return in the response, used for paging. For any response, the actual number of event definitions to return
* may be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<EventDefinitionListResponse>;
/** Records a batch of changes to the number of times events have occurred for the currently authenticated user of this application. */
record(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<EventUpdateResponse>;
}
interface LeaderboardsResource {
/** Retrieves the metadata of the leaderboard with the given ID. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the leaderboard. */
leaderboardId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Leaderboard>;
/** Lists all the leaderboard metadata for your application. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of leaderboards to return in the response. For any response, the actual number of leaderboards returned may be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<LeaderboardListResponse>;
}
interface MetagameResource {
/** Return the metagame configuration data for the calling application. */
getMetagameConfig(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<MetagameConfig>;
/** List play data aggregated per category for the player corresponding to playerId. */
listCategoriesByPlayer(request: {
/** Data format for the response. */
alt?: string;
/** The collection of categories for which data will be returned. */
collection: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of category resources to return in the response, used for paging. For any response, the actual number of category resources returned
* may be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CategoryListResponse>;
}
interface PlayersResource {
/** Retrieves the Player resource with the given ID. To retrieve the player for the currently authenticated user, set playerId to me. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Player>;
/** Get the collection of players for the currently authenticated user. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Collection of players being retrieved */
collection: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of player resources to return in the response, used for paging. For any response, the actual number of player resources returned may
* be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerListResponse>;
}
interface PushtokensResource {
/** Removes a push token for the current user and application. Removing a non-existent push token will report success. */
remove(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Registers a push token for the current user and application. */
update(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
}
interface QuestMilestonesResource {
/**
* Report that a reward for the milestone corresponding to milestoneId for the quest corresponding to questId has been claimed by the currently authorized
* user.
*/
claim(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The ID of the milestone. */
milestoneId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The ID of the quest. */
questId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A numeric ID to ensure that the request is handled correctly across retries. Your client application must generate this ID randomly. */
requestId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
}
interface QuestsResource {
/** Indicates that the currently authorized user will participate in the quest. */
accept(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The ID of the quest. */
questId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Quest>;
/** Get a list of quests for your application and the currently authenticated player. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of quest resources to return in the response, used for paging. For any response, the actual number of quest resources returned may
* be less than the specified maxResults. Acceptable values are 1 to 50, inclusive. (Default: 50).
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<QuestListResponse>;
}
interface RevisionsResource {
/** Checks whether the games client is out of date. */
check(request: {
/** Data format for the response. */
alt?: string;
/**
* The revision of the client SDK used by your application. Format:
* [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are:
*
* - "ANDROID" - Client is running the Android SDK.
* - "IOS" - Client is running the iOS SDK.
* - "WEB_APP" - Client is running as a Web App.
*/
clientRevision: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<RevisionCheckResponse>;
}
interface RoomsResource {
/** Create a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
create(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Room>;
/** Decline an invitation to join a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
decline(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Room>;
/** Dismiss an invitation to join a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
dismiss(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Get the data for a room. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Room>;
/** Join a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
join(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Room>;
/** Leave a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
leave(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Room>;
/** Returns invitations to join rooms. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of rooms to return in the response, used for paging. For any response, the actual number of rooms to return may be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<RoomList>;
/** Updates sent by a client reporting the status of peers in a room. For internal use by the Games SDK only. Calling this method directly is unsupported. */
reportStatus(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the room. */
roomId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<RoomStatus>;
}
interface ScoresResource {
/**
* Get high scores, and optionally ranks, in leaderboards for the currently authenticated player. For a specific time span, leaderboardId can be set to
* ALL to retrieve data for all leaderboards in a given time span.
* NOTE: You cannot ask for 'ALL' leaderboards and 'ALL' timeSpans in the same request; only one parameter may be set to 'ALL'.
*/
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The types of ranks to return. If the parameter is omitted, no ranks will be returned. */
includeRankType?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the leaderboard. Can be set to 'ALL' to retrieve data for all leaderboards for this application. */
leaderboardId: string;
/**
* The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than
* the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The time span for the scores and ranks you're requesting. */
timeSpan: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerLeaderboardScoreListResponse>;
/** Lists the scores in a leaderboard, starting from the top. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The collection of scores you're requesting. */
collection: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the leaderboard. */
leaderboardId: string;
/**
* The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than
* the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The time span for the scores and ranks you're requesting. */
timeSpan: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<LeaderboardScores>;
/** Lists the scores in a leaderboard around (and including) a player's score. */
listWindow(request: {
/** Data format for the response. */
alt?: string;
/** The collection of scores you're requesting. */
collection: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the leaderboard. */
leaderboardId: string;
/**
* The maximum number of leaderboard scores to return in the response. For any response, the actual number of leaderboard scores returned may be less than
* the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* The preferred number of scores to return above the player's score. More scores may be returned if the player is at the bottom of the leaderboard; fewer
* may be returned if the player is at the top. Must be less than or equal to maxResults.
*/
resultsAbove?: number;
/** True if the top scores should be returned when the player is not in the leaderboard. Defaults to true. */
returnTopIfAbsent?: boolean;
/** The time span for the scores and ranks you're requesting. */
timeSpan: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<LeaderboardScores>;
/** Submits a score to the specified leaderboard. */
submit(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the leaderboard. */
leaderboardId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* The score you're submitting. The submitted score is ignored if it is worse than a previously submitted score, where worse depends on the leaderboard
* sort order. The meaning of the score value depends on the leaderboard format type. For fixed-point, the score represents the raw value. For time, the
* score represents elapsed time in milliseconds. For currency, the score represents a value in micro units.
*/
score: string;
/**
* Additional information about the score you're submitting. Values must contain no more than 64 URI-safe characters as defined by section 2.3 of RFC
* 3986.
*/
scoreTag?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerScoreResponse>;
/** Submits multiple scores to leaderboards. */
submitMultiple(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PlayerScoreListResponse>;
}
interface SnapshotsResource {
/** Retrieves the metadata for a given snapshot ID. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the snapshot. */
snapshotId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Snapshot>;
/** Retrieves a list of snapshots created by your application for the player corresponding to the player ID. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/**
* The maximum number of snapshot resources to return in the response, used for paging. For any response, the actual number of snapshot resources returned
* may be less than the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** A player ID. A value of me may be used in place of the authenticated player's ID. */
playerId: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<SnapshotListResponse>;
}
interface TurnBasedMatchesResource {
/** Cancel a turn-based match. */
cancel(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Create a turn-based match. */
create(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Decline an invitation to play a turn-based match. */
decline(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Dismiss a turn-based match from the match list. The match will no longer show up in the list and will not generate notifications. */
dismiss(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/**
* Finish a turn-based match. Each player should make this call once, after all results are in. Only the player whose turn it is may make the first call
* to Finish, and can pass in the final match state.
*/
finish(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Get the data for a turn-based match. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Get match data along with metadata. */
includeMatchData?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Join a turn-based match. */
join(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Leave a turn-based match when it is not the current player's turn, without canceling the match. */
leave(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Leave a turn-based match during the current player's turn, without canceling the match. */
leaveTurn(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** The version of the match being updated. */
matchVersion: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The ID of another participant who should take their turn next. If not set, the match will wait for other player(s) to join via automatching; this is
* only valid if automatch criteria is set on the match with remaining slots for automatched players.
*/
pendingParticipantId?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
/** Returns turn-based matches the player is or was involved in. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* True if match data should be returned in the response. Note that not all data will necessarily be returned if include_match_data is true; the server
* may decide to only return data for some of the matches to limit download size for the client. The remainder of the data for these matches will be
* retrievable on request.
*/
includeMatchData?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The maximum number of completed or canceled matches to return in the response. If not set, all matches returned could be completed or canceled. */
maxCompletedMatches?: number;
/**
* The maximum number of matches to return in the response, used for paging. For any response, the actual number of matches to return may be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatchList>;
/**
* Create a rematch of a match that was previously completed, with the same participants. This can be called by only one player on a match still in their
* list; the player must have called Finish first. Returns the newly created match; it will be the caller's turn.
*/
rematch(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A randomly generated numeric ID for each request specified by the caller. This number is used at the server to ensure that the request is handled
* correctly across retries.
*/
requestId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatchRematch>;
/**
* Returns turn-based matches the player is or was involved in that changed since the last sync call, with the least recent changes coming first. Matches
* that should be removed from the local cache will have a status of MATCH_DELETED.
*/
sync(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* True if match data should be returned in the response. Note that not all data will necessarily be returned if include_match_data is true; the server
* may decide to only return data for some of the matches to limit download size for the client. The remainder of the data for these matches will be
* retrievable on request.
*/
includeMatchData?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The maximum number of completed or canceled matches to return in the response. If not set, all matches returned could be completed or canceled. */
maxCompletedMatches?: number;
/**
* The maximum number of matches to return in the response, used for paging. For any response, the actual number of matches to return may be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The token returned by the previous request. */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatchSync>;
/** Commit the results of a player turn. */
takeTurn(request: {
/** Data format for the response. */
alt?: string;
/** The last-seen mutation timestamp. */
consistencyToken?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The preferred language to use for strings returned by this method. */
language?: string;
/** The ID of the match. */
matchId: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<TurnBasedMatch>;
}
}
} | the_stack |
import { click, currentRouteName, fillIn } from '@ember/test-helpers';
import { setupMirage } from 'ember-cli-mirage/test-support';
import { percySnapshot } from 'ember-percy';
import { module, test, skip } from 'qunit';
import { timeout } from 'ember-concurrency';
import { t } from 'ember-intl/test-support';
import { visit } from 'ember-osf-web/tests/helpers';
import { setupEngineApplicationTest } from 'ember-osf-web/tests/helpers/engines';
import { selectChoose, selectSearch } from 'ember-power-select/test-support';
import { clickTrigger } from 'ember-power-select/test-support/helpers';
module('Registries | Acceptance | branded.moderation | moderators', hooks => {
setupEngineApplicationTest(hooks, 'registries');
setupMirage(hooks);
hooks.beforeEach(() => {
const regProvider = server.create('registration-provider', { id: 'mdr8n' });
server.createList('moderator', 3, { provider: regProvider });
server.create('registration-provider', { id: 'empty' });
});
test('logged out users are rerouted', async assert => {
await visit('/registries/mdr8n/moderation/moderators');
assert.equal(currentRouteName(), 'registries.page-not-found', 'Non-moderators are rerouted');
});
test('logged in, non-moderators are rerouted', async assert => {
server.create('user', 'loggedIn');
await visit('/registries/mdr8n/moderation/moderators');
assert.equal(currentRouteName(), 'registries.page-not-found', 'Non-moderators are rerouted');
});
test('moderators list view for moderators', async assert => {
const regProvider = server.schema.registrationProviders.find('mdr8n');
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', { id: currentUser.id, user: currentUser, provider: regProvider }, 'asModerator');
regProvider.update({ permissions: ['view_submissions'] });
await visit('/registries/mdr8n/moderation/moderators');
await percySnapshot('moderation moderators page: moderator view');
assert.equal(currentRouteName(), 'registries.branded.moderation.moderators',
'On the moderators page of registries reviews');
assert.dom('[data-test-moderator-row]').exists({ count: 4 }, 'There are 4 moderators shown');
assert.dom('[data-test-delete-moderator-button]')
.exists({ count: 1 }, 'Only one moderator is able to be removed');
assert.dom('[data-test-moderator-permission-option]')
.doesNotExist('Moderators are not able to edit permissions');
assert.dom(`[data-test-delete-moderator-button=${currentUser.id}]`).exists('Only able to remove self');
assert.dom('[data-test-add-moderator-button]')
.doesNotExist('Button to add moderator is not visible for moderators');
});
test('admins list view for moderators', async assert => {
const regProvider = server.schema.registrationProviders.find('mdr8n');
const currentUser = server.create('user', 'loggedIn');
server.create('moderator', { id: currentUser.id, user: currentUser, provider: regProvider }, 'asAdmin');
regProvider.update({ permissions: ['view_submissions'] });
await visit('/registries/mdr8n/moderation/moderators');
await percySnapshot('moderation moderators page: admin view');
assert.equal(currentRouteName(), 'registries.branded.moderation.moderators',
'On the moderators page of registries reviews');
assert.dom('[data-test-moderator-row]').exists({ count: 4 }, 'There are 4 moderators shown');
assert.dom('[data-test-moderator-permission-option]')
.exists({ count: 4 }, 'Admins are able to edit permissions for all users');
assert.dom('[data-test-delete-moderator-button]')
.exists({ count: 4 }, 'All moderators and admins are able to be removed');
assert.dom('[data-test-add-moderator-button]')
.exists('Button to add moderator is visible for admins');
});
test('moderator CRUD operations', async assert => {
const regProvider = server.schema.registrationProviders.find('empty');
const currentUser = server.create('user', { fullName: 'J' }, 'loggedIn');
const suzy = server.create('user', { fullName: 'Bae Suzy' });
server.create('moderator', { id: currentUser.id, user: currentUser, provider: regProvider }, 'asAdmin');
regProvider.update({ permissions: ['view_submissions'] });
await visit('/registries/empty/moderation/moderators');
assert.dom('[data-test-moderator-row]').exists({ count: 1 }, 'There is one moderator');
assert.dom(`[data-test-moderator-row="${currentUser.id}"]`).exists('And that moderator is the current user');
// Adding user as a moderator
await click('[data-test-add-moderator-button]');
await selectSearch('[data-test-select-user]', 'Suzy');
await selectChoose('[data-test-select-user]', 'Bae Suzy');
await selectChoose('[data-test-select-permission]', 'Moderator');
await click('[data-test-confirm-add-moderator-button]');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.addedNewModeratorSuccess',
{ userName: suzy.fullName, permission: 'moderator' },
),
'Toast successful message for adding user as moderator',
);
assert.dom('[data-test-moderator-row]').exists({ count: 2 }, 'There are two moderators');
assert.dom(`[data-test-moderator-row="${suzy.id}"]`).exists('Suzy is now a moderator');
// Inviting a user as a moderator
await click('[data-test-add-moderator-button]');
await click('[data-test-toggle-invite-form]');
await click('[data-test-confirm-add-moderator-button]');
await fillIn('[data-test-email-input]>div>input', 'testing@cos.io');
await fillIn('[data-test-full-name-input]>div>input', 'Baek Yerin');
await selectChoose('[data-test-select-permission]', 'Moderator');
await click('[data-test-confirm-add-moderator-button]');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.addedNewModeratorSuccess',
{ userName: 'Baek Yerin', permission: 'moderator' },
),
'Toast successful message for inviting moderator by email',
);
assert.dom('[data-test-moderator-row]').exists({ count: 3 }, 'There are three moderators');
// Updating Suzy's permission
await clickTrigger(`[data-test-moderator-row="${suzy.id}"]`);
await selectChoose(`[data-test-moderator-row="${suzy.id}"]`, 'Admin');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.updatedModeratorPermissionSuccess',
{ userName: suzy.fullName, permission: 'admin' },
),
'Toast successful message for updating permission',
);
assert.dom(`[data-test-moderator-row="${suzy.id}"]>div>[data-test-permission-group]`).hasText(
'Admin',
'Suzy is now an admin',
);
// Removing Suzy as a moderator
await click(`[data-test-delete-moderator-button="${suzy.id}"]>[data-test-delete-button]`);
await click('[data-test-confirm-delete]');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.removedModeratorSuccess',
{ userName: suzy.fullName },
),
'Toast successful message for removing moderator',
);
assert.dom('[data-test-moderator-row]').exists({ count: 2 }, 'There are two moderators');
assert.dom(`[data-test-moderator-row="${suzy.id}"]`).doesNotExist('Suzy is no longer a moderator');
});
// skip: probabilistic failures because of multiple toast messages
// TODO: separate the tests
skip('moderator CRUD operations failure should toast', async assert => {
server.namespace = '/v2';
server.post('/providers/registrations/:parentID/moderators', () => ({
errors: [{ detail: '' }],
}), 400);
server.put('/providers/registrations/:parentID/moderators/:id/', () => ({
errors: [{ detail: '' }],
}), 400);
server.patch('/providers/registrations/:parentID/moderators/:id/', () => ({
errors: [{ detail: '' }],
}), 400);
server.del('/providers/registrations/:parentID/moderators/:id/', () => ({
errors: [{ detail: '' }],
}), 400);
const regProvider = server.schema.registrationProviders.find('empty');
const currentUser = server.create('user', { fullName: 'J' }, 'loggedIn');
server.create('user', { fullName: 'Bae Suzy' });
server.create('moderator', { id: currentUser.id, user: currentUser, provider: regProvider }, 'asAdmin');
regProvider.update({ permissions: ['view_submissions'] });
await visit('/registries/empty/moderation/moderators');
// add failure should toast
await click('[data-test-add-moderator-button]');
await selectSearch('[data-test-select-user]', 'Suzy');
await selectChoose('[data-test-select-user]', 'Bae Suzy');
await selectChoose('[data-test-select-permission]', 'Moderator');
await click('[data-test-confirm-add-moderator-button]');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.addedNewModeratorError',
{ permission: 'moderator' },
),
'Toast error message for adding user as moderator failure',
);
await timeout(5000);
// update permission failure should toast
await clickTrigger(`[data-test-moderator-row="${currentUser.id}"]`);
await selectChoose(`[data-test-moderator-row="${currentUser.id}"]`, 'Moderator');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.updatedModeratorPermissionError',
{ permission: 'moderator' },
),
'Toast error message for updating permission failure',
);
await timeout(5000);
// delete failure should toast
await click(`[data-test-delete-moderator-button="${currentUser.id}"]>[data-test-delete-button]`);
await click('[data-test-confirm-delete]');
assert.dom('#toast-container', document as any).hasTextContaining(
t(
'registries.moderation.moderators.removedModeratorError',
{ permission: 'admin' },
),
'Toast error message for removing moderator failure',
);
});
}); | the_stack |
import * as React from "react"
import { useState } from "react"
import { NavLink, Redirect, Route, useHistory, useLocation, Switch } from "react-router-dom"
import { Button, Dropdown, message, Modal, MessageArgsProps, Tooltip, notification, Popover } from "antd"
// @Components
import { BreadcrumbsProps, withHome, Breadcrumbs } from "ui/components/Breadcrumbs/Breadcrumbs"
import { NotificationsWidget } from "lib/components/NotificationsWidget/NotificationsWidget"
import { CurrentPlan, UpgradePlan } from "ui/components/CurrentPlan/CurrentPlan"
import { CenteredSpin, handleError } from "lib/components/components"
// @Icons
import Icon, {
SettingOutlined,
AreaChartOutlined,
UserOutlined,
UserSwitchOutlined,
LogoutOutlined,
CloudFilled,
NotificationFilled,
ApiFilled,
ThunderboltFilled,
HomeFilled,
} from "@ant-design/icons"
import { ReactComponent as JitsuLogo } from "icons/logo-responsive.svg"
import { ReactComponent as Cross } from "icons/cross.svg"
import { ReactComponent as DbtCloudIcon } from "icons/dbtCloud.svg"
import { ReactComponent as KeyIcon } from "icons/key.svg"
import { ReactComponent as DownloadIcon } from "icons/download.svg"
import { ReactComponent as GlobeIcon } from "icons/globe.svg"
import classNames from "classnames"
// @Model
import { Permission, User } from "lib/services/model"
// @Utils
import { reloadPage } from "lib/commons/utils"
import { Page, usePageLocation } from "navigation"
// @Services
import { useServices } from "hooks/useServices"
import { AnalyticsBlock } from "lib/services/analytics"
import { CurrentSubscription } from "lib/services/billing"
// @Styles
import styles from "./Layout.module.less"
// @Misc
import { settingsPageRoutes } from "./ui/pages/SettingsPage/SettingsPage"
import { FeatureSettings } from "./lib/services/ApplicationServices"
import { usePersistentState } from "./hooks/usePersistentState"
import { ErrorBoundary } from "lib/components/ErrorBoundary/ErrorBoundary"
import { SupportOptions } from "lib/components/SupportOptions/SupportOptions"
import { actionNotification } from "ui/components/ActionNotification/ActionNotification"
import { useClickOutsideRef } from "hooks/useClickOutsideRef"
type MenuItem = {
icon: React.ReactNode
title: React.ReactNode
link: string
color: string
enabled: (f: FeatureSettings) => boolean
}
const makeItem = (
icon: React.ReactNode,
title: React.ReactNode,
link: string,
color: string,
enabled = (f: FeatureSettings) => true
): MenuItem => {
return { icon, title, link, color, enabled }
}
const menuItems = [
makeItem(<HomeFilled />, "Home", "/connections", "#77c593"),
makeItem(<ThunderboltFilled />, "Live Events", "/events_stream", "#fccd04"),
makeItem(<AreaChartOutlined />, "Statistics", "/dashboard", "#88bdbc"),
makeItem(<Icon component={KeyIcon} />, "API Keys", "/api-keys", "#d79922"),
makeItem(<ApiFilled />, "Sources", "/sources", "#d83f87"),
makeItem(<NotificationFilled />, "Destinations", "/destinations", "#4056a1"),
makeItem(<Icon component={DbtCloudIcon} />, "dbt Cloud Integration", "/dbtcloud", "#e76e52"),
makeItem(<Icon component={GlobeIcon} />, "Geo data resolver", "/geo_data_resolver", "#41b3a3"),
makeItem(<CloudFilled />, "Custom Domains", "/domains", "#5ab9ea", f => f.enableCustomDomains),
makeItem(<Icon component={DownloadIcon} />, "Download Config", "/cfg_download", "#14a76c"),
]
export const ApplicationMenu: React.FC<{ expanded: boolean }> = ({ expanded }) => {
const services = useServices()
const key = usePageLocation().mainMenuKey
const Wrapper = React.useMemo<React.FC<{ title?: string | React.ReactNode }>>(
() =>
expanded
? ({ children }) => <>{children}</>
: ({ title, children }) => (
<Tooltip title={title} placement="right" mouseEnterDelay={0} mouseLeaveDelay={0}>
{children}
</Tooltip>
),
[expanded]
)
return (
<div className={`max-h-full overflow-x-visible overflow-y-auto ${styles.sideBarContent_applicationMenu}`}>
{menuItems.map(item => {
const selected = item.link === "/" + key
const enabled = item.enabled(services.features)
return (
enabled && (
<NavLink to={item.link} key={item.link}>
<Wrapper title={item.title}>
<div
key={item.link}
className={`flex items-center ${
selected ? styles.selectedMenuItem : styles.sideBarContent_item__withRightBorder
} ${styles.menuItem} whitespace-nowrap text-textPale py-3 ml-2 pl-4 pr-6 rounded-l-xl`}
style={{ fill: item.color }}
>
<i className="block">{item.icon}</i>
{expanded && <span className="pl-2 whitespace-nowrap">{item.title}</span>}
</div>
</Wrapper>
</NavLink>
)
)
})}
</div>
)
}
export const ApplicationSidebar: React.FC<{}> = () => {
const [expanded, setExpanded] = usePersistentState<boolean>(true, "jitsu_menuExpanded")
return (
<div className={`relative ${styles.sideBarContent}`}>
<div className="flex flex-col items-stretch h-full">
<div className={`pb-3 ${styles.sideBarContent_item__withRightBorder}`}>
<a
href="https://jitsu.com"
className={`text-center block pt-5 h-14 overflow-hidden ${expanded ? "" : "w-12 pl-3"}`}
>
<JitsuLogo className={`h-8 w-40`} />
</a>
</div>
<div className={`flex-grow flex-shrink min-h-0 ${styles.sideBarContent_item__withRightBorder}`}>
<ApplicationMenu expanded={expanded} />
</div>
<div
className={`flex justify-center items-center py-2 ${styles.sideBarContent_item__withRightBorder}`}
onClick={() => setExpanded(!expanded)}
>
<Button
type="text"
className={styles.expandButton}
icon={
<i className={`inline-block text-center align-baseline w-3 h-full ${expanded ? "mr-2" : ""}`}>
<svg
xmlns="http://www.w3.org/2000/svg"
className={`transform ${expanded ? "rotate-90" : "-rotate-90"}`}
viewBox="0 0 24 24"
fill="currentColor"
>
<path
fill="currentColor"
d="M14.121,13.879c-0.586-0.586-6.414-6.414-7-7c-1.172-1.172-3.071-1.172-4.243,0 c-1.172,1.172-1.172,3.071,0,4.243c0.586,0.586,6.414,6.414,7,7c1.172,1.172,3.071,1.172,4.243,0 C15.293,16.95,15.293,15.05,14.121,13.879z"
/>
<path
fill="currentColor"
d="M14.121,18.121c0.586-0.586,6.414-6.414,7-7c1.172-1.172,1.172-3.071,0-4.243c-1.172-1.172-3.071-1.172-4.243,0 c-0.586,0.586-6.414,6.414-7,7c-1.172,1.172-1.172,3.071,0,4.243C11.05,19.293,12.95,19.293,14.121,18.121z"
/>
</svg>
</i>
}
>
{expanded ? <span className="inline-block h-full">{"Minimize Sidebar"}</span> : null}
</Button>
</div>
</div>
</div>
)
}
export type PageHeaderProps = {
user: User
plan: CurrentSubscription
}
function abbr(user: User) {
return user.name
?.split(" ")
.filter(part => part.length > 0)
.map(part => part[0])
.join("")
.toUpperCase()
}
export const PageHeader: React.FC<PageHeaderProps> = ({ plan, user, children }) => {
const [dropdownVisible, setDropdownVisible] = useState(false)
return (
<div className="border-b border-splitBorder mb-0 h-14 flex flex-nowrap">
<div className="flex-grow">
<div className="h-14 flex items-center">{children}</div>
</div>
<div className={`flex-shrink flex justify-center items-center mx-1`}>
<NotificationsWidget />
</div>
<div className="flex-shrink flex justify-center items-center">
<Dropdown
trigger={["click"]}
onVisibleChange={vis => setDropdownVisible(vis)}
visible={dropdownVisible}
overlay={<DropdownMenu user={user} plan={plan} hideMenu={() => setDropdownVisible(false)} />}
>
<Button
className="ml-1 border-primary border-2 hover:border-text text-text hover:text-text"
size="large"
shape="circle"
>
{abbr(user) || <UserOutlined />}
</Button>
</Dropdown>
</div>
</div>
)
}
export const DropdownMenu: React.FC<{ user: User; plan: CurrentSubscription; hideMenu: () => void }> = ({
plan,
user,
hideMenu,
}) => {
const services = useServices()
const history = useHistory()
const showSettings = React.useCallback<() => void>(() => history.push(settingsPageRoutes[0]), [history])
const becomeUser = async () => {
let email = prompt("Please enter e-mail of the user", "")
if (!email) {
return
}
try {
AnalyticsBlock.blockAll()
await services.userService.becomeUser(email)
} catch (e) {
handleError(e, "Can't login as other user")
AnalyticsBlock.unblockAll()
}
}
return (
<div>
<div className="py-5 border-b px-5 flex flex-col items-center">
<div className="text-center text-text text-lg">{user.name}</div>
<div className="text-secondaryText text-xs underline">{user.email}</div>
</div>
<div className="py-2 border-b border-main px-5 flex flex-col items-start">
<div>
Project: <b>{services.activeProject.name || "Unspecified"}</b>
</div>
</div>
{services.features.billingEnabled && services.applicationConfiguration.billingUrl && (
<div className="py-5 border-b border-main px-5 flex flex-col items-start">
<CurrentPlan planStatus={plan} onPlanChangeModalOpen={hideMenu} />
</div>
)}
<div className="p-2 flex flex-col items-stretch">
<Button type="text" className="text-left" key="settings" icon={<SettingOutlined />} onClick={showSettings}>
Settings
</Button>
{services.userService.getUser().hasPermission(Permission.BECOME_OTHER_USER) && (
<Button className="text-left" type="text" key="become" icon={<UserSwitchOutlined />} onClick={becomeUser}>
Become User
</Button>
)}
<Button
className="text-left"
type="text"
key="logout"
icon={<LogoutOutlined />}
onClick={() => services.userService.removeAuth(reloadPage)}
>
Logout
</Button>
</div>
</div>
)
}
export type ApplicationPageWrapperProps = {
pages: Page[]
extraForms?: JSX.Element[]
user: User
plan: CurrentSubscription
[propName: string]: any
}
function handleBillingMessage(params) {
if (!params.get("billingMessage")) {
return
}
;(params.get("billingStatus") === "error" ? notification.error : notification.success)({
message: params.get("billingMessage"),
duration: 5,
})
}
export const ApplicationPage: React.FC<ApplicationPageWrapperProps> = ({ plan, pages, user, extraForms }) => {
const location = useLocation()
const services = useServices()
const [breadcrumbs, setBreadcrumbs] = useState<BreadcrumbsProps>(
withHome({ elements: [{ title: pages[0].pageHeader }] })
)
const routes = pages.map(page => {
const Component = page.component as React.ExoticComponent
return (
<Route
key={page.pageTitle}
path={page.getPrefixedPath()}
exact={true}
render={routeProps => {
services.analyticsService.onPageLoad({
pagePath: routeProps.location.hash,
})
document["title"] = page.pageTitle
// setBreadcrumbs(withHome({ elements: [{ title: page.pageHeader }] }))
return (
<ErrorBoundary>
<Component setBreadcrumbs={setBreadcrumbs} {...(routeProps as any)} />
</ErrorBoundary>
)
}}
/>
)
})
routes.push(<Redirect key="dashboardRedirect" from="*" to="/dashboard" />)
handleBillingMessage(new URLSearchParams(useLocation().search))
React.useEffect(() => {
const pageMatchingPathname = pages.find(page => page.path.includes(location.pathname))
if (pageMatchingPathname) setBreadcrumbs(withHome({ elements: [{ title: pageMatchingPathname.pageHeader }] }))
}, [location.pathname])
return (
<div className={styles.applicationPage}>
<div className={classNames(styles.sidebar)}>
<ApplicationSidebar />
</div>
<div className={classNames(styles.rightbar)}>
<PageHeader user={user} plan={plan}>
<Breadcrumbs {...breadcrumbs} />
</PageHeader>
<div className={styles.applicationPageComponent}>
<React.Suspense fallback={<CenteredSpin />}>
<Switch key={"appPagesSwitch"}>{routes}</Switch>
{extraForms}
</React.Suspense>
</div>
</div>
</div>
)
}
export const SlackChatWidget: React.FC<{}> = () => {
const services = useServices()
const [popoverVisible, setPopoverVisible] = useState<boolean>(false)
const [upgradeDialogVisible, setUpgradeDialogVisible] = useState<boolean>(false)
const [popoverContentRef, buttonRef] = useClickOutsideRef<HTMLDivElement, HTMLDivElement>(() => {
setPopoverVisible(false)
})
const disablePrivateChannelButton: boolean = services.currentSubscription?.currentPlan?.id === "free"
const isJitsuCloud: boolean = services.features.environment === "jitsu_cloud"
const isPrivateSupportAvailable: boolean = services.slackApiSercice?.supportApiAvailable
const handleUpgradeClick = () => {
setPopoverVisible(false)
setUpgradeDialogVisible(true)
}
const handleJoinPublicChannel = React.useCallback(() => {
services.analyticsService.track("support_slack_public")
window.open("https://jitsu.com/slack", "_blank")
}, [])
const handleJoinPrivateChannel = React.useCallback(async () => {
services.analyticsService.track("support_slack_private")
try {
const invitationUrl = await services.slackApiSercice?.createPrivateSupportChannel(
services.activeProject.id,
services.activeProject.name
)
window.open(invitationUrl, "_blank")
} catch (_error) {
const error = _error instanceof Error ? _error : new Error(_error)
actionNotification.error(
`Failed to join a private channel due to internal error. Please, contact support via email or file an issue. Description:\n${error}`
)
services.analyticsService.track("support_slack_private_error", error)
}
}, [])
const handleSupportEmailCopy = React.useCallback(() => {
services.analyticsService.track("support_email_copied")
}, [])
return (
<>
<Popover
// ref={ref}
trigger="click"
placement="leftBottom"
// destroyTooltipOnHide={{ keepParent: false }}
visible={popoverVisible}
content={
<SupportOptions
ref={popoverContentRef}
showEmailOption={isJitsuCloud}
showPrivateChannelOption={isJitsuCloud && isPrivateSupportAvailable}
disablePrivateChannelButton={disablePrivateChannelButton}
privateChannelButtonDescription={
disablePrivateChannelButton ? (
<span className="text-xs text-secondaryText mb-3">
<a role="button" className="text-xs" onClick={handleUpgradeClick}>
Upgrade
</a>
{" to use this feature"}
</span>
) : null
}
onPublicChannelClick={handleJoinPublicChannel}
onPrivateChannelClick={handleJoinPrivateChannel}
onEmailCopyClick={handleSupportEmailCopy}
/>
}
>
<div
ref={buttonRef}
id="jitsuSlackWidget"
onClick={() => {
services.analyticsService.track("slack_invitation_open")
setPopoverVisible(visible => !visible)
}}
className="fixed bottom-5 right-5 rounded-full bg-primary text-text w-12 h-12 flex justify-center items-center cursor-pointer hover:bg-primaryHover"
>
<span
className={`absolute top-0 left-0 h-full w-full flex justify-center items-center text-xl transition-all duration-300 transform-gpu ${
popoverVisible ? "opacity-100 scale-100" : "opacity-0 scale-50"
}`}
>
<span className="block h-4 w-4 transform-gpu -translate-y-1/2">
<Cross />
</span>
</span>
<span
className={`absolute top-3 left-3 transition-all duration-300 transform-gpu ${
popoverVisible ? "opacity-0 scale-50" : "opacity-100 scale-100"
}`}
>
<svg className="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
<path d="M 4 3 C 2.9 3 2 3.9 2 5 L 2 15.792969 C 2 16.237969 2.5385156 16.461484 2.8535156 16.146484 L 5 14 L 14 14 C 15.1 14 16 13.1 16 12 L 16 5 C 16 3.9 15.1 3 14 3 L 4 3 z M 18 8 L 18 12 C 18 14.209 16.209 16 14 16 L 8 16 L 8 17 C 8 18.1 8.9 19 10 19 L 19 19 L 21.146484 21.146484 C 21.461484 21.461484 22 21.237969 22 20.792969 L 22 10 C 22 8.9 21.1 8 20 8 L 18 8 z" />
</svg>
</span>
</div>
</Popover>
<Modal
destroyOnClose={true}
width={800}
title={<h1 className="text-xl m-0 p-0">Upgrade subscription</h1>}
visible={upgradeDialogVisible}
onCancel={() => {
setUpgradeDialogVisible(false)
}}
footer={null}
>
<UpgradePlan planStatus={services.currentSubscription} />
</Modal>
</>
)
}
const EmailIsNotConfirmedMessage: React.FC<{ messageKey: React.Key }> = ({ messageKey }) => {
const services = useServices()
const [isSendingVerification, setIsSendingVerification] = useState<boolean>(false)
const handleDestroyMessage = () => message.destroy(messageKey)
const handleresendConfirmationLink = async () => {
setIsSendingVerification(true)
try {
await services.userService.sendConfirmationEmail()
} finally {
setIsSendingVerification(false)
}
handleDestroyMessage()
}
return (
<span className="flex flex-col items-center mt-1">
<span>
<span>{"Email "}</span>
{services.userService.getUser()?.email ? (
<span className={`font-semibold ${styles.emailHighlight}`}>{services.userService.getUser()?.email}</span>
) : (
""
)}
<span>
{` is not verified. Please, follow the instructions in your email
to complete the verification process.`}
</span>
</span>
<span>
<Button type="link" loading={isSendingVerification} onClick={handleresendConfirmationLink}>
{"Resend verification link"}
</Button>
<Button type="text" onClick={handleDestroyMessage}>
{"Close"}
</Button>
</span>
</span>
)
}
const MESSAGE_KEY = "email-not-confirmed-message"
export const emailIsNotConfirmedMessageConfig: MessageArgsProps = {
type: "error",
key: MESSAGE_KEY,
duration: null,
icon: <>{null}</>,
content: <EmailIsNotConfirmedMessage messageKey={MESSAGE_KEY} />,
} | the_stack |
import { PdfLayoutElement } from './../figures/layout-element';
import { PdfBrush } from './../brushes/pdf-brush';
import { PdfFont } from './../fonts/pdf-font';
import { PdfStandardFont } from './../fonts/pdf-standard-font';
import { PdfPen } from './../pdf-pen';
import { PdfStringFormat } from './../fonts/pdf-string-format';
import { PdfLayoutParams, PdfLayoutResult } from './../figures/base/element-layouter';
import { PdfGraphics } from './../pdf-graphics';
import { PdfTextLayoutResult, TextLayouter } from './base/text-layouter';
import { PdfSolidBrush } from './../brushes/pdf-solid-brush';
import { PdfColor } from './../pdf-color';
import { RectangleF, SizeF, PointF } from './../../drawing/pdf-drawing';
import { PdfPage } from './../../pages/pdf-page';
import { PdfLayoutFormat } from './base/element-layouter';
import { PdfStringLayoutResult, PdfStringLayouter } from './../fonts/string-layouter';
import { PdfTextAlignment } from './../enum';
/**
* `PdfTextElement` class represents the text area with the ability to span several pages
* and inherited from the 'PdfLayoutElement' class.
* @private
*/
export class PdfTextElement extends PdfLayoutElement {
// Fields
/**
* `Text` data.
* @private
*/
private content : string = '';
/**
* `Value` of text data.
* @private
*/
private elementValue : string = '';
/**
* `Pen` for text drawing.
* @private
*/
private pdfPen : PdfPen;
/**
* `Brush` for text drawing.
* @private
*/
private pdfBrush : PdfBrush;
/**
* `Font` for text drawing.
* @private
*/
private pdfFont : PdfFont;
/**
* Text `format`.
* @private
*/
private format : PdfStringFormat;
/**
* indicate whether the drawText with PointF overload is called or not.
* @default false
* @private
*/
private hasPointOverload : boolean = false;
/**
* indicate whether the PdfGridCell value is `PdfTextElement`
* @default false
* @private
*/
public isPdfTextElement : boolean = false;
// Constructors
/**
* Initializes a new instance of the `PdfTextElement` class.
* @private
*/
public constructor()
/**
* Initializes a new instance of the `PdfTextElement` class with text to draw into the PDF.
* @private
*/
public constructor(text : string)
/**
* Initializes a new instance of the `PdfTextElement` class with the text and `PdfFont`.
* @private
*/
public constructor(text : string, font : PdfFont)
/**
* Initializes a new instance of the `PdfTextElement` class with text,`PdfFont` and `PdfPen`.
* @private
*/
public constructor(text : string, font : PdfFont, pen : PdfPen)
/**
* Initializes a new instance of the `PdfTextElement` class with text,`PdfFont` and `PdfBrush`.
* @private
*/
public constructor(text : string, font : PdfFont, brush : PdfBrush)
/**
* Initializes a new instance of the `PdfTextElement` class with text,`PdfFont`,`PdfPen`,`PdfBrush` and `PdfStringFormat`.
* @private
*/
public constructor(text : string, font : PdfFont, pen : PdfPen, brush : PdfBrush, format : PdfStringFormat)
public constructor(arg1 ?: string, arg2 ?: PdfFont, arg3 ?: PdfPen|PdfBrush, arg4 ?: PdfBrush, arg5 ?: PdfStringFormat) {
super();
if (typeof arg1 === 'undefined') {
//
} else if (typeof arg1 === 'string' && typeof arg2 === 'undefined') {
this.content = arg1;
this.elementValue = arg1;
} else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && typeof arg3 === 'undefined') {
this.content = arg1;
this.elementValue = arg1;
this.pdfFont = arg2;
} else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && arg3 instanceof PdfPen && typeof arg4 === 'undefined') {
this.content = arg1;
this.elementValue = arg1;
this.pdfFont = arg2;
this.pdfPen = arg3;
} else if (typeof arg1 === 'string' && arg2 instanceof PdfFont && arg3 instanceof PdfBrush && typeof arg4 === 'undefined') {
this.content = arg1;
this.elementValue = arg1;
this.pdfFont = arg2;
this.pdfBrush = arg3;
} else {
this.content = arg1;
this.elementValue = arg1;
this.pdfFont = arg2;
this.pdfPen = arg3 as PdfPen;
this.pdfBrush = arg4;
this.format = arg5;
}
}
// Properties
/**
* Gets or sets a value indicating the `text` that should be printed.
* ```typescript
* // create a new PDF document.
* let document : PdfDocument = new PdfDocument();
* // add a page to the document.
* let page1 : PdfPage = document.pages.add();
* // create the font
* let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
* // create the Text Web Link
* let textLink : PdfTextWebLink = new PdfTextWebLink();
* // set the hyperlink
* textLink.url = 'http://www.google.com';
* //
* // set the link text
* textLink.text = 'Google';
* //
* // set the font
* textLink.font = font;
* // draw the hyperlink in PDF page
* textLink.draw(page1, new PointF(10, 40));
* // save the document.
* document.save('output.pdf');
* // destroy the document
* document.destroy();
* ```
*/
public get text() : string {
return this.content;
}
public set text(value : string) {
this.elementValue = value;
this.content = value;
}
//get value
/**
* Gets or sets a `value` indicating the text that should be printed.
* @private
*/
public get value() : string {
return this.elementValue;
}
//get pen
/**
* Gets or sets a `PdfPen` that determines the color, width, and style of the text
* @private
*/
public get pen() : PdfPen {
return this.pdfPen;
}
//Set pen value
public set pen(value : PdfPen) {
this.pdfPen = value;
}
//get brush
/**
* Gets or sets the `PdfBrush` that will be used to draw the text with color and texture.
* @private
*/
public get brush() : PdfBrush {
return this.pdfBrush;
}
//Set brush value
public set brush(value : PdfBrush) {
this.pdfBrush = value;
}
//get font
/**
* Gets or sets a `PdfFont` that defines the text format.
* ```typescript
* // create a new PDF document.
* let document : PdfDocument = new PdfDocument();
* // add a page to the document.
* let page1 : PdfPage = document.pages.add();
* // create the font
* let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
* // create the Text Web Link
* let textLink : PdfTextWebLink = new PdfTextWebLink();
* // set the hyperlink
* textLink.url = 'http://www.google.com';
* // set the link text
* textLink.text = 'Google';
* //
* // set the font
* textLink.font = font;
* //
* // draw the hyperlink in PDF page
* textLink.draw(page1, new PointF(10, 40));
* // save the document.
* document.save('output.pdf');
* // destroy the document
* document.destroy();
* ```
*/
public get font() : PdfFont {
return this.pdfFont;
}
public set font(value : PdfFont) {
this.pdfFont = value;
if (this.pdfFont instanceof PdfStandardFont && this.content != null) {
this.elementValue = PdfStandardFont.convert(this.content);
} else {
this.elementValue = this.content;
}
}
/**
* Gets or sets the `PdfStringFormat` that will be used to set the string format
* @private
*/
public get stringFormat() : PdfStringFormat {
return this.format;
}
public set stringFormat(value : PdfStringFormat) {
this.format = value;
}
// Implementation
/**
* Gets a `brush` for drawing.
* @private
*/
public getBrush() : PdfBrush {
return (this.pdfBrush == null || typeof this.pdfBrush === 'undefined') ? new PdfSolidBrush(new PdfColor(0, 0, 0)) : this.pdfBrush;
}
// /**
// * `Draws` an element on the Graphics.
// * @private
// */
// public drawInternal(graphics : PdfGraphics) : void {
// graphics.drawString(this.elementValue, this.pdfFont, this.pdfPen, this.getBrush(), 0, 0, this.stringFormat);
// }
/**
* `Layouts` the element.
* @private
*/
protected layout(param : PdfLayoutParams) : PdfLayoutResult {
let layouter : TextLayouter = new TextLayouter(this);
let result : PdfTextLayoutResult = layouter.layout(param) as PdfTextLayoutResult;
return result;
}
/* tslint:disable */
/**
* `Draws` the element on the page with the specified page and "PointF" class
* @private
*/
public drawText(page : PdfPage, location : PointF) : PdfLayoutResult
/**
* `Draws` the element on the page with the specified page and pair of coordinates
* @private
*/
public drawText(page : PdfPage, x : number, y : number) : PdfLayoutResult
/**
* `Draws` the element on the page with the specified page and "RectangleF" class
* @private
*/
public drawText(page : PdfPage, layoutRectangle : RectangleF) : PdfLayoutResult
/**
* `Draws` the element on the page with the specified page, "PointF" class and layout format
* @private
*/
public drawText(page : PdfPage, location : PointF, format : PdfLayoutFormat) : PdfLayoutResult
/**
* `Draws` the element on the page with the specified page, pair of coordinates and layout format
* @private
*/
public drawText(page : PdfPage, x : number, y : number, format : PdfLayoutFormat) : PdfLayoutResult
/**
* `Draws` the element on the page.
* @private
*/
public drawText(page : PdfPage, layoutRectangle : RectangleF, embedFonts : boolean) : PdfLayoutResult
/**
* `Draws` the element on the page with the specified page, "RectangleF" class and layout format
* @private
*/
public drawText(page : PdfPage, layoutRectangle : RectangleF, format : PdfLayoutFormat) : PdfLayoutResult
public drawText(arg2 : PdfPage, arg3 : RectangleF | PointF | number, arg4 ?: PdfLayoutFormat | number | boolean, arg5 ?: PdfLayoutFormat) : PdfLayoutResult {
if (arg3 instanceof PointF && typeof (arg3 as RectangleF).width === 'undefined' && typeof arg4 === 'undefined') {
this.hasPointOverload = true;
return this.drawText(arg2, arg3.x, arg3.y);
} else if (typeof arg3 === 'number' && typeof arg4 === 'number' && typeof arg5 === 'undefined') {
this.hasPointOverload = true;
return this.drawText(arg2, arg3, arg4, null);
} else if (arg3 instanceof RectangleF && typeof (arg3 as RectangleF).width !== 'undefined' && typeof arg4 === 'undefined') {
return this.drawText(arg2, arg3, null);
} else if (arg3 instanceof PointF && typeof (arg3 as RectangleF).width === 'undefined' && arg4 instanceof PdfLayoutFormat) {
this.hasPointOverload = true;
return this.drawText(arg2, arg3.x, arg3.y, arg4);
} else if (typeof arg3 === 'number' && typeof arg4 === 'number' && (arg5 instanceof PdfLayoutFormat || arg5 == null)) {
this.hasPointOverload = true;
let width : number = (arg2.graphics.clientSize.width - arg3);
let layoutRectangle : RectangleF = new RectangleF(arg3, arg4, width, 0);
return this.drawText(arg2, layoutRectangle, arg5);
} else if (arg3 instanceof RectangleF && typeof (arg3 as RectangleF).width !== 'undefined' && typeof arg4 === 'boolean') {
return this.drawText(arg2, arg3, null);
} else {
let layout : PdfStringLayouter = new PdfStringLayouter();
if (this.hasPointOverload) {
let stringLayoutResult : PdfStringLayoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg2.graphics.clientSize.width - (arg3 as RectangleF).x), 0), true, arg2.graphics.clientSize);
let layoutResult : PdfLayoutResult;
let param : PdfLayoutParams = new PdfLayoutParams();
let temparg3 : RectangleF = arg3 as RectangleF;
let temparg4 : PdfLayoutFormat = arg4 as PdfLayoutFormat;
param.page = arg2;
let previousPage : PdfPage = arg2;
param.bounds = temparg3;
param.format = (temparg4 != null) ? temparg4 : new PdfLayoutFormat();
if (stringLayoutResult.lines.length > 1) {
this.text = stringLayoutResult.layoutLines[0].text;
if (param.bounds.y <= param.page.graphics.clientSize.height) {
let previousPosition : PointF = new PointF(param.bounds.x, param.bounds.y);
layoutResult = this.layout(param);
let bounds : RectangleF = new RectangleF(0, layoutResult.bounds.y + stringLayoutResult.lineHeight, arg2.graphics.clientSize.width, stringLayoutResult.lineHeight);
let isPaginate : boolean = false;
for (let i : number = 1; i < stringLayoutResult.lines.length; i++) {
param.page = layoutResult.page;
param.bounds = new RectangleF(new PointF(bounds.x, bounds.y), new SizeF(bounds.width, bounds.height));
this.text = stringLayoutResult.layoutLines[i].text;
if (bounds.y + stringLayoutResult.lineHeight > layoutResult.page.graphics.clientSize.height) {
isPaginate = true;
param.page = param.page.graphics.getNextPage();
if (previousPosition.y > (layoutResult.page.graphics.clientSize.height - layoutResult.bounds.height)) {
bounds = new RectangleF(0, layoutResult.bounds.height, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);
} else {
bounds = new RectangleF(0, 0, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);
}
param.bounds = bounds;
}
layoutResult = this.layout(param);
if (i !== (stringLayoutResult.lines.length - 1)) {
bounds = new RectangleF(0, layoutResult.bounds.y + stringLayoutResult.lineHeight, layoutResult.page.graphics.clientSize.width, stringLayoutResult.lineHeight);
} else {
let lineWidth : number = this.font.measureString(this.text, this.format).width;
layoutResult = this.calculateResultBounds(layoutResult, lineWidth, layoutResult.page.graphics.clientSize.width, 0);
}
}
}
return layoutResult;
} else {
let lineSize : SizeF = this.font.measureString(this.text, this.format);
if (param.bounds.y <= param.page.graphics.clientSize.height) {
layoutResult = this.layout(param);
layoutResult = this.calculateResultBounds(layoutResult, lineSize.width, layoutResult.page.graphics.clientSize.width, 0);
}
return layoutResult;
}
} else {
let layoutResult : PdfStringLayoutResult = layout.layout(this.value, this.font, this.stringFormat, new SizeF((arg3 as RectangleF).width, 0), false, arg2.graphics.clientSize);
let result : PdfLayoutResult;
let param : PdfLayoutParams = new PdfLayoutParams();
let temparg3 : RectangleF = arg3 as RectangleF;
let temparg4 : PdfLayoutFormat = arg4 as PdfLayoutFormat;
param.page = arg2;
param.bounds = temparg3;
param.format = (temparg4 != null) ? temparg4 : new PdfLayoutFormat();
if (layoutResult.lines.length > 1) {
this.text = layoutResult.layoutLines[0].text;
if (param.bounds.y <= param.page.graphics.clientSize.height) {
let previousPosition : PointF = new PointF(param.bounds.x, param.bounds.y);
result = this.layout(param);
let bounds : RectangleF = new RectangleF(temparg3.x, result.bounds.y + layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);
let isPaginate : boolean = false;
for (let i : number = 1; i < layoutResult.lines.length; i++) {
param.page = result.page;
param.bounds = new RectangleF(bounds.x, bounds.y, bounds.width, bounds.height);
this.text = layoutResult.layoutLines[i].text;
if (bounds.y + layoutResult.lineHeight > result.page.graphics.clientSize.height) {
isPaginate = true;
param.page = param.page.graphics.getNextPage();
if (previousPosition.y > (result.page.graphics.clientSize.height - result.bounds.height)) {
bounds = new RectangleF(temparg3.x, layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);
} else {
bounds = new RectangleF(temparg3.x, 0, temparg3.width, layoutResult.lineHeight);
}
param.bounds = bounds;
}
result = this.layout(param);
if (i !== (layoutResult.lines.length - 1)) {
bounds = new RectangleF(temparg3.x, result.bounds.y + layoutResult.lineHeight, temparg3.width, layoutResult.lineHeight);
} else {
let lineWidth : number = this.font.measureString(this.text, this.format).width;
result = this.calculateResultBounds(result, lineWidth, temparg3.width, temparg3.x);
}
}
}
return result;
} else {
let lineSize : SizeF = this.font.measureString(this.text, this.format);
if (param.bounds.y <= param.page.graphics.clientSize.height) {
result = this.layout(param);
result = this.calculateResultBounds(result, lineSize.width, temparg3.width, temparg3.x);
}
return result;
}
}
}
}
private calculateResultBounds(result : PdfLayoutResult, lineWidth : number, maximumWidth : number, startPosition : number) : PdfLayoutResult {
let shift : number = 0;
if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Center) {
result.bounds.x = startPosition + (maximumWidth - lineWidth) / 2;
result.bounds.width = lineWidth;
} else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Right) {
result.bounds.x = startPosition + (maximumWidth - lineWidth);
result.bounds.width = lineWidth;
} else if (this.stringFormat != null && typeof this.stringFormat !== 'undefined' && this.stringFormat.alignment === PdfTextAlignment.Justify) {
result.bounds.x = startPosition;
result.bounds.width = maximumWidth;
} else {
result.bounds.width = startPosition;
result.bounds.width = lineWidth;
}
return result;
}
/* tslint:enable */
} | the_stack |
import messaging from '@react-native-firebase/messaging'
import Log from '../Log/Log'
import { sublocale } from '../i18n'
import MarketingEvent from '../Marketing/MarketingEvent'
import settingsActions from '../../appstores/Stores/Settings/SettingsActions'
import config from '../../config/config'
import NavStore from '../../components/navigation/NavStore'
import UpdateAppNewsDaemon from '../../daemons/back/UpdateAppNewsDaemon'
import AppNotificationPushSave from './AppNotificationPushSave'
import AppNotificationPopup from './AppNotificationPopup'
import { AppNewsActions } from '../../appstores/Stores/AppNews/AppNewsActions'
import { SettingsKeystore } from '../../appstores/Stores/Settings/SettingsKeystore'
import { Platform } from 'react-native'
import { setLockScreenConfig, LockScreenFlowTypes } from '@app/appstores/Stores/LockScreen/LockScreenActions'
import trusteeAsyncStorage from '@appV2/services/trusteeAsyncStorage/trusteeAsyncStorage'
import { LANGUAGE_SETTINGS } from '@app/modules/Settings/helpers'
import ApiProxyLoad from '@app/services/Api/ApiProxyLoad'
const CACHE_VALID_TIME = 120000000 // 2000 minute
const DEBUG_NOTIFS = true
const TOPICS = ['transactions', 'exchangeRates', 'news']
export default new class AppNotificationListener {
private messageListener: any
private inited: boolean = false
private initing: number = 0
private timer : any
async init(): Promise<void> {
const now = new Date().getTime()
if (this.inited || (now - this.initing) < 10000) {
return
}
this.initing = now
const hasInternet = await ApiProxyLoad.hasInternet()
if (hasInternet) {
if (await this.checkPermission()) {
this.inited = true
await this.createRefreshListener()
await this.createMessageListener()
}
}
}
async checkPermission(): Promise<boolean> {
let res = false
try {
const enabled: any = await messaging().hasPermission()
if (enabled) {
await this.getToken()
res = true
} else {
res = await this.requestPermission()
}
} catch (e) {
if (config.debug.appErrors) {
await console.log('PUSH checkPermission error ' + e.message)
}
await Log.log('PUSH checkPermission error ' + e.message)
}
if (DEBUG_NOTIFS) {
await Log.log('PUSH checkPermission result ' + JSON.stringify(res))
}
/*
if (res) {
await appNewsDS.setRemoved({ newsName: 'PUSH_NOTIFICATION_DISABLED' })
} else {
await appNewsDS.saveAppNews({
onlyOne: true,
newsGroup: 'PUSHES',
newsName: 'PUSH_NOTIFICATION_DISABLED',
newsJson: {}
})
}
*/
return res
}
async _subscribe(topic: string, locale: string, isDev: boolean): Promise<void> {
if (!this.inited) {
return
}
if (DEBUG_NOTIFS) {
Log.log('PUSH subscribe ' + topic + ' started ' + locale)
}
for (const lang of LANGUAGE_SETTINGS) {
const sub = sublocale(lang.code)
if (sub === locale) {
if (DEBUG_NOTIFS) {
Log.log('PUSH subscribe ' + topic + ' lang ' + locale + ' isDEV ' + (isDev ? ' true ' : ' false '))
}
await messaging().subscribeToTopic(topic)
await messaging().subscribeToTopic(topic + '_' + locale)
if (Platform.OS === 'ios') {
await messaging().subscribeToTopic(topic + '_ios')
await messaging().subscribeToTopic(topic + '_ios_' + locale)
} else {
await messaging().subscribeToTopic(topic + '_android')
await messaging().subscribeToTopic(topic + '_android_' + locale)
}
if (isDev) {
await messaging().subscribeToTopic(topic + '_dev')
await messaging().subscribeToTopic(topic + '_dev_' + locale)
} else {
await messaging().unsubscribeFromTopic(topic + '_dev')
await messaging().unsubscribeFromTopic(topic + '_dev_' + locale)
}
} else {
if (DEBUG_NOTIFS) {
Log.log('PUSH subscribe ' + topic + ' unlang ' + sub + ' isDEV ' + (isDev ? ' true ' : ' false '))
}
await messaging().unsubscribeFromTopic(topic + '_' + sub)
await messaging().unsubscribeFromTopic(topic + '_dev_' + sub)
if (Platform.OS === 'ios') {
await messaging().unsubscribeFromTopic(topic + '_ios_' + sub)
} else {
await messaging().unsubscribeFromTopic(topic + '_android_' + sub)
}
}
}
if (DEBUG_NOTIFS) {
Log.log('PUSH subscribe ' + topic + ' finished')
}
}
async _unsubscribe(topic: string): Promise<void> {
if (!this.inited) {
return
}
if (DEBUG_NOTIFS) {
Log.log('PUSH unsubscribe ' + topic + ' started')
}
await messaging().unsubscribeFromTopic(topic)
await messaging().unsubscribeFromTopic(topic + '_dev')
if (Platform.OS === 'ios') {
await messaging().unsubscribeFromTopic(topic + '_ios')
} else {
await messaging().unsubscribeFromTopic(topic + '_android')
}
for (const lang of LANGUAGE_SETTINGS) {
const sub = sublocale(lang.code)
await messaging().unsubscribeFromTopic(topic + '_' + sub)
await messaging().unsubscribeFromTopic(topic + '_dev_' + sub)
if (Platform.OS === 'ios') {
await messaging().unsubscribeFromTopic(topic + '_ios_' + sub)
} else {
await messaging().unsubscribeFromTopic(topic + '_android_' + sub)
}
}
if (DEBUG_NOTIFS) {
Log.log('PUSH unsubscribe ' + topic + ' finished')
}
}
async rmvOld(fcmToken: string = ''): Promise<void> {
if (!this.inited) {
return
}
if (fcmToken && fcmToken.indexOf('NO_GOOGLE') !== -1) {
return
}
try {
if (DEBUG_NOTIFS) {
await Log.log('PUSH rmvOld start')
}
await messaging().unsubscribeFromTopic('trustee_all')
await messaging().unsubscribeFromTopic('trustee_dev')
for (const lang of LANGUAGE_SETTINGS) {
const sub = sublocale(lang.code)
await messaging().unsubscribeFromTopic('trustee_all_' + sub)
await messaging().unsubscribeFromTopic('trustee_dev_' + sub)
}
if (DEBUG_NOTIFS) {
await Log.log('PUSH rmvOld finished')
}
} catch (e) {
if (config.debug.appErrors) {
Log.log('PUSH rmvOld error ' + e.message)
}
}
}
async updateSubscriptions(fcmToken: string = ''): Promise<void> {
if (!this.inited) {
if (DEBUG_NOTIFS) {
Log.log('PUSH updateSubscriptions NOT INITIED')
}
return
}
if (fcmToken && fcmToken.indexOf('NO_GOOGLE') !== -1) {
if (DEBUG_NOTIFS) {
Log.log('PUSH updateSubscriptions NO_GOOGLE')
}
return
}
if (DEBUG_NOTIFS) {
Log.log('PUSH updateSubscriptions ' + fcmToken)
}
const settings = await settingsActions.getSettings(false, false)
if (typeof settings === 'undefined' || !settings) {
return
}
const notifsStatus = settings && typeof settings.notifsStatus !== 'undefined' && settings.notifsStatus ? settings.notifsStatus : '1'
const locale = settings && typeof settings.language !== 'undefined' && settings.language ? sublocale(settings.language) : sublocale()
if (DEBUG_NOTIFS) {
Log.log('PUSH updateSubscriptions currentSettings ' + settings.language + ' locale ' + locale)
}
const isDev = trusteeAsyncStorage.getDevMode()
await this._subscribe('trusteeAll', locale, isDev as boolean)
if (notifsStatus === '1') {
for (const key of TOPICS) {
// @ts-ignore
if (typeof settings[key + 'Notifs'] === 'undefined' || settings[key + 'Notifs'] === '1') {
await this._subscribe(key, locale, isDev as boolean)
} else {
await this._unsubscribe(key)
}
}
} else {
for (const key of TOPICS) {
await this._unsubscribe(key)
}
}
if (typeof fcmToken === 'undefined' || fcmToken === '') {
fcmToken = MarketingEvent.DATA.LOG_TOKEN
}
if (typeof settings.dbVersion !== 'undefined' && settings.dbVersion) {
await settingsActions.setSettings('notifsSavedToken', fcmToken)
}
}
async updateSubscriptionsLater(): Promise<void> {
if (!this.inited) {
return
}
if (DEBUG_NOTIFS) {
await Log.log('PUSH updateSubscriptionsLater')
}
await settingsActions.setSettings('notifsSavedToken', '')
try {
if (this.timer) {
clearTimeout(this.timer)
}
} catch (e) {
await Log.log('PUSH updateSubscriptionsLater timer clean error ' + e.message)
}
this.timer = setTimeout(() => {
this.updateSubscriptions()
}, 2000)
}
async getToken(): Promise<string | null> {
let fcmToken: string | null = await trusteeAsyncStorage.getFcmToken()
// @ts-ignore
let time: number = 1 * trusteeAsyncStorage.getFcmTokenTime()
const now = new Date().getTime()
if (time && fcmToken) {
if (now - time > CACHE_VALID_TIME && fcmToken.indexOf('NO_GOOGLE') === -1) {
time = 0
fcmToken = ''
if (DEBUG_NOTIFS) {
await Log.log('PUSH getToken cache invalidate ' + (now - time) + ' time ' + time)
}
} else {
// Log.log('PUSH getToken cache valid ' + (now - time) + ' time ' + time)
}
}
await settingsActions.getSettings(false, false)
const notifsSavedToken = await settingsActions.getSetting('notifsSavedToken')
const notifsRmvOld = await settingsActions.getSetting('notifsRmvOld')
try {
if (!time || !fcmToken || fcmToken === '' || notifsSavedToken !== fcmToken) {
if (fcmToken) {
await this.updateSubscriptions(fcmToken)
}
try {
fcmToken = await messaging().getToken()
if (!notifsRmvOld && fcmToken) {
await this.rmvOld(fcmToken)
await settingsActions.setSettings('notifsRmvOld', '1')
}
} catch (e) {
if (config.debug.appErrors) {
console.log('PUSH getToken fcmToken error ' + e.message + ' ' + fcmToken)
}
await Log.log('PUSH getToken fcmToken error ' + e.message + ' ' + fcmToken)
}
if (!fcmToken) {
try {
await messaging().registerDeviceForRemoteMessages()
fcmToken = await messaging().getToken()
} catch (e) {
if (config.debug.appErrors) {
console.log('PUSH getToken fcmToken error ' + e.message)
}
await Log.log('PUSH getToken fcmToken error ' + e.message)
if (e.message.indexOf('MISSING_INSTANCEID_SERVICE') !== -1) {
fcmToken = 'NO_GOOGLE_' + (new Date().getTime()) + '_' + (Math.ceil(Math.random() * 100000))
}
}
}
if (DEBUG_NOTIFS) {
await Log.log('PUSH getToken subscribed token ' + fcmToken)
}
await this._onRefresh(fcmToken)
trusteeAsyncStorage.setFcmTokenTime(now + '')
} else {
// Log.log('PUSH getToken1 cache result ', fcmToken)
}
// @ts-ignore
MarketingEvent.DATA.LOG_TOKEN = fcmToken
} catch (e) {
if (config.debug.appErrors) {
console.log('PUSH getToken error ' + e.message)
}
await Log.log('PUSH getToken error ' + e.message)
}
return fcmToken
}
async requestPermission(): Promise<boolean> {
try {
await messaging().requestPermission()
await this.getToken()
return true
} catch (e) {
if (config.debug.appErrors) {
console.log('PUSH requestPermission rejected error ' + e.message)
}
Log.log('PUSH requestPermission rejected error ' + e.message)
return false
}
}
createMessageListener = async (): Promise<void> => {
try {
const startMessage = await messaging().getInitialNotification()
if (startMessage && typeof startMessage.messageId !== 'undefined') {
const lockScreen = await SettingsKeystore.getLockScreenStatus()
if (+lockScreen) {
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage startMessage not null but lockScreen is needed', startMessage)
}
const unifiedPush = await AppNotificationPushSave.unifyPushAndSave(startMessage)
setLockScreenConfig({flowType : LockScreenFlowTypes.PUSH_POPUP_CALLBACK, callback : async () => {
await Log.log('PUSH _onMessage startMessage after lock screen', unifiedPush)
if (await AppNewsActions.onOpen(unifiedPush, '', '', false)) {
NavStore.reset('NotificationsScreen')
} else {
NavStore.reset('TabBar')
}
}})
NavStore.goNext('LockScreenPop')
} else {
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage startMessage not null', startMessage)
}
UpdateAppNewsDaemon.goToNotifications('AFTER_APP')
const unifiedPush = await AppNotificationPushSave.unifyPushAndSave(startMessage)
await UpdateAppNewsDaemon.updateAppNewsDaemon()
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage startMessage unified', unifiedPush)
}
if (UpdateAppNewsDaemon.isGoToNotifications('INITED_APP')) {
await Log.log('PUSH _onMessage startMessage app is inited first')
if (await AppNewsActions.onOpen(unifiedPush)) {
NavStore.reset('NotificationsScreen')
}
} else {
await Log.log('PUSH _onMessage startMessage app is not inited')
await AppNewsActions.onOpen(unifiedPush)
}
}
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage startMessage finished')
}
} else {
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage startMessage is null', startMessage)
}
}
} catch (e) {
if (config.debug.appErrors) {
console.log('PUSH _onMessage startMessage error ' + e.message)
}
await Log.log('PUSH _onMessage startMessage error ' + e.message)
}
this.messageListener = messaging().onMessage(async (message) => {
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onMessage inited, locked ' + JSON.stringify(MarketingEvent.UI_DATA.IS_LOCKED))
}
await AppNotificationPopup.displayPush(message)
})
await messaging().onNotificationOpenedApp(async (message) => {
if (DEBUG_NOTIFS) {
await Log.log('PUSH _onNotificationOpened inited, locked ' + JSON.stringify(MarketingEvent.UI_DATA.IS_LOCKED))
}
await AppNotificationPopup.onOpened(message)
})
}
_onRefresh = async (fcmToken: string): Promise<void> => {
if (!fcmToken) return
let tmp = trusteeAsyncStorage.getFcmTokensAll()
let all = {}
try {
if (tmp != null) {
tmp = JSON.parse(tmp)
}
if (tmp) all = tmp
} catch (e) {
}
// @ts-ignore
all[fcmToken] = '1'
if (DEBUG_NOTIFS) {
Log.log('PUSH _onRefreshAll ', all)
}
await trusteeAsyncStorage.setFcmTokensAll(all, fcmToken)
}
createRefreshListener = async (): Promise<void> => {
/*
* Triggered for data only payload in foreground
* */
if (DEBUG_NOTIFS) {
Log.log('PUSH _onRefresh inited')
}
this.messageListener = messaging().onTokenRefresh((fcmToken) => {
if (DEBUG_NOTIFS) {
Log.log('PUSH _onRefresh', fcmToken)
}
this._onRefresh(fcmToken)
})
}
} | the_stack |
import { VTransmitFile } from "../classes/VTransmitFile";
import { VTransmitUploadContext } from "../classes/VTransmitUploadContext";
import { DriverInterface, UploadResult } from "../core/interfaces";
import {
VTransmitEvents,
UploadStatuses,
ErrType,
is_function,
} from "../core/utils";
import { Dictionary } from "../types";
export type ParamName = string | ((file: VTransmitFile) => string);
export type StaticOrDynamic<T> = T | ((files: VTransmitFile[]) => T);
function resolveStaticOrDynamic<T>(
x: StaticOrDynamic<T>,
files: VTransmitFile[]
): T {
if (is_function(x)) {
return x(files);
}
return x;
}
export enum ParamNameStyle {
Empty,
Indexed,
Brackets,
}
/**
* Responsibilities:
* - send and manage upload via transport
* - on progress: emit progress stats
* - on error: emit to vue-transmit & update file status
* - on timeout: emit to vue-transmit & update file status
* - on error: emit to vue-transmit & update file status
* - on success: emit to vue-transmit & update file status
* - once complete: emit to vue-transmit & update file status
*/
export type XHRDriverOptions<T = any> = {
/**
* A string representing the URL to send the request to
* or a function called with an array of files for the upload
* that returns a string url.
*/
url: StaticOrDynamic<string>;
/**
* The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc.
* Ignored for non-HTTP(S) URLs.
*
* ```
* // default => "post"
* ```
*/
method?: StaticOrDynamic<string>;
/**
* The XMLHttpRequest.withCredentials property is a Boolean that indicates
* whether or not cross-site Access-Control requests should be made using
* credentials such as cookies, authorization headers or TLS client
* certificates. Setting withCredentials has no effect on same-site requests.
*/
withCredentials?: StaticOrDynamic<boolean>;
/**
* The XMLHttpRequest.timeout property is an unsigned long representing the
* number of milliseconds a request can take before automatically being
* terminated. The default value is 0, which means there is no timeout.
* Timeout shouldn't be used for synchronous XMLHttpRequests requests used in
* a document environment or it will throw an InvalidAccessError exception.
* When a timeout happens, a timeout event is fired.
*/
timeout?: StaticOrDynamic<number>;
/**
* The name of the file param that gets transferred.
*/
paramName?: ParamName;
/**
* The param name syntax for multiple uploads.
*
* **Options:**
* - `0 (Empty)` _(Default)_ Adds nothing to the paramName: `file`
* - `1 (Indexed)` Adds the array index of the file: `file[0]`
* - `2 (Brackets)` Adds the array-like brackets without index: `file[]`
*/
multipleParamNameStyle?: ParamNameStyle;
/**
* An object of additional parameters to transfer to the server.
* This is the same as adding hidden input fields in the form element.
*/
params?: StaticOrDynamic<Dictionary<string>>;
headers?: StaticOrDynamic<Dictionary<string>>;
/**
* The XMLHttpRequest.responseType property is an enumerated value that
* returns the type of response. It also lets the author change the response
* type. If an empty string is set as the value of responseType, the default
* value text will be used.
*
* Setting the value of responseType to "document" is ignored if done in a
* Worker environment. When setting responseType to a particular value,
* the author should make sure that the server is actually sending a response
* compatible to that format. If the server returns data that is not
* compatible to the responseType that was set, the value of response will be
* null. Also, setting responseType for synchronous requests will throw an
* InvalidAccessError exception.
*/
responseType?: StaticOrDynamic<XMLHttpRequestResponseType>;
/**
* responseParseFunc is a function that given an XMLHttpRequest
* returns a response object. Allows for custom response parsing.
*/
responseParseFunc?: (xhr: XMLHttpRequest) => T;
errUploadError?: (xhr: XMLHttpRequest) => string;
errUploadTimeout?: (xhr: XMLHttpRequest) => string;
renameFile?: (name: string) => string;
};
export type XHRUploadGroup = {
id: number;
files: VTransmitFile[];
xhr: XMLHttpRequest;
};
let group_id = 0;
export class XHRDriver<T = any> implements DriverInterface {
public context: VTransmitUploadContext;
public url: StaticOrDynamic<string>;
public method: StaticOrDynamic<string>;
public withCredentials: StaticOrDynamic<boolean>;
public timeout: StaticOrDynamic<number>;
public paramName: ParamName;
public multipleParamNameStyle: ParamNameStyle;
public params: StaticOrDynamic<Dictionary<string>>;
public headers: StaticOrDynamic<Dictionary<string>>;
public responseType: StaticOrDynamic<XMLHttpRequestResponseType>;
public errUploadError: (xhr: XMLHttpRequest) => string;
public errUploadTimeout: (xhr: XMLHttpRequest) => string;
public renameFile: (name: string) => string;
public responseParseFunc?: (xhr: XMLHttpRequest) => T;
private uploadGroups: { [key: number]: XHRUploadGroup } = Object.create(
null
);
constructor(context: VTransmitUploadContext, options: XHRDriverOptions<T>) {
let {
url,
method = "post",
withCredentials = false,
timeout = 0,
paramName = "file",
multipleParamNameStyle = ParamNameStyle.Empty,
params = Object.create(null),
headers = {
Accept: "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
},
responseType = "json",
responseParseFunc,
errUploadError = (xhr: XMLHttpRequest) =>
`Error during upload: ${xhr.statusText} [${xhr.status}]`,
errUploadTimeout = (_xhr: XMLHttpRequest) =>
`Error during upload: the server timed out.`,
renameFile = (name: string) => name,
} = options;
if (!url) {
throw new TypeError(
`${
this.constructor.name
} requires a 'url' parameter. Supply a string or a function returning a string.`
);
}
this.context = context;
this.url = url;
this.method = method;
this.withCredentials = withCredentials;
this.timeout = timeout;
this.paramName = paramName;
this.multipleParamNameStyle = multipleParamNameStyle;
this.params = params;
this.headers = headers;
// @ts-ignore
this.responseType = responseType;
this.responseParseFunc = responseParseFunc;
this.errUploadError = errUploadError;
this.errUploadTimeout = errUploadTimeout;
this.renameFile = renameFile;
}
uploadFiles(files: VTransmitFile[]): Promise<UploadResult<T>> {
return new Promise(resolve => {
if (!this.url) {
return resolve({
ok: false,
err: {
type: ErrType.Any,
message: `Missing upload URL.`,
data: this.url,
},
});
}
const xhr = new XMLHttpRequest();
const updateProgress = this.handleUploadProgress(files);
const id = group_id++;
const params = resolveStaticOrDynamic(this.params, files);
const headers = resolveStaticOrDynamic(this.headers, files);
this.uploadGroups[id] = { id, xhr, files };
for (const file of files) {
file.driverData.groupID = id;
file.startProgress();
}
xhr.open(
resolveStaticOrDynamic(this.method, files),
resolveStaticOrDynamic(this.url, files),
true
);
// Setting the timeout after open because of IE11 issue:
// @link https://gitlab.com/meno/dropzone/issues/8
xhr.timeout = resolveStaticOrDynamic(this.timeout, files);
xhr.withCredentials = resolveStaticOrDynamic(
this.withCredentials,
files
);
xhr.responseType = resolveStaticOrDynamic(this.responseType, files);
xhr.addEventListener("error", () => {
this.rmGroup(id);
resolve({
ok: false,
err: {
type: ErrType.Any,
message: this.errUploadError(xhr),
data: xhr,
},
});
});
xhr.upload.addEventListener("progress", updateProgress);
xhr.addEventListener("timeout", () => {
this.rmGroup(id);
resolve({
ok: false,
err: {
type: ErrType.Timeout,
message: this.errUploadTimeout(xhr),
data: xhr,
},
});
});
xhr.addEventListener("load", () => {
if (
files[0].status === UploadStatuses.Canceled ||
xhr.readyState !== XMLHttpRequest.DONE
) {
return;
}
// The XHR is complete, so remove the group
this.rmGroup(id);
let response: T;
if (this.responseParseFunc) {
response = this.responseParseFunc(xhr);
} else {
response = xhr.response;
if (!xhr.responseType) {
let contentType = xhr.getResponseHeader("content-type");
if (
contentType &&
contentType.indexOf("application/json") > -1
) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
return resolve({
ok: false,
err: {
message: "Invalid JSON response from server.",
type: ErrType.Any,
data: err,
},
});
}
}
}
}
// Called on load (complete) to complete progress tracking logic.
updateProgress();
if (xhr.status < 200 || xhr.status >= 300) {
return resolve({
ok: false,
err: {
type: ErrType.Any,
message: this.errUploadError(xhr),
data: xhr,
},
});
}
return resolve({
ok: true,
data: response,
});
});
for (const headerName of Object.keys(headers)) {
if (headers[headerName]) {
xhr.setRequestHeader(headerName, headers[headerName]);
}
}
const formData = new FormData();
for (const key of Object.keys(params)) {
formData.append(key, params[key]);
}
for (const file of files) {
this.context.emit(VTransmitEvents.Sending, file, xhr, formData);
}
if (this.context.props.uploadMultiple) {
this.context.emit(
VTransmitEvents.SendingMultiple,
files,
xhr,
formData
);
}
for (let i = 0, len = files.length; i < len; i++) {
formData.append(
this.getParamName(files[i], i),
files[i].nativeFile,
this.renameFile(files[i].name)
);
}
xhr.send(formData);
});
}
handleUploadProgress(files: VTransmitFile[]): (e?: ProgressEvent) => void {
const vm = this.context.vtransmit;
return function onProgressFn(e?: ProgressEvent): void {
if (!e) {
let allFilesFinished = true;
for (const file of files) {
if (
file.upload.progress !== 100 ||
file.upload.bytesSent !== file.upload.total
) {
allFilesFinished = false;
}
file.upload.progress = 100;
file.upload.bytesSent = file.upload.total;
file.endProgress();
}
if (allFilesFinished) {
return;
}
}
for (const file of files) {
if (e) {
file.handleProgress(e);
}
vm.$emit(
VTransmitEvents.UploadProgress,
file,
file.upload.progress,
file.upload.bytesSent
);
}
};
}
getParamName(file: VTransmitFile, index: string | number): string {
let paramName: string;
if (is_function(this.paramName)) {
paramName = this.paramName(file);
} else {
paramName = this.paramName;
}
if (!this.context.props.uploadMultiple) {
return paramName;
}
switch (this.multipleParamNameStyle) {
case ParamNameStyle.Indexed:
paramName += `[${index}]`;
break;
case ParamNameStyle.Brackets:
paramName += `[]`;
break;
case ParamNameStyle.Empty:
default:
break;
}
return paramName;
}
cancelUpload(file: VTransmitFile): VTransmitFile[] {
let group = this.uploadGroups[file.driverData.groupID];
if (!group) {
return [];
}
group.xhr.abort();
this.rmGroup(file.driverData.groupID);
return [...group.files];
}
rmGroup(id: number) {
delete this.uploadGroups[id];
}
} | the_stack |
import * as nakamajs from "@heroiclabs/nakama-js";
import * as nakamajsprotobuf from "../nakama-js-protobuf";
import {generateid, createPage, adapters, AdapterType, matchmakerTimeout} from "./utils";
import {describe, expect, it} from '@jest/globals'
import {MatchmakerMatched, PartyPresenceEvent, PartyData, PartyJoinRequest, PartyLeader, PartyMatchmakerTicket} from "@heroiclabs/nakama-js";
import { assert } from "console";
describe('Party Tests', () => {
it.each(adapters)('should create party and receive presence', async (adapter) => {
const page = await createPage();
const customid = generateid();
const response : PartyPresenceEvent = await page.evaluate(async (customid, adapter) => {
const client = new nakamajs.Client();
const socket = client.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session = await client.authenticateCustom(customid);
await socket.connect(session, false);
var presencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket.onpartypresence = (presence) => {
resolve(presence);
}
});
socket.createParty(false, 3);
return presencePromise;
}, customid, adapter);
expect(response).not.toBeNull;
expect(response.party_id).toBeDefined;
expect(response.joins.length).toEqual(1);
});
it.each(adapters)('should create closed party and accept member', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response : PartyPresenceEvent = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
var presencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(false, 3);
const presenceEvent = await presencePromise;
const joinRequestPromise = new Promise<PartyJoinRequest>((resolve, reject) => {
socket1.onpartyjoinrequest = (request) => {
resolve(request);
}
});
socket2.joinParty(presenceEvent.party_id);
const joinRequest : PartyJoinRequest = await joinRequestPromise;
const joinedPromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (request) => {
resolve(request);
}
});
socket1.acceptPartyMember(joinRequest.party_id, joinRequest.presences[0]);
return joinedPromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
});
it.each(adapters)('should only create open party and only have member join', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response : PartyPresenceEvent = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
var presencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(true, 3);
const presenceEvent = await presencePromise;
const socket2PresencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (request) => {
resolve(request);
}
});
socket2.joinParty(presenceEvent.party_id);
return socket2PresencePromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
});
it.each(adapters)('should create open party and have member join and send data', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response : PartyData = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
var presencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(true, 3);
const presenceEvent = await presencePromise;
const socket2PresencePromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (request) => {
resolve(request);
}
});
socket2.joinParty(presenceEvent.party_id);
await socket2PresencePromise;
const socket2DataPromise = new Promise<PartyData>((resolve, reject) => {
socket2.onpartydata = (data) => {
resolve(data);
}
});
socket1.sendPartyData(presenceEvent.party_id, 1, {"hello": "world"});
return socket2DataPromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
expect(response.party_id).toBeDefined();
expect(response.op_code == 1);
expect(response.data).toBeDefined();
expect(response.data.hello).toEqual("world");
});
it.each(adapters)('should create closed party and have member join and then removed', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response : PartyPresenceEvent = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
const id1PresenceJoinPromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(false, 3);
const id1PresenceEvent = await id1PresenceJoinPromise;
const id2JoinRequestPromise = new Promise<PartyJoinRequest>((resolve, reject) => {
socket1.onpartyjoinrequest = (request) => {
resolve(request);
}
});
socket2.joinParty(id1PresenceEvent.party_id);
const id2JoinRequest : PartyJoinRequest = await id2JoinRequestPromise;
await socket1.acceptPartyMember(id2JoinRequest.party_id, id2JoinRequest.presences[0]);
socket1.removePartyMember(id2JoinRequest.party_id, id2JoinRequest.presences[0]);
const id2PresenceRemovedPromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
if (presence.leaves?.length > 0) {
resolve(presence);
}
}
});
return id2PresenceRemovedPromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
expect(response.leaves).toHaveLength(1);
});
it.each(adapters)('should create closed party and have member join and then promoted', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response : PartyLeader = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
const id1PresenceJoinPromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(false, 3);
const id1PresenceEvent = await id1PresenceJoinPromise;
const id2JoinRequestPromise = new Promise<PartyJoinRequest>((resolve, reject) => {
socket1.onpartyjoinrequest = (request) => {
resolve(request);
}
});
socket2.joinParty(id1PresenceEvent.party_id);
const id2JoinRequest : PartyJoinRequest = await id2JoinRequestPromise;
await socket1.acceptPartyMember(id2JoinRequest.party_id, id2JoinRequest.presences[0]);
socket1.promotePartyMember(id2JoinRequest.party_id, id2JoinRequest.presences[0]);
const id2PresencePromotedPromise = new Promise<PartyLeader>((resolve, reject) => {
socket1.onpartyleader = (leader) => {
resolve(leader);
}
});
return id2PresencePromotedPromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
expect(response.presence).toBeDefined();
});
it.each(adapters)('should create closed party and have member join and then join match', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const customid3 = generateid();
const response : MatchmakerMatched = await page.evaluate(async (customid1, customid2, customid3, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const client3 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket3 = client3.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
const session3 = await client3.authenticateCustom(customid3);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
await socket3.connect(session3, false);
const id1PresenceJoinPromise = new Promise<PartyPresenceEvent>((resolve, reject) => {
socket1.onpartypresence = (presence) => {
resolve(presence);
}
});
socket1.createParty(false, 3);
const id1PresenceEvent = await id1PresenceJoinPromise;
const id2JoinRequestPromise = new Promise<PartyJoinRequest>((resolve, reject) => {
socket1.onpartyjoinrequest = (request) => {
resolve(request);
}
});
socket2.joinParty(id1PresenceEvent.party_id);
const id2JoinRequest : PartyJoinRequest = await id2JoinRequestPromise;
await socket1.acceptPartyMember(id2JoinRequest.party_id, id2JoinRequest.presences[0]);
await socket3.addMatchmaker("*", 3, 3);
socket1.addMatchmakerParty(id1PresenceEvent.party_id, "*", 3, 3);
const id1MatchedPromise = new Promise<MatchmakerMatched>((resolve, reject) => {
socket1.onmatchmakermatched = (request) => {
resolve(request);
}
});
return id1MatchedPromise;
}, customid1, customid2, customid3, adapter);
expect(response).toBeDefined();
expect(response.token).toBeDefined();
expect(response.users.length).toEqual(3);
expect(response.self.party_id).toBeDefined();
}, matchmakerTimeout);
it.each(adapters)('should create party and add matchmaker and leave matchmaker', async (adapter) => {
const page = await createPage();
const customid1 = generateid();
const customid2 = generateid();
const response = await page.evaluate(async (customid1, customid2, adapter) => {
const client1 = new nakamajs.Client();
const client2 = new nakamajs.Client();
const socket1 = client1.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const socket2 = client2.createSocket(false, false,
adapter == AdapterType.Protobuf ? new nakamajsprotobuf.WebSocketAdapterPb() : new nakamajs.WebSocketAdapterText());
const session1 = await client1.authenticateCustom(customid1);
const session2 = await client2.authenticateCustom(customid2);
await socket1.connect(session1, false);
await socket2.connect(session2, false);
const party = await socket1.createParty(true, 1);
await socket2.joinParty(party.party_id);
const memberTicketPromise = new Promise<PartyMatchmakerTicket>((resolve, reject) => {
socket2.onpartymatchmakerticket = (ticket) => {
resolve(ticket);
}
});
const leaderTicketPromise = socket1.addMatchmakerParty(party.party_id, "*", 3, 3);
const allTickets = await Promise.all([leaderTicketPromise, memberTicketPromise]);
await socket1.removeMatchmakerParty(allTickets[0].party_id, allTickets[0].ticket);
return leaderTicketPromise;
}, customid1, customid2, adapter);
expect(response).toBeDefined();
expect(response.party_id).toBeDefined();
expect(response.ticket).toBeDefined();
});
}); | the_stack |
import { BasePlugin, Func, HeaderGetter, HeaderSetter, Span, TraceOptions, MessageEventType, SpanKind, CanonicalCode } from '@opencensus/core'
import * as httpModule from 'http'
import * as semver from 'semver'
import * as shimmer from 'shimmer'
import * as url from 'url'
import * as uuid from 'uuid'
import { kMiddlewareStack } from './express'
export type IgnoreMatcher<T> = string | RegExp | ((url: string, request: T) => boolean)
export type HttpPluginConfig = {
/**
* Ignore specific incoming request depending on their path
*/
ignoreIncomingPaths: Array<IgnoreMatcher<httpModule.IncomingMessage>>
/**
* Ignore specific outgoing request depending on their url
*/
ignoreOutgoingUrls: Array<IgnoreMatcher<httpModule.ClientRequest>>
/**
* Disable the creation of root span with http server
* mainly used if net plugin is implemented
*/
createSpanWithNet: boolean
}
export type HttpModule = typeof httpModule
export type RequestFunction = typeof httpModule.request
/** Http instrumentation plugin for Opencensus */
export class HttpPlugin extends BasePlugin {
/**
* Attributes Names according to Opencensus HTTP Specs
* https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/HTTP.md
*/
static ATTRIBUTE_HTTP_HOST = 'http.host'
static ATTRIBUTE_HTTP_METHOD = 'http.method'
static ATTRIBUTE_HTTP_PATH = 'http.path'
static ATTRIBUTE_HTTP_ROUTE = 'http.route'
static ATTRIBUTE_HTTP_USER_AGENT = 'http.user_agent'
static ATTRIBUTE_HTTP_STATUS_CODE = 'http.status_code'
// NOT ON OFFICIAL SPEC
static ATTRIBUTE_HTTP_ERROR_NAME = 'http.error_name'
static ATTRIBUTE_HTTP_ERROR_MESSAGE = 'http.error_message'
protected options: HttpPluginConfig
/** Constructs a new HttpPlugin instance. */
constructor (moduleName: string) {
super(moduleName)
}
/**
* Patches HTTP incoming and outcoming request functions.
*/
protected applyPatch () {
this.logger.debug('applying patch to %s@%s', this.moduleName, this.version)
shimmer.wrap(
this.moduleExports, 'request', this.getPatchOutgoingRequestFunction())
// In Node 8, http.get calls a private request method, therefore we patch it
// here too.
if (semver.satisfies(this.version, '>=8.0.0')) {
shimmer.wrap(
this.moduleExports, 'get', () => {
// Re-implement http.get. This needs to be done (instead of using
// makeRequestTrace to patch it) because we need to set the trace
// context header before the returned ClientRequest is ended.
// The Node.js docs state that the only differences between request and
// get are that (1) get defaults to the HTTP GET method and (2) the
// returned request object is ended immediately.
// The former is already true (at least in supported Node versions up to
// v9), so we simply follow the latter.
// Ref:
// https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
// https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/plugins/plugin-http.ts#L198
return function getTrace (options, callback) {
const req = httpModule.request(options, callback)
req.end()
return req
}
})
}
if (this.moduleExports && this.moduleExports.Server &&
this.moduleExports.Server.prototype) {
shimmer.wrap(
this.moduleExports.Server.prototype, 'emit',
this.getPatchIncomingRequestFunction())
} else {
this.logger.error(
'Could not apply patch to %s.emit. Interface is not as expected.',
this.moduleName)
}
return this.moduleExports
}
/** Unpatches all HTTP patched function. */
protected applyUnpatch (): void {
shimmer.unwrap(this.moduleExports, 'request')
if (semver.satisfies(this.version, '>=8.0.0')) {
shimmer.unwrap(this.moduleExports, 'get')
}
if (this.moduleExports && this.moduleExports.Server &&
this.moduleExports.Server.prototype) {
shimmer.unwrap(this.moduleExports.Server.prototype, 'emit')
}
}
/**
* Check whether the given request is ignored by configuration
* @param url URL of request
* @param request Request to inspect
* @param list List of ignore patterns
*/
protected isIgnored<T> (
url: string, request: T, list: Array<IgnoreMatcher<T>>): boolean {
if (!list) {
// No ignored urls - trace everything
return false
}
for (const pattern of list) {
if (this.isSatisfyPattern(url, request, pattern)) {
return true
}
}
return false
}
/**
* Check whether the given request match pattern
* @param url URL of request
* @param request Request to inspect
* @param pattern Match pattern
*/
protected isSatisfyPattern<T> (
url: string, request: T, pattern: IgnoreMatcher<T>): boolean {
if (typeof pattern === 'string') {
return pattern === url
} else if (pattern instanceof RegExp) {
return pattern.test(url)
} else if (typeof pattern === 'function') {
return pattern(url, request)
} else {
throw new TypeError('Pattern is in unsupported datatype')
}
}
/**
* Creates spans for incoming requests, restoring spans' context if applied.
*/
protected getPatchIncomingRequestFunction () {
return (original: (event: string) => boolean) => {
const plugin = this
// This function's signature is that of an event listener, which can have
// any number of variable-type arguments.
// tslint:disable-next-line:no-any
return function incomingRequest (event: string, ...args: any[]): boolean {
// Only traces request events
if (event !== 'request') {
return original.apply(this, arguments)
}
const request: httpModule.IncomingMessage = args[0]
const response: httpModule.ServerResponse = args[1]
// @ts-ignore
const path = url.parse(request.url).pathname
plugin.logger.debug('%s plugin incomingRequest', plugin.moduleName)
if (plugin.isIgnored(path, request, plugin.options.ignoreIncomingPaths)) {
return original.apply(this, arguments)
}
const propagation = plugin.tracer.propagation
const headers = request.headers
const getter: HeaderGetter = {
getHeader (name: string) {
return headers[name]
}
}
const context = propagation ? propagation.extract(getter) : null
const traceOptions: TraceOptions = {
name: path,
kind: SpanKind.SERVER,
spanContext: context !== null ? context : undefined
}
return plugin.createSpan(traceOptions, rootSpan => {
if (!rootSpan) return original.apply(this, arguments)
plugin.tracer.wrapEmitter(request)
plugin.tracer.wrapEmitter(response)
// Wraps end (inspired by:
// https://github.com/GoogleCloudPlatform/cloud-trace-nodejs/blob/master/src/plugins/plugin-connect.ts#L75)
const originalEnd = response.end
response.end = function (this: httpModule.ServerResponse) {
response.end = originalEnd
const returned = response.end.apply(this, arguments)
const requestUrl = url.parse(request.url || 'localhost')
const host = headers.host || 'localhost'
const userAgent =
(headers['user-agent'] || headers['User-Agent']) as string
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_HOST,
host.replace(/^(.*)(\:[0-9]{1,5})/, '$1'))
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_METHOD, request.method || 'GET')
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_PATH, `${requestUrl.pathname}`)
let route = `${requestUrl.path}`
const middlewareStack: string[] = request[kMiddlewareStack]
if (middlewareStack) {
route = middlewareStack
.filter(path => path !== '/')
.map(path => {
return path[0] === '/' ? path : '/' + path
}).join('')
}
rootSpan.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ROUTE, route)
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent)
rootSpan.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE,
response.statusCode.toString())
rootSpan.setStatus(HttpPlugin.convertTraceStatus(response.statusCode))
// Message Event ID is not defined
rootSpan.addMessageEvent(
MessageEventType.RECEIVED, uuid.v4().split('-').join(''))
rootSpan.end()
return returned
}
return original.apply(this, arguments)
})
}
}
}
/**
* Creates spans for outgoing requests, sending spans' context for distributed
* tracing.
*/
protected getPatchOutgoingRequestFunction () {
return (original: Func<httpModule.ClientRequest>): Func<
httpModule.ClientRequest> => {
const plugin = this
const kind = plugin.moduleName === 'https' ? 'HTTPS' : 'HTTP'
return function outgoingRequest (
options: httpModule.RequestOptions | string,
callback): httpModule.ClientRequest {
if (!options) {
return original.apply(this, arguments)
}
// Makes sure the url is an url object
let pathname = ''
let method = 'GET'
let origin = ''
if (typeof (options) === 'string') {
const parsedUrl = url.parse(options)
options = parsedUrl
pathname = parsedUrl.pathname || '/'
origin = `${parsedUrl.protocol || 'http:'}//${parsedUrl.host}`
} else {
// Do not trace ourselves
if (options.headers &&
options.headers['x-opencensus-outgoing-request']) {
plugin.logger.debug(
'header with "x-opencensus-outgoing-request" - do not trace')
return original.apply(this, arguments)
}
try {
pathname = (options as url.URL).pathname || ''
if (pathname.length === 0 && typeof options.path === 'string') {
pathname = url.parse(options.path).pathname || ''
}
method = options.method || 'GET'
origin = `${options.protocol || 'http:'}//${options.host}`
} catch (e) {
return original.apply(this, arguments)
}
}
const request: httpModule.ClientRequest =
original.apply(this, arguments)
if (plugin.isIgnored(origin + pathname, request, plugin.options.ignoreOutgoingUrls)) {
return request
}
plugin.tracer.wrapEmitter(request)
plugin.logger.debug('%s plugin outgoingRequest', plugin.moduleName)
const traceOptions = {
name: `${kind.toLowerCase()}-${(method || 'GET').toLowerCase()}`,
kind: SpanKind.CLIENT
}
// Checks if this outgoing request is part of an operation by checking
// if there is a current root span, if so, we create a child span. In
// case there is no root span, this means that the outgoing request is
// the first operation, therefore we create a root span.
if (!plugin.tracer.currentRootSpan) {
plugin.logger.debug('outgoingRequest starting a root span')
return plugin.tracer.startRootSpan(
traceOptions,
plugin.getMakeRequestTraceFunction(request, options, plugin))
} else {
plugin.logger.debug('outgoingRequest starting a child span')
const span = plugin.tracer.startChildSpan(
traceOptions.name, traceOptions.kind)
return (plugin.getMakeRequestTraceFunction(request, options, plugin))(
span)
}
}
}
}
/**
* Injects span's context to header for distributed tracing and finshes the
* span when the response is finished.
* @param original The original patched function.
* @param options The arguments to the original function.
*/
private getMakeRequestTraceFunction (
request: httpModule.ClientRequest, options: httpModule.RequestOptions,
plugin: HttpPlugin): Func<httpModule.ClientRequest> {
return (span: Span): httpModule.ClientRequest => {
plugin.logger.debug('makeRequestTrace')
if (!span) {
plugin.logger.debug('makeRequestTrace span is null')
return request
}
const setter: HeaderSetter = {
setHeader (name: string, value: string) {
// If outgoing request headers contain the "Expect" header, the returned
// ClientRequest will throw an error if any new headers are added. For this
// reason, only in this scenario, we opt to clone the options object to
// inject the trace context header instead of using ClientRequest#setHeader.
// (We don't do this generally because cloning the options object is an
// expensive operation.)
if (plugin.hasExpectHeader(options) && options.headers) {
// @ts-ignore
if (options.__cloned !== true) {
options = Object.assign({}, options) as httpModule.ClientRequestArgs
options.headers = Object.assign({}, options.headers)
// @ts-ignore
options.__cloned = true
}
// Inject the trace context header.
options.headers[name] = value
} else {
request.setHeader(name, value)
}
}
}
const propagation = plugin.tracer.propagation
if (propagation) {
propagation.inject(setter, span.spanContext)
}
request.on('response', (response: httpModule.IncomingMessage) => {
plugin.tracer.wrapEmitter(response)
plugin.logger.debug('outgoingRequest on response()')
response.on('end', () => {
plugin.logger.debug('outgoingRequest on end()')
const method = response.method ? response.method : 'GET'
const headers = options.headers
const userAgent =
headers ? (headers['user-agent'] || headers['User-Agent']) : null
if (options.host || options.hostname) {
const value = options.host || options.hostname
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_HOST, `${value}`)
}
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_METHOD, method)
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_PATH, `${options.path}`)
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ROUTE, `${options.path}`)
if (userAgent) {
span.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_USER_AGENT, userAgent.toString())
}
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_STATUS_CODE, `${response.statusCode}`)
span.setStatus(HttpPlugin.convertTraceStatus(response.statusCode || 0))
// Message Event ID is not defined
span.addMessageEvent(MessageEventType.SENT, uuid.v4().split('-').join(''))
span.end()
})
response.on('error', error => {
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_NAME, error.name)
span.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, error.message)
span.setStatus(CanonicalCode.UNKNOWN)
span.end()
})
})
request.on('error', error => {
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_NAME, error.name)
span.addAttribute(
HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, error.message)
span.setStatus(CanonicalCode.UNKNOWN)
span.end()
})
plugin.logger.debug('makeRequestTrace return request')
return request
}
}
private createSpan<T> (options: TraceOptions, fn: (span: Span) => T): T {
const forceChildspan = this.options.createSpanWithNet === true
if (forceChildspan) {
const span = this.tracer.startChildSpan(options.name, options.kind)
return fn(span)
} else {
return this.tracer.startRootSpan(options, fn)
}
}
/**
* Converts an HTTP status code to an OpenCensus Trace status code.
* @param statusCode The HTTP status code to convert.
*/
static convertTraceStatus (statusCode: number): number {
if (statusCode < 200 || statusCode > 504) {
return TraceStatusCodes.UNKNOWN
} else if (statusCode >= 200 && statusCode < 400) {
return TraceStatusCodes.OK
} else {
switch (statusCode) {
case (400):
return TraceStatusCodes.INVALID_ARGUMENT
case (504):
return TraceStatusCodes.DEADLINE_EXCEEDED
case (404):
return TraceStatusCodes.NOT_FOUND
case (403):
return TraceStatusCodes.PERMISSION_DENIED
case (401):
return TraceStatusCodes.UNAUTHENTICATED
case (429):
return TraceStatusCodes.RESOURCE_EXHAUSTED
case (501):
return TraceStatusCodes.UNIMPLEMENTED
case (503):
return TraceStatusCodes.UNAVAILABLE
default:
return TraceStatusCodes.UNKNOWN
}
}
}
/**
* Returns whether the Expect header is on the given options object.
* @param options Options for http.request.
*/
hasExpectHeader (options: httpModule.ClientRequestArgs | url.URL): boolean {
return !!(
(options as httpModule.ClientRequestArgs).headers &&
(options as httpModule.ClientRequestArgs).headers!.Expect)
}
}
/**
* An enumeration of OpenCensus Trace status codes.
*/
export enum TraceStatusCodes {
UNKNOWN = 2,
OK = 0,
INVALID_ARGUMENT = 3,
DEADLINE_EXCEEDED = 4,
NOT_FOUND = 5,
PERMISSION_DENIED = 7,
UNAUTHENTICATED = 16,
RESOURCE_EXHAUSTED = 8,
UNIMPLEMENTED = 12,
UNAVAILABLE = 14
}
export const plugin = new HttpPlugin('http') | the_stack |
import { SearchOperator } from "../Queries/SearchOperator";
import { OrderingType } from "./OrderingType";
import { MethodCall } from "./MethodCall";
import { WhereParams } from "./WhereParams";
import { DynamicSpatialField } from "../Queries/Spatial/DynamicSpatialField";
import { SpatialCriteria } from "../Queries/Spatial/SpatialCriteria";
import { GroupBy } from "../Queries/GroupBy";
import { DocumentType } from "../DocumentAbstractions";
import { MoreLikeThisScope } from "../Queries/MoreLikeThis/MoreLikeThisScope";
import { SuggestionBase } from "../Queries/Suggestions/SuggestionBase";
import { HighlightingParameters } from "../Queries/Highlighting/HighlightingParameters";
import { ValueCallback } from "../../Types/Callbacks";
import { Highlightings } from "../Queries/Highlighting/Hightlightings";
import { IncludeBuilderBase } from "./Loaders/IncludeBuilderBase";
import { DocumentConventions } from "../Conventions/DocumentConventions";
export interface IAbstractDocumentQuery<T> {
indexName: string;
collectionName: string;
/**
* Gets the document convention from the query session
*/
conventions: DocumentConventions;
/**
* Determines if it is a dynamic map-reduce query
*/
isDynamicMapReduce(): boolean;
/**
* Instruct the query to wait for non stale result for the specified wait timeout.
*/
_waitForNonStaleResults(waitTimeout: number): void;
/**
* Gets the fields for projection
*/
getProjectionFields(): string[];
/**
* Order the search results randomly
*/
_randomOrdering(): void;
/**
* Order the search results randomly using the specified seed
* this is useful if you want to have repeatable random queries
*/
_randomOrdering(seed: string): void;
//TBD 4.1 void _customSortUsing(String typeName);
//TBD 4.1 void _customSortUsing(String typeName, boolean descending);
/**
* Includes the specified path in the query, loading the document specified in that path
*/
_include(path: string): void;
/**
* Includes the specified documents and/or counters in the query, specified by IncludeBuilder
* @param includes builder
*/
_include(includes: IncludeBuilderBase): void;
// TBD expr linq void Include(Expression<Func<T, object>> path);
/**
* Takes the specified count.
*/
_take(count: number): void;
/**
* Skips the specified count.
*/
_skip(count: number): void;
/**
* Matches value
*/
_whereEquals(fieldName: string, value: any): void;
/**
* Matches value
*/
_whereEquals(fieldName: string, value: any, exact: boolean): void;
/**
* Matches value
*/
_whereEquals(fieldName: string, method: MethodCall): void;
/**
* Matches value
*/
_whereEquals(fieldName: string, method: MethodCall, exact: boolean): void;
/**
* Matches value
*/
_whereEquals(whereParams: WhereParams): void;
/**
* Not matches value
*/
_whereNotEquals(fieldName: string, value: any): void;
/**
* Not matches value
*/
_whereNotEquals(fieldName: string, value: any, exact: boolean): void;
/**
* Not matches value
*/
_whereNotEquals(fieldName: string, method: MethodCall): void;
/**
* Not matches value
*/
_whereNotEquals(fieldName: string, method: MethodCall, exact: boolean): void;
/**
* Not matches value
*/
_whereNotEquals(whereParams: WhereParams): void;
/**
* Simplified method for opening a new clause within the query
*/
_openSubclause(): void;
/**
* Simplified method for closing a clause within the query
*/
_closeSubclause(): void;
/**
* Negate the next operation
*/
_negateNext(): void;
/**
* Check that the field has one of the specified value
*/
_whereIn(fieldName: string, values: any[]): void;
/**
* Check that the field has one of the specified value
*/
_whereIn(fieldName: string, values: any[], exact: boolean): void;
/**
* Matches fields which starts with the specified value.
*/
_whereStartsWith(fieldName: string, value: any): void;
/**
* Matches fields which starts with the specified value.
*/
_whereStartsWith(fieldName: string, value: any, exact: boolean): void;
/**
* Matches fields which ends with the specified value.
*/
_whereEndsWith(fieldName: string, value: any): void;
/**
* Matches fields which ends with the specified value.
*/
_whereEndsWith(fieldName: string, value: any, exact: boolean): void;
/**
* Matches fields where the value is between the specified start and end, inclusive
*/
_whereBetween(fieldName: string, start: any, end: any): void;
/**
* Matches fields where the value is between the specified start and end, inclusive
*/
_whereBetween(fieldName: string, start: any, end: any, exact: boolean): void;
/**
* Matches fields where the value is greater than the specified value
*/
_whereGreaterThan(fieldName: string, value: any): void;
/**
* Matches fields where the value is greater than the specified value
*/
_whereGreaterThan(fieldName: string, value: any, exact: boolean): void;
/**
* Matches fields where the value is greater than or equal to the specified value
*/
_whereGreaterThanOrEqual(fieldName: string, value: any): void;
/**
* Matches fields where the value is greater than or equal to the specified value
*/
_whereGreaterThanOrEqual(fieldName: string, value: any, exact: boolean): void;
/**
* Matches fields where the value is less than the specified value
*/
_whereLessThan(fieldName: string, value: any): void;
/**
* Matches fields where the value is less than the specified value
*/
_whereLessThan(fieldName: string, value: any, exact: boolean): void;
/**
* Matches fields where the value is less than or equal to the specified value
*/
_whereLessThanOrEqual(fieldName: string, value: any): void;
/**
* Matches fields where the value is less than or equal to the specified value
*/
_whereLessThanOrEqual(fieldName: string, value: any, exact: boolean): void;
_whereExists(fieldName: string): void;
_whereRegex(fieldName: string, pattern: string): void;
/**
* Add an AND to the query
*/
_andAlso(): void;
/**
* Add an OR to the query
*/
_orElse(): void;
/**
* Specifies a boost weight to the last where clause.
* The higher the boost factor, the more relevant the term will be.
*
* boosting factor where 1.0 is default, less than 1.0 is lower weight, greater than 1.0 is higher weight
*
* http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Boosting%20a%20Term
*/
_boost(boost: number): void;
/**
* Specifies a fuzziness factor to the single word term in the last where clause
*
* 0.0 to 1.0 where 1.0 means closer match
*
* http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Fuzzy%20Searches
*/
_fuzzy(fuzzy: number): void;
/**
* Specifies a proximity distance for the phrase in the last search clause
*
* http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Proximity%20Searches
*/
_proximity(proximity: number): void;
/**
* Order the results by the specified fields
* The field is the name of the field to sort, defaulting to sorting by ascending.
*/
_orderBy(field: string): void;
/**
* Order the results by the specified fields
* The field is the name of the field to sort, defaulting to sorting by ascending.
*/
_orderBy(field: string, ordering: OrderingType): void;
/**
* Order the results by the specified fields
* The field is the name of the field to sort using sorterName
*/
_orderBy(field: string, options: { sorterName: string }): void;
_orderByDescending(field: string): void;
_orderByDescending(field: string, ordering: OrderingType): void;
_orderByDescending(field: string, options: { sorterName: string }): void;
_orderByScore(): void;
_orderByScoreDescending(): void;
_highlight(
parameters: HighlightingParameters,
highlightingsCallback: ValueCallback<Highlightings>): void;
/**
* Perform a search for documents which fields that match the searchTerms.
* If there is more than a single term, each of them will be checked independently.
*/
_search(fieldName: string, searchTerms: string): void;
/**
* Perform a search for documents which fields that match the searchTerms.
* If there is more than a single term, each of them will be checked independently.
*/
_search(fieldName: string, searchTerms: string, operator: SearchOperator): void;
toString(): string;
_intersect(): void;
addRootType(clazz: DocumentType): void;
_distinct(): void;
/**
* Performs a query matching ANY of the provided values against the given field (OR)
*/
_containsAny(fieldName: string, values: any[]): void;
/**
* Performs a query matching ALL of the provided values against the given field (AND)
*/
_containsAll(fieldName: string, values: any[]): void;
_groupBy(fieldName: string, ...fieldNames: string[]): void;
_groupBy(field: GroupBy, ...fields: GroupBy[]): void;
_groupByKey(fieldName: string): void;
_groupByKey(fieldName: string, projectedName: string): void;
_groupBySum(fieldName: string): void;
_groupBySum(fieldName: string, projectedName: string): void;
_groupByCount(): void;
_groupByCount(projectedName: string): void;
_whereTrue(): void;
_spatial(field: DynamicSpatialField, criteria: SpatialCriteria): void;
_spatial(fieldName: string, criteria: SpatialCriteria): void;
_orderByDistance(field: DynamicSpatialField, latitude: number, longitude: number): void;
_orderByDistance(fieldName: string, latitude: number, longitude: number): void;
_orderByDistance(fieldName: string, latitude: number, longitude: number, roundFactor: number): void;
_orderByDistance(field: DynamicSpatialField, shapeWkt: string): void;
_orderByDistance(fieldName: string, shapeWkt: string): void;
_orderByDistance(fieldName: string, shapeWkt: string, roundFactor: number): void;
_orderByDistanceDescending(field: DynamicSpatialField, latitude: number, longitude: number): void;
_orderByDistanceDescending(fieldName: string, latitude: number, longitude: number): void;
_orderByDistanceDescending(fieldName: string, latitude: number, longitude: number, roundFactor: number): void;
_orderByDistanceDescending(field: DynamicSpatialField, shapeWkt: string): void;
_orderByDistanceDescending(fieldName: string, shapeWkt: string): void;
_orderByDistanceDescending(fieldName: string, shapeWkt: string, roundFactor: number): void;
_moreLikeThis(): MoreLikeThisScope;
addAliasToIncludesTokens(fromAlias: string): string;
// TBD void AggregateBy(FacetBase facet);
// TBD IAggregationDocumentQuery<T> AggregateBy(Action<IFacetBuilder<T>> builder);
// TBD void AggregateUsing(string facetSetupDocumentId);
_suggestUsing(suggestion: SuggestionBase);
parameterPrefix: string;
iterator(): Promise<IterableIterator<T>>;
} | the_stack |
/// <reference types="node" />
/// <reference types="bytebuffer" />
import { EventEmitter } from 'events';
export class CMClient extends EventEmitter {
/**
* A boolean that indicates whether you are currently connected and the encryption handshake is complete.
* 'connected' is emitted when it changes to true, and 'error' is emitted when it changes to false unless you called disconnect.
* Sending any client messages is only allowed while this is true.
*/
connected: boolean;
/**
* A boolean that indicates whether you are currently logged on.
* Calling any handler methods except for methods to log on is only allowed while logged on.
*/
loggedOn: boolean;
/**
* Your own SteamID while logged on, otherwise unspecified.
* Must be set to a valid initial value before sending a logon message.
*/
steamID: string;
/**
* If we've initiated a connection previously, a string containing "ipv4:port" for the server we're connecting/connected to.
* Also contains the address of the last host we were connected to if we're currently disconnected.
*/
remoteAddress: string;
// Default is TCP. UDP support is experimental
constructor(protocol?: EConnectionProtocol);
/**
* Override the address and/or port that will be used for the outgoing connection.
* Takes effect the next time you connect.
*
* @param localAddress The local IP address you want to use for the outgoing connection
* @param localPort The local port you want to use for the outgoing connection
*/
bind(localAddress?: string, localPort?: string | number): void;
/**
* Connects to Steam.It will keep trying to reconnect (provided autoRetry is not false) until encryption handshake is complete (see 'connected'), unless you cancel it with disconnect.
*
* You can call this method at any time. If you are already connected, disconnects you first. If there is an ongoing connection attempt, cancels it.
*
* @param server If you want to connect to a specific CM server, provide an object here containing host and port properties. Default is a random value from the servers property.
* @param autoRetry true if you want to automatically retry connection until successful, or false if you want an error event if connection fails. Default true
*/
connect(server?: Server, autoRetry?: boolean): void;
/**
* Immediately terminates the connection and prevents any events (including 'error') from being emitted until you connect again.
* If you are already disconnected, does nothing.
* If there is an ongoing connection attempt, cancels it.
*/
disconnect(): void;
/**
* Send a logon message to the CM.
* You must first be connected and set steamID to a valid initial value.
* You will receive the response in the logOnResponse event.
*
* @param details An object containing your logon parameters
*/
logOn(details: CMsgClientLogonPassword | CMsgClientLogonLoginKey): void;
/**
*
* @param header
* @param body
* @param callback
*/
send: SendMessage;
// Events
on<T extends keyof CMEventCallback>(eventType: T, callback: CMEventCallback[T]): this;
}
/**
* Steam.servers contains the list of CM servers that CMClient will attempt to connect to.
* The bootstrapped list is not always up-to-date and might contain dead servers.
* To avoid timeouts, replace it with your own list before logging in if you have one (see 'servers' event).
*/
export const servers: Server[];
export type SendMessage = (
/**
* An object containing the message header. It has the following properties:
* The following fields are reserved for internal use and shall be ignored: steamid, client_sessionid, jobid_source, jobid_target.
* (Note: pass an empty object if you don't need to set any fields)
*/
header: {
/**
* A value from EMsg
*/
msg: EMsg,
/**
* A CMsgProtoBufHeader object if this message is protobuf-backed, otherwise header.proto is falsy.
*/
proto?: CMsgProtoBufHeader | false | undefined
},
/**
* A Buffer or ByteBuffer containing the rest of the message
*/
body: Buffer | ByteBuffer,
/**
* If not falsy, then this message is a request, and callback shall be called with any response to it instead of 'message'/send. callback has the same arguments as 'message'/send.
*/
callback?: SendMessage | false
) => void;
export interface CMEventCallback {
/**
* Connection closed by the server.
* Only emitted if the encryption handshake is complete, otherwise it will reconnect automatically (unless you disabled autoRetry).
* loggedOn is now false.
*
* @param err An Error object. May contain an eresult property.
*/
error: (err: Error) => void;
/**
* Encryption handshake complete.
* From now on, it's your responsibility to handle disconnections and reconnect (see error).
* You'll likely want to log on now.
*
* @param serverLoad The load value of the CM server you're connected to. Only available if you're connecting using UDP. It's unclear at this time what scale this value uses.
*/
connected: (serverLoad: string) => void;
/**
* Logon response received. If eresult is EResult.OK, loggedOn is now true.
*
* @param response An object with the properties in CMsgClientLogonResponse
*/
logOnResponse: (response: CMsgClientLogonResponse) => void;
/**
* CMClient will use this new list when reconnecting, but it will be lost when your application restarts.
* You might want to save it to a file or a database and assign it to Steam.servers before logging in next time.
*
* Note that Steam.servers will be automatically updated after this event is emitted.
* This will be useful if you want to compare the old list with the new one for some reason - otherwise it shouldn't matter.
*
* @param servers An array containing the up-to-date server list
*/
servers: (servers: Server[]) => void;
/**
* You were logged off from Steam. loggedOn is now false.
*
* @param eresesult A value from EResult
*/
loggedOff: (eresesult: EResult) => void;
message: SendMessage;
}
export interface Server {
host: string;
port: string | number;
}
// Protobufs
export interface CMsgClientLogon {
/**
* Your steam login
*/
account_name: string;
/**
* Steam Guard code. Must be valid if provided, otherwise the logon will fail. Note that Steam Guard codes expire after a short while
*/
auth_code?: string | undefined;
/**
* Two-factor authentication code provided by the Steam mobile application. You will have to provide this code every time you log in if your account uses 2FA.
*/
two_factor_code?: string | undefined;
/**
* SHA1 hash of your sentry file.
* If not provided, Steam will send you a sentry file through the ClientUpdateMachineAuth message
* (unless a limit for registered sentries is reached? see https://github.com/seishun/node-steam/issues/178).
* If no Steam Guard code is provided, the hash must be already registered with this account, otherwise it's ignored.
* This value will be ignored if you enable 2FA.
*/
sha_sentryfile?: string | undefined;
}
export interface CMsgClientLogonPassword extends CMsgClientLogon {
/**
* Required unless login_key is used
*/
password: string;
}
export interface CMsgClientLogonLoginKey extends CMsgClientLogon {
/**
* Alternative to password
*/
login_key: string;
}
export interface CMsgClientLogonResponse {
/**
* The logon was successful if equal to EResult.OK
*/
eresult: EResult;
/**
* "loginkey" to be used with WebAPI's AuthenticateUser."
*/
webapi_authenticate_user_nonce: string;
}
export interface CMsgProtoBufHeader {
steamid?: string | undefined;
client_sessionid?: number | undefined;
routing_appid?: number | undefined;
jobid_source?: string | undefined;
jobid_target?: string | undefined;
target_job_name?: string | undefined;
seq_num?: number | undefined;
eresult?: number | undefined;
error_message?: string | undefined;
ip?: number | undefined;
auth_account_flags?: number | undefined;
token_source?: number | undefined;
admin_spoofing_user?: boolean | undefined;
transport_error?: number | undefined;
messageid?: string | undefined;
publisher_group_id?: number | undefined;
sysid?: number | undefined;
trace_tag?: string | undefined;
webapi_key_id?: number | undefined;
is_from_external_source?: boolean | undefined;
forward_to_sysid?: number[] | undefined;
}
// Enums
export enum EConnectionProtocol {
TCP = 1,
UDP = 2,
WebSocket = 3,
}
export enum EMsg {
Invalid = 0,
Multi = 1,
ProtobufWrapped = 2,
BaseGeneral = 100,
GenericReply = 100,
DestJobFailed = 113,
Alert = 115,
SCIDRequest = 120,
SCIDResponse = 121,
JobHeartbeat = 123,
HubConnect = 124,
Subscribe = 126,
RouteMessage = 127, // obsolete
RemoteSysID = 128, // obsolete
AMCreateAccountResponse = 129,
WGRequest = 130,
WGResponse = 131,
KeepAlive = 132,
WebAPIJobRequest = 133,
WebAPIJobResponse = 134,
ClientSessionStart = 135,
ClientSessionEnd = 136,
ClientSessionUpdateAuthTicket = 137, // obsolete "renamed to ClientSessionUpdate"
ClientSessionUpdate = 137,
StatsDeprecated = 138, // obsolete
Ping = 139,
PingResponse = 140,
Stats = 141,
RequestFullStatsBlock = 142,
LoadDBOCacheItem = 143,
LoadDBOCacheItemResponse = 144,
InvalidateDBOCacheItems = 145,
ServiceMethod = 146,
ServiceMethodResponse = 147,
ClientPackageVersions = 148,
TimestampRequest = 149,
TimestampResponse = 150,
BaseShell = 200,
AssignSysID = 200,
Exit = 201,
DirRequest = 202,
DirResponse = 203,
ZipRequest = 204,
ZipResponse = 205,
UpdateRecordResponse = 215,
UpdateCreditCardRequest = 221,
UpdateUserBanResponse = 225,
PrepareToExit = 226,
ContentDescriptionUpdate = 227,
TestResetServer = 228,
UniverseChanged = 229,
ShellConfigInfoUpdate = 230,
RequestWindowsEventLogEntries = 233,
ProvideWindowsEventLogEntries = 234,
ShellSearchLogs = 235,
ShellSearchLogsResponse = 236,
ShellCheckWindowsUpdates = 237,
ShellCheckWindowsUpdatesResponse = 238,
ShellFlushUserLicenseCache = 239, // obsolete
BaseGM = 300,
Heartbeat = 300,
ShellFailed = 301,
ExitShells = 307,
ExitShell = 308,
GracefulExitShell = 309,
NotifyWatchdog = 314,
LicenseProcessingComplete = 316,
SetTestFlag = 317,
QueuedEmailsComplete = 318,
GMReportPHPError = 319,
GMDRMSync = 320,
PhysicalBoxInventory = 321,
UpdateConfigFile = 322,
TestInitDB = 323,
GMWriteConfigToSQL = 324,
GMLoadActivationCodes = 325,
GMQueueForFBS = 326,
GMSchemaConversionResults = 327,
GMSchemaConversionResultsResponse = 328, // obsolete
GMWriteShellFailureToSQL = 329,
GMWriteStatsToSOS = 330,
GMGetServiceMethodRouting = 331,
GMGetServiceMethodRoutingResponse = 332,
GMConvertUserWallets = 333,
BaseAIS = 400,
AISRefreshContentDescription = 401, // obsolete
AISRequestContentDescription = 402,
AISUpdateAppInfo = 403,
AISUpdatePackageInfo = 404, // obsolete "renamed to AISUpdatePackageCosts"
AISUpdatePackageCosts = 404,
AISGetPackageChangeNumber = 405,
AISGetPackageChangeNumberResponse = 406,
AISAppInfoTableChanged = 407, // obsolete
AISUpdatePackageCostsResponse = 408,
AISCreateMarketingMessage = 409,
AISCreateMarketingMessageResponse = 410,
AISGetMarketingMessage = 411,
AISGetMarketingMessageResponse = 412,
AISUpdateMarketingMessage = 413,
AISUpdateMarketingMessageResponse = 414,
AISRequestMarketingMessageUpdate = 415,
AISDeleteMarketingMessage = 416,
AISGetMarketingTreatments = 419, // obsolete
AISGetMarketingTreatmentsResponse = 420, // obsolete
AISRequestMarketingTreatmentUpdate = 421, // obsolete
AISTestAddPackage = 422, // obsolete
AIGetAppGCFlags = 423,
AIGetAppGCFlagsResponse = 424,
AIGetAppList = 425,
AIGetAppListResponse = 426,
AIGetAppInfo = 427, // obsolete
AIGetAppInfoResponse = 428, // obsolete
AISGetCouponDefinition = 429,
AISGetCouponDefinitionResponse = 430,
AISUpdateSlaveContentDescription = 431,
AISUpdateSlaveContentDescriptionResponse = 432,
AISTestEnableGC = 433,
BaseAM = 500,
AMUpdateUserBanRequest = 504,
AMAddLicense = 505,
AMBeginProcessingLicenses = 507, // obsolete
AMSendSystemIMToUser = 508,
AMExtendLicense = 509,
AMAddMinutesToLicense = 510,
AMCancelLicense = 511,
AMInitPurchase = 512,
AMPurchaseResponse = 513,
AMGetFinalPrice = 514,
AMGetFinalPriceResponse = 515,
AMGetLegacyGameKey = 516,
AMGetLegacyGameKeyResponse = 517,
AMFindHungTransactions = 518,
AMSetAccountTrustedRequest = 519,
AMCompletePurchase = 521,
AMCancelPurchase = 522,
AMNewChallenge = 523,
AMLoadOEMTickets = 524,
AMFixPendingPurchase = 525,
AMFixPendingPurchaseResponse = 526,
AMIsUserBanned = 527,
AMRegisterKey = 528,
AMLoadActivationCodes = 529,
AMLoadActivationCodesResponse = 530,
AMLookupKeyResponse = 531,
AMLookupKey = 532,
AMChatCleanup = 533,
AMClanCleanup = 534,
AMFixPendingRefund = 535,
AMReverseChargeback = 536,
AMReverseChargebackResponse = 537,
AMClanCleanupList = 538,
AMGetLicenses = 539,
AMGetLicensesResponse = 540,
AllowUserToPlayQuery = 550,
AllowUserToPlayResponse = 551,
AMVerfiyUser = 552,
AMClientNotPlaying = 553,
ClientRequestFriendship = 554,
AMRelayPublishStatus = 555,
AMResetCommunityContent = 556, // obsolete
AMPrimePersonaStateCache = 557, // obsolete
AMAllowUserContentQuery = 558, // obsolete
AMAllowUserContentResponse = 559, // obsolete
AMInitPurchaseResponse = 560,
AMRevokePurchaseResponse = 561,
AMLockProfile = 562, // obsolete
AMRefreshGuestPasses = 563,
AMInviteUserToClan = 564,
AMAcknowledgeClanInvite = 565,
AMGrantGuestPasses = 566,
AMClanDataUpdated = 567,
AMReloadAccount = 568,
AMClientChatMsgRelay = 569,
AMChatMulti = 570,
AMClientChatInviteRelay = 571,
AMChatInvite = 572,
AMClientJoinChatRelay = 573,
AMClientChatMemberInfoRelay = 574,
AMPublishChatMemberInfo = 575,
AMClientAcceptFriendInvite = 576,
AMChatEnter = 577,
AMClientPublishRemovalFromSource = 578,
AMChatActionResult = 579,
AMFindAccounts = 580,
AMFindAccountsResponse = 581,
AMRequestAccountData = 582,
AMRequestAccountDataResponse = 583,
AMSetAccountFlags = 584,
AMCreateClan = 586,
AMCreateClanResponse = 587,
AMGetClanDetails = 588,
AMGetClanDetailsResponse = 589,
AMSetPersonaName = 590,
AMSetAvatar = 591,
AMAuthenticateUser = 592,
AMAuthenticateUserResponse = 593,
AMGetAccountFriendsCount = 594, // obsolete
AMGetAccountFriendsCountResponse = 595, // obsolete
AMP2PIntroducerMessage = 596,
ClientChatAction = 597,
AMClientChatActionRelay = 598,
BaseVS = 600,
ReqChallenge = 600,
VACResponse = 601,
ReqChallengeTest = 602,
VSMarkCheat = 604,
VSAddCheat = 605,
VSPurgeCodeModDB = 606,
VSGetChallengeResults = 607,
VSChallengeResultText = 608,
VSReportLingerer = 609,
VSRequestManagedChallenge = 610,
VSLoadDBFinished = 611,
BaseDRMS = 625,
DRMBuildBlobRequest = 628,
DRMBuildBlobResponse = 629,
DRMResolveGuidRequest = 630,
DRMResolveGuidResponse = 631,
DRMVariabilityReport = 633,
DRMVariabilityReportResponse = 634,
DRMStabilityReport = 635,
DRMStabilityReportResponse = 636,
DRMDetailsReportRequest = 637,
DRMDetailsReportResponse = 638,
DRMProcessFile = 639,
DRMAdminUpdate = 640,
DRMAdminUpdateResponse = 641,
DRMSync = 642,
DRMSyncResponse = 643,
DRMProcessFileResponse = 644,
DRMEmptyGuidCache = 645,
DRMEmptyGuidCacheResponse = 646,
BaseCS = 650,
CSUserContentRequest = 652, // obsolete
BaseClient = 700,
ClientLogOn_Deprecated = 701, // obsolete
ClientAnonLogOn_Deprecated = 702, // obsolete
ClientHeartBeat = 703,
ClientVACResponse = 704,
ClientGamesPlayed_obsolete = 705, // obsolete
ClientLogOff = 706,
ClientNoUDPConnectivity = 707,
ClientInformOfCreateAccount = 708,
ClientAckVACBan = 709, // obsolete
ClientConnectionStats = 710,
ClientInitPurchase = 711, // obsolete
ClientPingResponse = 712,
ClientRemoveFriend = 714,
ClientGamesPlayedNoDataBlob = 715,
ClientChangeStatus = 716,
ClientVacStatusResponse = 717,
ClientFriendMsg = 718,
ClientGameConnect_obsolete = 719, // obsolete
ClientGamesPlayed2_obsolete = 720, // obsolete
ClientGameEnded_obsolete = 721, // obsolete
ClientGetFinalPrice = 722, // obsolete
ClientSystemIM = 726,
ClientSystemIMAck = 727,
ClientGetLicenses = 728,
ClientCancelLicense = 729, // obsolete
ClientGetLegacyGameKey = 730,
ClientContentServerLogOn_Deprecated = 731, // obsolete
ClientAckVACBan2 = 732,
ClientAckMessageByGID = 735, // obsolete
ClientGetPurchaseReceipts = 736,
ClientAckPurchaseReceipt = 737, // obsolete
ClientGamesPlayed3_obsolete = 738, // obsolete
ClientSendGuestPass = 739, // obsolete
ClientAckGuestPass = 740,
ClientRedeemGuestPass = 741,
ClientGamesPlayed = 742,
ClientRegisterKey = 743,
ClientInviteUserToClan = 744,
ClientAcknowledgeClanInvite = 745,
ClientPurchaseWithMachineID = 746,
ClientAppUsageEvent = 747,
ClientGetGiftTargetList = 748, // obsolete
ClientGetGiftTargetListResponse = 749, // obsolete
ClientLogOnResponse = 751,
ClientVACChallenge = 753, // obsolete
ClientSetHeartbeatRate = 755,
ClientNotLoggedOnDeprecated = 756, // obsolete
ClientLoggedOff = 757,
GSApprove = 758,
GSDeny = 759,
GSKick = 760,
ClientCreateAcctResponse = 761,
ClientPurchaseResponse = 763,
ClientPing = 764,
ClientNOP = 765,
ClientPersonaState = 766,
ClientFriendsList = 767,
ClientAccountInfo = 768,
ClientVacStatusQuery = 770, // obsolete
ClientNewsUpdate = 771,
ClientGameConnectDeny = 773,
GSStatusReply = 774,
ClientGetFinalPriceResponse = 775, // obsolete
ClientGameConnectTokens = 779,
ClientLicenseList = 780,
ClientCancelLicenseResponse = 781, // obsolete
ClientVACBanStatus = 782,
ClientCMList = 783,
ClientEncryptPct = 784,
ClientGetLegacyGameKeyResponse = 785,
ClientFavoritesList = 786, // obsolete
CSUserContentApprove = 787, // obsolete
CSUserContentDeny = 788, // obsolete
ClientInitPurchaseResponse = 789, // obsolete
ClientAddFriend = 791,
ClientAddFriendResponse = 792,
ClientInviteFriend = 793, // obsolete
ClientInviteFriendResponse = 794, // obsolete
ClientSendGuestPassResponse = 795, // obsolete
ClientAckGuestPassResponse = 796,
ClientRedeemGuestPassResponse = 797,
ClientUpdateGuestPassesList = 798,
ClientChatMsg = 799,
ClientChatInvite = 800,
ClientJoinChat = 801,
ClientChatMemberInfo = 802,
ClientLogOnWithCredentials_Deprecated = 803, // obsolete
ClientPasswordChangeResponse = 805,
ClientChatEnter = 807,
ClientFriendRemovedFromSource = 808,
ClientCreateChat = 809,
ClientCreateChatResponse = 810,
ClientUpdateChatMetadata = 811, // obsolete
ClientP2PIntroducerMessage = 813,
ClientChatActionResult = 814,
ClientRequestFriendData = 815,
ClientGetUserStats = 818,
ClientGetUserStatsResponse = 819,
ClientStoreUserStats = 820,
ClientStoreUserStatsResponse = 821,
ClientClanState = 822,
ClientServiceModule = 830,
ClientServiceCall = 831,
ClientServiceCallResponse = 832,
ClientPackageInfoRequest = 833, // obsolete
ClientPackageInfoResponse = 834, // obsolete
ClientNatTraversalStatEvent = 839,
ClientAppInfoRequest = 840, // obsolete
ClientAppInfoResponse = 841, // obsolete
ClientSteamUsageEvent = 842,
ClientCheckPassword = 845,
ClientResetPassword = 846,
ClientCheckPasswordResponse = 848,
ClientResetPasswordResponse = 849,
ClientSessionToken = 850,
ClientDRMProblemReport = 851,
ClientSetIgnoreFriend = 855,
ClientSetIgnoreFriendResponse = 856,
ClientGetAppOwnershipTicket = 857,
ClientGetAppOwnershipTicketResponse = 858,
ClientGetLobbyListResponse = 860,
ClientGetLobbyMetadata = 861, // obsolete
ClientGetLobbyMetadataResponse = 862, // obsolete
ClientVTTCert = 863, // obsolete
ClientAppInfoUpdate = 866, // obsolete
ClientAppInfoChanges = 867, // obsolete
ClientServerList = 880,
ClientEmailChangeResponse = 891,
ClientSecretQAChangeResponse = 892,
ClientDRMBlobRequest = 896,
ClientDRMBlobResponse = 897,
ClientLookupKey = 898, // obsolete
ClientLookupKeyResponse = 899, // obsolete
BaseGameServer = 900,
GSDisconnectNotice = 901,
GSStatus = 903,
GSUserPlaying = 905,
GSStatus2 = 906,
GSStatusUpdate_Unused = 907,
GSServerType = 908,
GSPlayerList = 909,
GSGetUserAchievementStatus = 910,
GSGetUserAchievementStatusResponse = 911,
GSGetPlayStats = 918,
GSGetPlayStatsResponse = 919,
GSGetUserGroupStatus = 920,
AMGetUserGroupStatus = 921,
AMGetUserGroupStatusResponse = 922,
GSGetUserGroupStatusResponse = 923,
GSGetReputation = 936,
GSGetReputationResponse = 937,
GSAssociateWithClan = 938,
GSAssociateWithClanResponse = 939,
GSComputeNewPlayerCompatibility = 940,
GSComputeNewPlayerCompatibilityResponse = 941,
BaseAdmin = 1000,
AdminCmd = 1000,
AdminCmdResponse = 1004,
AdminLogListenRequest = 1005,
AdminLogEvent = 1006,
LogSearchRequest = 1007, // obsolete
LogSearchResponse = 1008, // obsolete
LogSearchCancel = 1009, // obsolete
UniverseData = 1010,
RequestStatHistory = 1014, // obsolete
StatHistory = 1015, // obsolete
AdminPwLogon = 1017, // obsolete
AdminPwLogonResponse = 1018, // obsolete
AdminSpew = 1019,
AdminConsoleTitle = 1020,
AdminGCSpew = 1023,
AdminGCCommand = 1024,
AdminGCGetCommandList = 1025,
AdminGCGetCommandListResponse = 1026,
FBSConnectionData = 1027,
AdminMsgSpew = 1028,
BaseFBS = 1100,
FBSReqVersion = 1100,
FBSVersionInfo = 1101,
FBSForceRefresh = 1102,
FBSForceBounce = 1103,
FBSDeployPackage = 1104,
FBSDeployResponse = 1105,
FBSUpdateBootstrapper = 1106,
FBSSetState = 1107,
FBSApplyOSUpdates = 1108,
FBSRunCMDScript = 1109,
FBSRebootBox = 1110,
FBSSetBigBrotherMode = 1111,
FBSMinidumpServer = 1112,
FBSSetShellCount_obsolete = 1113, // obsolete
FBSDeployHotFixPackage = 1114,
FBSDeployHotFixResponse = 1115,
FBSDownloadHotFix = 1116,
FBSDownloadHotFixResponse = 1117,
FBSUpdateTargetConfigFile = 1118,
FBSApplyAccountCred = 1119,
FBSApplyAccountCredResponse = 1120,
FBSSetShellCount = 1121,
FBSTerminateShell = 1122,
FBSQueryGMForRequest = 1123,
FBSQueryGMResponse = 1124,
FBSTerminateZombies = 1125,
FBSInfoFromBootstrapper = 1126,
FBSRebootBoxResponse = 1127,
FBSBootstrapperPackageRequest = 1128,
FBSBootstrapperPackageResponse = 1129,
FBSBootstrapperGetPackageChunk = 1130,
FBSBootstrapperGetPackageChunkResponse = 1131,
FBSBootstrapperPackageTransferProgress = 1132,
FBSRestartBootstrapper = 1133,
BaseFileXfer = 1200,
FileXferRequest = 1200,
FileXferResponse = 1201,
FileXferData = 1202,
FileXferEnd = 1203,
FileXferDataAck = 1204,
BaseChannelAuth = 1300,
ChannelAuthChallenge = 1300,
ChannelAuthResponse = 1301,
ChannelAuthResult = 1302,
ChannelEncryptRequest = 1303,
ChannelEncryptResponse = 1304,
ChannelEncryptResult = 1305,
BaseBS = 1400,
BSPurchaseStart = 1401,
BSPurchaseResponse = 1402, // obsolete
BSSettleNOVA = 1404, // obsolete
BSSettleComplete = 1406,
BSBannedRequest = 1407, // obsolete
BSInitPayPalTxn = 1408,
BSInitPayPalTxnResponse = 1409,
BSGetPayPalUserInfo = 1410,
BSGetPayPalUserInfoResponse = 1411,
BSRefundTxn = 1413, // obsolete
BSRefundTxnResponse = 1414, // obsolete
BSGetEvents = 1415, // obsolete
BSChaseRFRRequest = 1416, // obsolete
BSPaymentInstrBan = 1417,
BSPaymentInstrBanResponse = 1418,
BSProcessGCReports = 1419, // obsolete
BSProcessPPReports = 1420, // obsolete
BSInitGCBankXferTxn = 1421,
BSInitGCBankXferTxnResponse = 1422,
BSQueryGCBankXferTxn = 1423, // obsolete
BSQueryGCBankXferTxnResponse = 1424, // obsolete
BSCommitGCTxn = 1425,
BSQueryTransactionStatus = 1426,
BSQueryTransactionStatusResponse = 1427,
BSQueryCBOrderStatus = 1428, // obsolete
BSQueryCBOrderStatusResponse = 1429, // obsolete
BSRunRedFlagReport = 1430, // obsolete
BSQueryPaymentInstUsage = 1431,
BSQueryPaymentInstResponse = 1432,
BSQueryTxnExtendedInfo = 1433,
BSQueryTxnExtendedInfoResponse = 1434,
BSUpdateConversionRates = 1435,
BSProcessUSBankReports = 1436, // obsolete
BSPurchaseRunFraudChecks = 1437,
BSPurchaseRunFraudChecksResponse = 1438,
BSStartShippingJobs = 1439, // obsolete
BSQueryBankInformation = 1440,
BSQueryBankInformationResponse = 1441,
BSValidateXsollaSignature = 1445,
BSValidateXsollaSignatureResponse = 1446,
BSQiwiWalletInvoice = 1448,
BSQiwiWalletInvoiceResponse = 1449,
BSUpdateInventoryFromProPack = 1450,
BSUpdateInventoryFromProPackResponse = 1451,
BSSendShippingRequest = 1452,
BSSendShippingRequestResponse = 1453,
BSGetProPackOrderStatus = 1454,
BSGetProPackOrderStatusResponse = 1455,
BSCheckJobRunning = 1456,
BSCheckJobRunningResponse = 1457,
BSResetPackagePurchaseRateLimit = 1458,
BSResetPackagePurchaseRateLimitResponse = 1459,
BSUpdatePaymentData = 1460,
BSUpdatePaymentDataResponse = 1461,
BSGetBillingAddress = 1462,
BSGetBillingAddressResponse = 1463,
BSGetCreditCardInfo = 1464,
BSGetCreditCardInfoResponse = 1465,
BSRemoveExpiredPaymentData = 1468,
BSRemoveExpiredPaymentDataResponse = 1469,
BSConvertToCurrentKeys = 1470,
BSConvertToCurrentKeysResponse = 1471,
BSInitPurchase = 1472,
BSInitPurchaseResponse = 1473,
BSCompletePurchase = 1474,
BSCompletePurchaseResponse = 1475,
BSPruneCardUsageStats = 1476,
BSPruneCardUsageStatsResponse = 1477,
BSStoreBankInformation = 1478,
BSStoreBankInformationResponse = 1479,
BSVerifyPOSAKey = 1480,
BSVerifyPOSAKeyResponse = 1481,
BSReverseRedeemPOSAKey = 1482,
BSReverseRedeemPOSAKeyResponse = 1483,
BSQueryFindCreditCard = 1484,
BSQueryFindCreditCardResponse = 1485,
BSStatusInquiryPOSAKey = 1486,
BSStatusInquiryPOSAKeyResponse = 1487,
BSValidateMoPaySignature = 1488,
BSValidateMoPaySignatureResponse = 1489,
BSMoPayConfirmProductDelivery = 1490,
BSMoPayConfirmProductDeliveryResponse = 1491,
BSGenerateMoPayMD5 = 1492,
BSGenerateMoPayMD5Response = 1493,
BSBoaCompraConfirmProductDelivery = 1494,
BSBoaCompraConfirmProductDeliveryResponse = 1495,
BSGenerateBoaCompraMD5 = 1496,
BSGenerateBoaCompraMD5Response = 1497,
BSCommitWPTxn = 1498,
BaseATS = 1500,
ATSStartStressTest = 1501,
ATSStopStressTest = 1502,
ATSRunFailServerTest = 1503,
ATSUFSPerfTestTask = 1504,
ATSUFSPerfTestResponse = 1505,
ATSCycleTCM = 1506,
ATSInitDRMSStressTest = 1507,
ATSCallTest = 1508,
ATSCallTestReply = 1509,
ATSStartExternalStress = 1510,
ATSExternalStressJobStart = 1511,
ATSExternalStressJobQueued = 1512,
ATSExternalStressJobRunning = 1513,
ATSExternalStressJobStopped = 1514,
ATSExternalStressJobStopAll = 1515,
ATSExternalStressActionResult = 1516,
ATSStarted = 1517,
ATSCSPerfTestTask = 1518,
ATSCSPerfTestResponse = 1519,
BaseDP = 1600,
DPSetPublishingState = 1601,
DPGamePlayedStats = 1602, // obsolete
DPUniquePlayersStat = 1603,
DPStreamingUniquePlayersStat = 1604,
DPVacInfractionStats = 1605,
DPVacBanStats = 1606,
DPBlockingStats = 1607,
DPNatTraversalStats = 1608,
DPSteamUsageEvent = 1609, // obsolete
DPVacCertBanStats = 1610,
DPVacCafeBanStats = 1611,
DPCloudStats = 1612,
DPAchievementStats = 1613,
DPAccountCreationStats = 1614,
DPGetPlayerCount = 1615,
DPGetPlayerCountResponse = 1616,
DPGameServersPlayersStats = 1617,
DPDownloadRateStatistics = 1618, // obsolete
DPFacebookStatistics = 1619,
ClientDPCheckSpecialSurvey = 1620,
ClientDPCheckSpecialSurveyResponse = 1621,
ClientDPSendSpecialSurveyResponse = 1622,
ClientDPSendSpecialSurveyResponseReply = 1623,
DPStoreSaleStatistics = 1624,
ClientDPUpdateAppJobReport = 1625,
ClientDPSteam2AppStarted = 1627, // obsolete
DPUpdateContentEvent = 1626,
DPPartnerMicroTxns = 1628,
DPPartnerMicroTxnsResponse = 1629,
ClientDPContentStatsReport = 1630,
DPVRUniquePlayersStat = 1631,
BaseCM = 1700,
CMSetAllowState = 1701,
CMSpewAllowState = 1702,
CMAppInfoResponseDeprecated = 1703, // obsolete
BaseDSS = 1800, // obsolete
DSSNewFile = 1801, // obsolete
DSSCurrentFileList = 1802, // obsolete
DSSSynchList = 1803, // obsolete
DSSSynchListResponse = 1804, // obsolete
DSSSynchSubscribe = 1805, // obsolete
DSSSynchUnsubscribe = 1806, // obsolete
BaseEPM = 1900, // obsolete
EPMStartProcess = 1901, // obsolete
EPMStopProcess = 1902, // obsolete
EPMRestartProcess = 1903, // obsolete
BaseGC = 2200,
GCSendClient = 2200, // obsolete
AMRelayToGC = 2201, // obsolete
GCUpdatePlayedState = 2202, // obsolete
GCCmdRevive = 2203,
GCCmdBounce = 2204, // obsolete
GCCmdForceBounce = 2205, // obsolete
GCCmdDown = 2206,
GCCmdDeploy = 2207,
GCCmdDeployResponse = 2208,
GCCmdSwitch = 2209,
AMRefreshSessions = 2210,
GCUpdateGSState = 2211, // obsolete
GCAchievementAwarded = 2212,
GCSystemMessage = 2213,
GCValidateSession = 2214, // obsolete
GCValidateSessionResponse = 2215, // obsolete
GCCmdStatus = 2216,
GCRegisterWebInterfaces = 2217, // obsolete
GCRegisterWebInterfaces_Deprecated = 2217, // obsolete
GCGetAccountDetails = 2218, // obsolete
GCGetAccountDetails_DEPRECATED = 2218, // obsolete
GCInterAppMessage = 2219,
GCGetEmailTemplate = 2220,
GCGetEmailTemplateResponse = 2221,
ISRelayToGCH = 2222, // obsolete "renamed to GCHRelay"
GCHRelay = 2222,
GCHRelayClientToIS = 2223, // obsolete "renamed to GCHRelayToClient"
GCHRelayToClient = 2223,
GCHUpdateSession = 2224,
GCHRequestUpdateSession = 2225,
GCHRequestStatus = 2226,
GCHRequestStatusResponse = 2227,
GCHAccountVacStatusChange = 2228,
GCHSpawnGC = 2229,
GCHSpawnGCResponse = 2230,
GCHKillGC = 2231,
GCHKillGCResponse = 2232,
GCHAccountTradeBanStatusChange = 2233,
GCHAccountLockStatusChange = 2234,
GCHVacVerificationChange = 2235,
GCHAccountPhoneNumberChange = 2236,
GCHAccountTwoFactorChange = 2237,
BaseP2P = 2500,
P2PIntroducerMessage = 2502,
BaseSM = 2900,
SMExpensiveReport = 2902,
SMHourlyReport = 2903,
SMFishingReport = 2904,
SMPartitionRenames = 2905,
SMMonitorSpace = 2906,
SMGetSchemaConversionResults = 2907, // obsolete
SMGetSchemaConversionResultsResponse = 2908, // obsolete
BaseTest = 3000,
FailServer = 3000,
JobHeartbeatTest = 3001,
JobHeartbeatTestResponse = 3002,
BaseFTSRange = 3100,
FTSGetBrowseCounts = 3101, // obsolete
FTSGetBrowseCountsResponse = 3102, // obsolete
FTSBrowseClans = 3103, // obsolete
FTSBrowseClansResponse = 3104, // obsolete
FTSSearchClansByLocation = 3105, // obsolete
FTSSearchClansByLocationResponse = 3106, // obsolete
FTSSearchPlayersByLocation = 3107, // obsolete
FTSSearchPlayersByLocationResponse = 3108, // obsolete
FTSClanDeleted = 3109, // obsolete
FTSSearch = 3110, // obsolete
FTSSearchResponse = 3111, // obsolete
FTSSearchStatus = 3112, // obsolete
FTSSearchStatusResponse = 3113, // obsolete
FTSGetGSPlayStats = 3114, // obsolete
FTSGetGSPlayStatsResponse = 3115, // obsolete
FTSGetGSPlayStatsForServer = 3116, // obsolete
FTSGetGSPlayStatsForServerResponse = 3117, // obsolete
FTSReportIPUpdates = 3118, // obsolete
BaseCCSRange = 3150,
CCSGetComments = 3151, // obsolete
CCSGetCommentsResponse = 3152, // obsolete
CCSAddComment = 3153, // obsolete
CCSAddCommentResponse = 3154, // obsolete
CCSDeleteComment = 3155, // obsolete
CCSDeleteCommentResponse = 3156, // obsolete
CCSPreloadComments = 3157, // obsolete
CCSNotifyCommentCount = 3158, // obsolete
CCSGetCommentsForNews = 3159, // obsolete
CCSGetCommentsForNewsResponse = 3160, // obsolete
CCSDeleteAllCommentsByAuthor = 3161,
CCSDeleteAllCommentsByAuthorResponse = 3162,
BaseLBSRange = 3200,
LBSSetScore = 3201,
LBSSetScoreResponse = 3202,
LBSFindOrCreateLB = 3203,
LBSFindOrCreateLBResponse = 3204,
LBSGetLBEntries = 3205,
LBSGetLBEntriesResponse = 3206,
LBSGetLBList = 3207,
LBSGetLBListResponse = 3208,
LBSSetLBDetails = 3209,
LBSDeleteLB = 3210,
LBSDeleteLBEntry = 3211,
LBSResetLB = 3212,
LBSResetLBResponse = 3213,
LBSDeleteLBResponse = 3214,
BaseOGS = 3400,
OGSBeginSession = 3401,
OGSBeginSessionResponse = 3402,
OGSEndSession = 3403,
OGSEndSessionResponse = 3404,
OGSWriteAppSessionRow = 3406,
BaseBRP = 3600,
BRPStartShippingJobs = 3601,
BRPProcessUSBankReports = 3602,
BRPProcessGCReports = 3603,
BRPProcessPPReports = 3604,
BRPSettleNOVA = 3605, // obsolete
BRPSettleCB = 3606, // obsolete
BRPCommitGC = 3607,
BRPCommitGCResponse = 3608,
BRPFindHungTransactions = 3609,
BRPCheckFinanceCloseOutDate = 3610,
BRPProcessLicenses = 3611,
BRPProcessLicensesResponse = 3612,
BRPRemoveExpiredPaymentData = 3613,
BRPRemoveExpiredPaymentDataResponse = 3614,
BRPConvertToCurrentKeys = 3615,
BRPConvertToCurrentKeysResponse = 3616,
BRPPruneCardUsageStats = 3617,
BRPPruneCardUsageStatsResponse = 3618,
BRPCheckActivationCodes = 3619,
BRPCheckActivationCodesResponse = 3620,
BRPCommitWP = 3621,
BRPCommitWPResponse = 3622,
BRPProcessWPReports = 3623,
BRPProcessPaymentRules = 3624,
BRPProcessPartnerPayments = 3625,
BRPCheckSettlementReports = 3626,
BRPPostTaxToAvalara = 3628,
BRPPostTransactionTax = 3629,
BRPPostTransactionTaxResponse = 3630,
BRPProcessIMReports = 3631,
BaseAMRange2 = 4000,
AMCreateChat = 4001,
AMCreateChatResponse = 4002,
AMUpdateChatMetadata = 4003, // obsolete
AMPublishChatMetadata = 4004, // obsolete
AMSetProfileURL = 4005,
AMGetAccountEmailAddress = 4006,
AMGetAccountEmailAddressResponse = 4007,
AMRequestFriendData = 4008, // obsolete "renamed to AMRequestClanData"
AMRequestClanData = 4008,
AMRouteToClients = 4009,
AMLeaveClan = 4010,
AMClanPermissions = 4011,
AMClanPermissionsResponse = 4012,
AMCreateClanEvent = 4013,
AMCreateClanEventResponse = 4014,
AMUpdateClanEvent = 4015,
AMUpdateClanEventResponse = 4016,
AMGetClanEvents = 4017,
AMGetClanEventsResponse = 4018,
AMDeleteClanEvent = 4019,
AMDeleteClanEventResponse = 4020,
AMSetClanPermissionSettings = 4021,
AMSetClanPermissionSettingsResponse = 4022,
AMGetClanPermissionSettings = 4023,
AMGetClanPermissionSettingsResponse = 4024,
AMPublishChatRoomInfo = 4025,
ClientChatRoomInfo = 4026,
AMCreateClanAnnouncement = 4027, // obsolete
AMCreateClanAnnouncementResponse = 4028, // obsolete
AMUpdateClanAnnouncement = 4029, // obsolete
AMUpdateClanAnnouncementResponse = 4030, // obsolete
AMGetClanAnnouncementsCount = 4031, // obsolete
AMGetClanAnnouncementsCountResponse = 4032, // obsolete
AMGetClanAnnouncements = 4033, // obsolete
AMGetClanAnnouncementsResponse = 4034, // obsolete
AMDeleteClanAnnouncement = 4035, // obsolete
AMDeleteClanAnnouncementResponse = 4036, // obsolete
AMGetSingleClanAnnouncement = 4037, // obsolete
AMGetSingleClanAnnouncementResponse = 4038, // obsolete
AMGetClanHistory = 4039,
AMGetClanHistoryResponse = 4040,
AMGetClanPermissionBits = 4041,
AMGetClanPermissionBitsResponse = 4042,
AMSetClanPermissionBits = 4043,
AMSetClanPermissionBitsResponse = 4044,
AMSessionInfoRequest = 4045,
AMSessionInfoResponse = 4046,
AMValidateWGToken = 4047,
AMGetSingleClanEvent = 4048,
AMGetSingleClanEventResponse = 4049,
AMGetClanRank = 4050,
AMGetClanRankResponse = 4051,
AMSetClanRank = 4052,
AMSetClanRankResponse = 4053,
AMGetClanPOTW = 4054,
AMGetClanPOTWResponse = 4055,
AMSetClanPOTW = 4056,
AMSetClanPOTWResponse = 4057,
AMRequestChatMetadata = 4058, // obsolete
AMDumpUser = 4059,
AMKickUserFromClan = 4060,
AMAddFounderToClan = 4061,
AMValidateWGTokenResponse = 4062,
AMSetCommunityState = 4063,
AMSetAccountDetails = 4064,
AMGetChatBanList = 4065,
AMGetChatBanListResponse = 4066,
AMUnBanFromChat = 4067,
AMSetClanDetails = 4068,
AMGetAccountLinks = 4069,
AMGetAccountLinksResponse = 4070,
AMSetAccountLinks = 4071,
AMSetAccountLinksResponse = 4072,
AMGetUserGameStats = 4073,
AMGetUserGameStatsResponse = 4074,
AMCheckClanMembership = 4075,
AMGetClanMembers = 4076,
AMGetClanMembersResponse = 4077,
AMJoinPublicClan = 4078,
AMNotifyChatOfClanChange = 4079,
AMResubmitPurchase = 4080,
AMAddFriend = 4081,
AMAddFriendResponse = 4082,
AMRemoveFriend = 4083,
AMDumpClan = 4084,
AMChangeClanOwner = 4085,
AMCancelEasyCollect = 4086,
AMCancelEasyCollectResponse = 4087,
AMGetClanMembershipList = 4088, // obsolete
AMGetClanMembershipListResponse = 4089, // obsolete
AMClansInCommon = 4090,
AMClansInCommonResponse = 4091,
AMIsValidAccountID = 4092,
AMConvertClan = 4093,
AMGetGiftTargetListRelay = 4094, // obsolete
AMWipeFriendsList = 4095,
AMSetIgnored = 4096,
AMClansInCommonCountResponse = 4097,
AMFriendsList = 4098,
AMFriendsListResponse = 4099,
AMFriendsInCommon = 4100,
AMFriendsInCommonResponse = 4101,
AMFriendsInCommonCountResponse = 4102,
AMClansInCommonCount = 4103,
AMChallengeVerdict = 4104,
AMChallengeNotification = 4105,
AMFindGSByIP = 4106,
AMFoundGSByIP = 4107,
AMGiftRevoked = 4108,
AMCreateAccountRecord = 4109,
AMUserClanList = 4110,
AMUserClanListResponse = 4111,
AMGetAccountDetails2 = 4112,
AMGetAccountDetailsResponse2 = 4113,
AMSetCommunityProfileSettings = 4114,
AMSetCommunityProfileSettingsResponse = 4115,
AMGetCommunityPrivacyState = 4116,
AMGetCommunityPrivacyStateResponse = 4117,
AMCheckClanInviteRateLimiting = 4118,
AMGetUserAchievementStatus = 4119,
AMGetIgnored = 4120,
AMGetIgnoredResponse = 4121,
AMSetIgnoredResponse = 4122,
AMSetFriendRelationshipNone = 4123,
AMGetFriendRelationship = 4124,
AMGetFriendRelationshipResponse = 4125,
AMServiceModulesCache = 4126,
AMServiceModulesCall = 4127,
AMServiceModulesCallResponse = 4128,
AMGetCaptchaDataForIP = 4129,
AMGetCaptchaDataForIPResponse = 4130,
AMValidateCaptchaDataForIP = 4131,
AMValidateCaptchaDataForIPResponse = 4132,
AMTrackFailedAuthByIP = 4133,
AMGetCaptchaDataByGID = 4134,
AMGetCaptchaDataByGIDResponse = 4135,
AMGetLobbyList = 4136, // obsolete
AMGetLobbyListResponse = 4137, // obsolete
AMGetLobbyMetadata = 4138, // obsolete
AMGetLobbyMetadataResponse = 4139, // obsolete
CommunityAddFriendNews = 4140,
AMAddClanNews = 4141, // obsolete
AMWriteNews = 4142, // obsolete
AMFindClanUser = 4143,
AMFindClanUserResponse = 4144,
AMBanFromChat = 4145,
AMGetUserHistoryResponse = 4146, // obsolete
AMGetUserNewsSubscriptions = 4147,
AMGetUserNewsSubscriptionsResponse = 4148,
AMSetUserNewsSubscriptions = 4149,
AMGetUserNews = 4150, // obsolete
AMGetUserNewsResponse = 4151, // obsolete
AMSendQueuedEmails = 4152,
AMSetLicenseFlags = 4153,
AMGetUserHistory = 4154, // obsolete
CommunityDeleteUserNews = 4155,
AMAllowUserFilesRequest = 4156,
AMAllowUserFilesResponse = 4157,
AMGetAccountStatus = 4158,
AMGetAccountStatusResponse = 4159,
AMEditBanReason = 4160,
AMCheckClanMembershipResponse = 4161,
AMProbeClanMembershipList = 4162,
AMProbeClanMembershipListResponse = 4163,
AMGetFriendsLobbies = 4165,
AMGetFriendsLobbiesResponse = 4166,
AMGetUserFriendNewsResponse = 4172,
CommunityGetUserFriendNews = 4173,
AMGetUserClansNewsResponse = 4174,
AMGetUserClansNews = 4175,
AMStoreInitPurchase = 4176, // obsolete
AMStoreInitPurchaseResponse = 4177, // obsolete
AMStoreGetFinalPrice = 4178, // obsolete
AMStoreGetFinalPriceResponse = 4179, // obsolete
AMStoreCompletePurchase = 4180, // obsolete
AMStoreCancelPurchase = 4181, // obsolete
AMStorePurchaseResponse = 4182, // obsolete
AMCreateAccountRecordInSteam3 = 4183, // obsolete
AMGetPreviousCBAccount = 4184,
AMGetPreviousCBAccountResponse = 4185,
AMUpdateBillingAddress = 4186, // obsolete
AMUpdateBillingAddressResponse = 4187, // obsolete
AMGetBillingAddress = 4188, // obsolete
AMGetBillingAddressResponse = 4189, // obsolete
AMGetUserLicenseHistory = 4190,
AMGetUserLicenseHistoryResponse = 4191,
AMSupportChangePassword = 4194,
AMSupportChangeEmail = 4195,
AMSupportChangeSecretQA = 4196, // obsolete
AMResetUserVerificationGSByIP = 4197,
AMUpdateGSPlayStats = 4198,
AMSupportEnableOrDisable = 4199,
AMGetComments = 4200, // obsolete
AMGetCommentsResponse = 4201, // obsolete
AMAddComment = 4202, // obsolete
AMAddCommentResponse = 4203, // obsolete
AMDeleteComment = 4204, // obsolete
AMDeleteCommentResponse = 4205, // obsolete
AMGetPurchaseStatus = 4206,
AMSupportIsAccountEnabled = 4209,
AMSupportIsAccountEnabledResponse = 4210,
AMGetUserStats = 4211,
AMSupportKickSession = 4212,
AMGSSearch = 4213,
MarketingMessageUpdate = 4216,
AMRouteFriendMsg = 4219,
AMTicketAuthRequestOrResponse = 4220,
AMVerifyDepotManagementRights = 4222,
AMVerifyDepotManagementRightsResponse = 4223,
AMAddFreeLicense = 4224,
AMGetUserFriendsMinutesPlayed = 4225, // obsolete
AMGetUserFriendsMinutesPlayedResponse = 4226, // obsolete
AMGetUserMinutesPlayed = 4227, // obsolete
AMGetUserMinutesPlayedResponse = 4228, // obsolete
AMValidateEmailLink = 4231,
AMValidateEmailLinkResponse = 4232,
AMAddUsersToMarketingTreatment = 4234, // obsolete
AMStoreUserStats = 4236,
AMGetUserGameplayInfo = 4237, // obsolete
AMGetUserGameplayInfoResponse = 4238, // obsolete
AMGetCardList = 4239, // obsolete
AMGetCardListResponse = 4240, // obsolete
AMDeleteStoredCard = 4241,
AMRevokeLegacyGameKeys = 4242,
AMGetWalletDetails = 4244,
AMGetWalletDetailsResponse = 4245,
AMDeleteStoredPaymentInfo = 4246,
AMGetStoredPaymentSummary = 4247,
AMGetStoredPaymentSummaryResponse = 4248,
AMGetWalletConversionRate = 4249,
AMGetWalletConversionRateResponse = 4250,
AMConvertWallet = 4251,
AMConvertWalletResponse = 4252,
AMRelayGetFriendsWhoPlayGame = 4253, // obsolete
AMRelayGetFriendsWhoPlayGameResponse = 4254, // obsolete
AMSetPreApproval = 4255,
AMSetPreApprovalResponse = 4256,
AMMarketingTreatmentUpdate = 4257, // obsolete
AMCreateRefund = 4258,
AMCreateRefundResponse = 4259,
AMCreateChargeback = 4260,
AMCreateChargebackResponse = 4261,
AMCreateDispute = 4262,
AMCreateDisputeResponse = 4263,
AMClearDispute = 4264,
AMClearDisputeResponse = 4265,
AMPlayerNicknameList = 4266,
AMPlayerNicknameListResponse = 4267,
AMSetDRMTestConfig = 4268,
AMGetUserCurrentGameInfo = 4269,
AMGetUserCurrentGameInfoResponse = 4270,
AMGetGSPlayerList = 4271,
AMGetGSPlayerListResponse = 4272,
AMUpdatePersonaStateCache = 4275, // obsolete
AMGetGameMembers = 4276,
AMGetGameMembersResponse = 4277,
AMGetSteamIDForMicroTxn = 4278,
AMGetSteamIDForMicroTxnResponse = 4279,
AMAddPublisherUser = 4280,
AMRemovePublisherUser = 4281,
AMGetUserLicenseList = 4282,
AMGetUserLicenseListResponse = 4283,
AMReloadGameGroupPolicy = 4284,
AMAddFreeLicenseResponse = 4285,
AMVACStatusUpdate = 4286,
AMGetAccountDetails = 4287,
AMGetAccountDetailsResponse = 4288,
AMGetPlayerLinkDetails = 4289,
AMGetPlayerLinkDetailsResponse = 4290,
AMSubscribeToPersonaFeed = 4291, // obsolete
AMGetUserVacBanList = 4292, // obsolete
AMGetUserVacBanListResponse = 4293, // obsolete
AMGetAccountFlagsForWGSpoofing = 4294,
AMGetAccountFlagsForWGSpoofingResponse = 4295,
AMGetFriendsWishlistInfo = 4296, // obsolete
AMGetFriendsWishlistInfoResponse = 4297, // obsolete
AMGetClanOfficers = 4298,
AMGetClanOfficersResponse = 4299,
AMNameChange = 4300,
AMGetNameHistory = 4301,
AMGetNameHistoryResponse = 4302,
AMUpdateProviderStatus = 4305,
AMClearPersonaMetadataBlob = 4306, // obsolete
AMSupportRemoveAccountSecurity = 4307,
AMIsAccountInCaptchaGracePeriod = 4308,
AMIsAccountInCaptchaGracePeriodResponse = 4309,
AMAccountPS3Unlink = 4310,
AMAccountPS3UnlinkResponse = 4311,
AMStoreUserStatsResponse = 4312,
AMGetAccountPSNInfo = 4313,
AMGetAccountPSNInfoResponse = 4314,
AMAuthenticatedPlayerList = 4315,
AMGetUserGifts = 4316,
AMGetUserGiftsResponse = 4317,
AMTransferLockedGifts = 4320,
AMTransferLockedGiftsResponse = 4321,
AMPlayerHostedOnGameServer = 4322,
AMGetAccountBanInfo = 4323,
AMGetAccountBanInfoResponse = 4324,
AMRecordBanEnforcement = 4325,
AMRollbackGiftTransfer = 4326,
AMRollbackGiftTransferResponse = 4327,
AMHandlePendingTransaction = 4328,
AMRequestClanDetails = 4329,
AMDeleteStoredPaypalAgreement = 4330,
AMGameServerUpdate = 4331,
AMGameServerRemove = 4332,
AMGetPaypalAgreements = 4333,
AMGetPaypalAgreementsResponse = 4334,
AMGameServerPlayerCompatibilityCheck = 4335,
AMGameServerPlayerCompatibilityCheckResponse = 4336,
AMRenewLicense = 4337,
AMGetAccountCommunityBanInfo = 4338,
AMGetAccountCommunityBanInfoResponse = 4339,
AMGameServerAccountChangePassword = 4340,
AMGameServerAccountDeleteAccount = 4341,
AMRenewAgreement = 4342,
AMSendEmail = 4343, // obsolete
AMXsollaPayment = 4344,
AMXsollaPaymentResponse = 4345,
AMAcctAllowedToPurchase = 4346,
AMAcctAllowedToPurchaseResponse = 4347,
AMSwapKioskDeposit = 4348,
AMSwapKioskDepositResponse = 4349,
AMSetUserGiftUnowned = 4350,
AMSetUserGiftUnownedResponse = 4351,
AMClaimUnownedUserGift = 4352,
AMClaimUnownedUserGiftResponse = 4353,
AMSetClanName = 4354,
AMSetClanNameResponse = 4355,
AMGrantCoupon = 4356,
AMGrantCouponResponse = 4357,
AMIsPackageRestrictedInUserCountry = 4358,
AMIsPackageRestrictedInUserCountryResponse = 4359,
AMHandlePendingTransactionResponse = 4360,
AMGrantGuestPasses2 = 4361,
AMGrantGuestPasses2Response = 4362,
AMSessionQuery = 4363,
AMSessionQueryResponse = 4364,
AMGetPlayerBanDetails = 4365,
AMGetPlayerBanDetailsResponse = 4366,
AMFinalizePurchase = 4367,
AMFinalizePurchaseResponse = 4368,
AMPersonaChangeResponse = 4372,
AMGetClanDetailsForForumCreation = 4373,
AMGetClanDetailsForForumCreationResponse = 4374,
AMGetPendingNotificationCount = 4375,
AMGetPendingNotificationCountResponse = 4376,
AMPasswordHashUpgrade = 4377,
AMMoPayPayment = 4378,
AMMoPayPaymentResponse = 4379,
AMBoaCompraPayment = 4380,
AMBoaCompraPaymentResponse = 4381,
AMExpireCaptchaByGID = 4382,
AMCompleteExternalPurchase = 4383,
AMCompleteExternalPurchaseResponse = 4384,
AMResolveNegativeWalletCredits = 4385,
AMResolveNegativeWalletCreditsResponse = 4386,
AMPayelpPayment = 4387,
AMPayelpPaymentResponse = 4388,
AMPlayerGetClanBasicDetails = 4389,
AMPlayerGetClanBasicDetailsResponse = 4390,
AMMOLPayment = 4391,
AMMOLPaymentResponse = 4392,
GetUserIPCountry = 4393,
GetUserIPCountryResponse = 4394,
NotificationOfSuspiciousActivity = 4395,
AMDegicaPayment = 4396,
AMDegicaPaymentResponse = 4397,
AMEClubPayment = 4398,
AMEClubPaymentResponse = 4399,
AMPayPalPaymentsHubPayment = 4400,
AMPayPalPaymentsHubPaymentResponse = 4401,
AMTwoFactorRecoverAuthenticatorRequest = 4402,
AMTwoFactorRecoverAuthenticatorResponse = 4403,
AMSmart2PayPayment = 4404,
AMSmart2PayPaymentResponse = 4405,
AMValidatePasswordResetCodeAndSendSmsRequest = 4406,
AMValidatePasswordResetCodeAndSendSmsResponse = 4407,
AMGetAccountResetDetailsRequest = 4408,
AMGetAccountResetDetailsResponse = 4409,
AMBitPayPayment = 4410,
AMBitPayPaymentResponse = 4411,
AMSendAccountInfoUpdate = 4412,
BasePSRange = 5000,
PSCreateShoppingCart = 5001,
PSCreateShoppingCartResponse = 5002,
PSIsValidShoppingCart = 5003,
PSIsValidShoppingCartResponse = 5004,
PSAddPackageToShoppingCart = 5005,
PSAddPackageToShoppingCartResponse = 5006,
PSRemoveLineItemFromShoppingCart = 5007,
PSRemoveLineItemFromShoppingCartResponse = 5008,
PSGetShoppingCartContents = 5009,
PSGetShoppingCartContentsResponse = 5010,
PSAddWalletCreditToShoppingCart = 5011,
PSAddWalletCreditToShoppingCartResponse = 5012,
BaseUFSRange = 5200,
ClientUFSUploadFileRequest = 5202,
ClientUFSUploadFileResponse = 5203,
ClientUFSUploadFileChunk = 5204,
ClientUFSUploadFileFinished = 5205,
ClientUFSGetFileListForApp = 5206,
ClientUFSGetFileListForAppResponse = 5207,
ClientUFSDownloadRequest = 5210,
ClientUFSDownloadResponse = 5211,
ClientUFSDownloadChunk = 5212,
ClientUFSLoginRequest = 5213,
ClientUFSLoginResponse = 5214,
UFSReloadPartitionInfo = 5215,
ClientUFSTransferHeartbeat = 5216,
UFSSynchronizeFile = 5217,
UFSSynchronizeFileResponse = 5218,
ClientUFSDeleteFileRequest = 5219,
ClientUFSDeleteFileResponse = 5220,
UFSDownloadRequest = 5221, // obsolete
UFSDownloadResponse = 5222, // obsolete
UFSDownloadChunk = 5223, // obsolete
ClientUFSGetUGCDetails = 5226,
ClientUFSGetUGCDetailsResponse = 5227,
UFSUpdateFileFlags = 5228,
UFSUpdateFileFlagsResponse = 5229,
ClientUFSGetSingleFileInfo = 5230,
ClientUFSGetSingleFileInfoResponse = 5231,
ClientUFSShareFile = 5232,
ClientUFSShareFileResponse = 5233,
UFSReloadAccount = 5234,
UFSReloadAccountResponse = 5235,
UFSUpdateRecordBatched = 5236,
UFSUpdateRecordBatchedResponse = 5237,
UFSMigrateFile = 5238,
UFSMigrateFileResponse = 5239,
UFSGetUGCURLs = 5240,
UFSGetUGCURLsResponse = 5241,
UFSHttpUploadFileFinishRequest = 5242,
UFSHttpUploadFileFinishResponse = 5243,
UFSDownloadStartRequest = 5244,
UFSDownloadStartResponse = 5245,
UFSDownloadChunkRequest = 5246,
UFSDownloadChunkResponse = 5247,
UFSDownloadFinishRequest = 5248,
UFSDownloadFinishResponse = 5249,
UFSFlushURLCache = 5250,
UFSUploadCommit = 5251,
UFSUploadCommitResponse = 5252,
UFSMigrateFileAppID = 5253,
UFSMigrateFileAppIDResponse = 5254,
BaseClient2 = 5400,
ClientRequestForgottenPasswordEmail = 5401,
ClientRequestForgottenPasswordEmailResponse = 5402,
ClientCreateAccountResponse = 5403,
ClientResetForgottenPassword = 5404,
ClientResetForgottenPasswordResponse = 5405,
ClientCreateAccount2 = 5406,
ClientInformOfResetForgottenPassword = 5407,
ClientInformOfResetForgottenPasswordResponse = 5408,
ClientAnonUserLogOn_Deprecated = 5409, // obsolete
ClientGamesPlayedWithDataBlob = 5410,
ClientUpdateUserGameInfo = 5411,
ClientFileToDownload = 5412,
ClientFileToDownloadResponse = 5413,
ClientLBSSetScore = 5414,
ClientLBSSetScoreResponse = 5415,
ClientLBSFindOrCreateLB = 5416,
ClientLBSFindOrCreateLBResponse = 5417,
ClientLBSGetLBEntries = 5418,
ClientLBSGetLBEntriesResponse = 5419,
ClientMarketingMessageUpdate = 5420, // obsolete
ClientChatDeclined = 5426,
ClientFriendMsgIncoming = 5427,
ClientAuthList_Deprecated = 5428, // obsolete
ClientTicketAuthComplete = 5429,
ClientIsLimitedAccount = 5430,
ClientRequestAuthList = 5431,
ClientAuthList = 5432,
ClientStat = 5433,
ClientP2PConnectionInfo = 5434,
ClientP2PConnectionFailInfo = 5435,
ClientGetNumberOfCurrentPlayers = 5436, // obsolete
ClientGetNumberOfCurrentPlayersResponse = 5437, // obsolete
ClientGetDepotDecryptionKey = 5438,
ClientGetDepotDecryptionKeyResponse = 5439,
GSPerformHardwareSurvey = 5440,
ClientGetAppBetaPasswords = 5441, // obsolete
ClientGetAppBetaPasswordsResponse = 5442, // obsolete
ClientEnableTestLicense = 5443,
ClientEnableTestLicenseResponse = 5444,
ClientDisableTestLicense = 5445,
ClientDisableTestLicenseResponse = 5446,
ClientRequestValidationMail = 5448,
ClientRequestValidationMailResponse = 5449,
ClientCheckAppBetaPassword = 5450,
ClientCheckAppBetaPasswordResponse = 5451,
ClientToGC = 5452,
ClientFromGC = 5453,
ClientRequestChangeMail = 5454,
ClientRequestChangeMailResponse = 5455,
ClientEmailAddrInfo = 5456,
ClientPasswordChange3 = 5457,
ClientEmailChange3 = 5458,
ClientPersonalQAChange3 = 5459,
ClientResetForgottenPassword3 = 5460,
ClientRequestForgottenPasswordEmail3 = 5461,
ClientCreateAccount3 = 5462, // obsolete
ClientNewLoginKey = 5463,
ClientNewLoginKeyAccepted = 5464,
ClientLogOnWithHash_Deprecated = 5465, // obsolete
ClientStoreUserStats2 = 5466,
ClientStatsUpdated = 5467,
ClientActivateOEMLicense = 5468,
ClientRegisterOEMMachine = 5469,
ClientRegisterOEMMachineResponse = 5470,
ClientRequestedClientStats = 5480,
ClientStat2Int32 = 5481,
ClientStat2 = 5482,
ClientVerifyPassword = 5483,
ClientVerifyPasswordResponse = 5484,
ClientDRMDownloadRequest = 5485,
ClientDRMDownloadResponse = 5486,
ClientDRMFinalResult = 5487,
ClientGetFriendsWhoPlayGame = 5488,
ClientGetFriendsWhoPlayGameResponse = 5489,
ClientOGSBeginSession = 5490,
ClientOGSBeginSessionResponse = 5491,
ClientOGSEndSession = 5492,
ClientOGSEndSessionResponse = 5493,
ClientOGSWriteRow = 5494,
ClientDRMTest = 5495,
ClientDRMTestResult = 5496,
ClientServerUnavailable = 5500,
ClientServersAvailable = 5501,
ClientRegisterAuthTicketWithCM = 5502,
ClientGCMsgFailed = 5503,
ClientMicroTxnAuthRequest = 5504,
ClientMicroTxnAuthorize = 5505,
ClientMicroTxnAuthorizeResponse = 5506,
ClientAppMinutesPlayedData = 5507,
ClientGetMicroTxnInfo = 5508,
ClientGetMicroTxnInfoResponse = 5509,
ClientMarketingMessageUpdate2 = 5510,
ClientDeregisterWithServer = 5511,
ClientSubscribeToPersonaFeed = 5512,
ClientLogon = 5514,
ClientGetClientDetails = 5515,
ClientGetClientDetailsResponse = 5516,
ClientReportOverlayDetourFailure = 5517,
ClientGetClientAppList = 5518,
ClientGetClientAppListResponse = 5519,
ClientInstallClientApp = 5520,
ClientInstallClientAppResponse = 5521,
ClientUninstallClientApp = 5522,
ClientUninstallClientAppResponse = 5523,
ClientSetClientAppUpdateState = 5524,
ClientSetClientAppUpdateStateResponse = 5525,
ClientRequestEncryptedAppTicket = 5526,
ClientRequestEncryptedAppTicketResponse = 5527,
ClientWalletInfoUpdate = 5528,
ClientLBSSetUGC = 5529,
ClientLBSSetUGCResponse = 5530,
ClientAMGetClanOfficers = 5531,
ClientAMGetClanOfficersResponse = 5532,
ClientCheckFileSignature = 5533, // obsolete
ClientCheckFileSignatureResponse = 5534, // obsolete
ClientFriendProfileInfo = 5535,
ClientFriendProfileInfoResponse = 5536,
ClientUpdateMachineAuth = 5537,
ClientUpdateMachineAuthResponse = 5538,
ClientReadMachineAuth = 5539,
ClientReadMachineAuthResponse = 5540,
ClientRequestMachineAuth = 5541,
ClientRequestMachineAuthResponse = 5542,
ClientScreenshotsChanged = 5543,
ClientEmailChange4 = 5544,
ClientEmailChangeResponse4 = 5545,
ClientGetCDNAuthToken = 5546,
ClientGetCDNAuthTokenResponse = 5547,
ClientDownloadRateStatistics = 5548,
ClientRequestAccountData = 5549,
ClientRequestAccountDataResponse = 5550,
ClientResetForgottenPassword4 = 5551,
ClientHideFriend = 5552,
ClientFriendsGroupsList = 5553,
ClientGetClanActivityCounts = 5554,
ClientGetClanActivityCountsResponse = 5555,
ClientOGSReportString = 5556,
ClientOGSReportBug = 5557,
ClientSentLogs = 5558,
ClientLogonGameServer = 5559,
AMClientCreateFriendsGroup = 5560,
AMClientCreateFriendsGroupResponse = 5561,
AMClientDeleteFriendsGroup = 5562,
AMClientDeleteFriendsGroupResponse = 5563,
AMClientRenameFriendsGroup = 5564,
AMClientRenameFriendsGroupResponse = 5565,
AMClientAddFriendToGroup = 5566,
AMClientAddFriendToGroupResponse = 5567,
AMClientRemoveFriendFromGroup = 5568,
AMClientRemoveFriendFromGroupResponse = 5569,
ClientAMGetPersonaNameHistory = 5570,
ClientAMGetPersonaNameHistoryResponse = 5571,
ClientRequestFreeLicense = 5572,
ClientRequestFreeLicenseResponse = 5573,
ClientDRMDownloadRequestWithCrashData = 5574,
ClientAuthListAck = 5575,
ClientItemAnnouncements = 5576,
ClientRequestItemAnnouncements = 5577,
ClientFriendMsgEchoToSender = 5578,
ClientChangeSteamGuardOptions = 5579, // obsolete
ClientChangeSteamGuardOptionsResponse = 5580, // obsolete
ClientOGSGameServerPingSample = 5581,
ClientCommentNotifications = 5582,
ClientRequestCommentNotifications = 5583,
ClientPersonaChangeResponse = 5584,
ClientRequestWebAPIAuthenticateUserNonce = 5585,
ClientRequestWebAPIAuthenticateUserNonceResponse = 5586,
ClientPlayerNicknameList = 5587,
AMClientSetPlayerNickname = 5588,
AMClientSetPlayerNicknameResponse = 5589,
ClientRequestOAuthTokenForApp = 5590, // obsolete
ClientRequestOAuthTokenForAppResponse = 5591, // obsolete
ClientCreateAccountProto = 5590,
ClientCreateAccountProtoResponse = 5591,
ClientGetNumberOfCurrentPlayersDP = 5592,
ClientGetNumberOfCurrentPlayersDPResponse = 5593,
ClientServiceMethod = 5594,
ClientServiceMethodResponse = 5595,
ClientFriendUserStatusPublished = 5596,
ClientCurrentUIMode = 5597,
ClientVanityURLChangedNotification = 5598,
ClientUserNotifications = 5599,
BaseDFS = 5600,
DFSGetFile = 5601,
DFSInstallLocalFile = 5602,
DFSConnection = 5603,
DFSConnectionReply = 5604,
ClientDFSAuthenticateRequest = 5605,
ClientDFSAuthenticateResponse = 5606,
ClientDFSEndSession = 5607,
DFSPurgeFile = 5608,
DFSRouteFile = 5609,
DFSGetFileFromServer = 5610,
DFSAcceptedResponse = 5611,
DFSRequestPingback = 5612,
DFSRecvTransmitFile = 5613,
DFSSendTransmitFile = 5614,
DFSRequestPingback2 = 5615,
DFSResponsePingback2 = 5616,
ClientDFSDownloadStatus = 5617,
DFSStartTransfer = 5618,
DFSTransferComplete = 5619,
DFSRouteFileResponse = 5620,
BaseMDS = 5800,
ClientMDSLoginRequest = 5801, // obsolete
ClientMDSLoginResponse = 5802, // obsolete
ClientMDSUploadManifestRequest = 5803, // obsolete
ClientMDSUploadManifestResponse = 5804, // obsolete
ClientMDSTransmitManifestDataChunk = 5805, // obsolete
ClientMDSHeartbeat = 5806, // obsolete
ClientMDSUploadDepotChunks = 5807, // obsolete
ClientMDSUploadDepotChunksResponse = 5808, // obsolete
ClientMDSInitDepotBuildRequest = 5809, // obsolete
ClientMDSInitDepotBuildResponse = 5810, // obsolete
AMToMDSGetDepotDecryptionKey = 5812,
MDSToAMGetDepotDecryptionKeyResponse = 5813,
MDSGetVersionsForDepot = 5814, // obsolete
MDSGetVersionsForDepotResponse = 5815, // obsolete
MDSSetPublicVersionForDepot = 5816, // obsolete
MDSSetPublicVersionForDepotResponse = 5817, // obsolete
ClientMDSInitWorkshopBuildRequest = 5816, // obsolete
ClientMDSInitWorkshopBuildResponse = 5817, // obsolete
ClientMDSGetDepotManifest = 5818, // obsolete
ClientMDSGetDepotManifestResponse = 5819, // obsolete
ClientMDSGetDepotManifestChunk = 5820, // obsolete
ClientMDSUploadRateTest = 5823, // obsolete
ClientMDSUploadRateTestResponse = 5824, // obsolete
MDSDownloadDepotChunksAck = 5825, // obsolete
MDSContentServerStatsBroadcast = 5826, // obsolete
MDSContentServerConfigRequest = 5827,
MDSContentServerConfig = 5828,
MDSGetDepotManifest = 5829,
MDSGetDepotManifestResponse = 5830,
MDSGetDepotManifestChunk = 5831,
MDSGetDepotChunk = 5832,
MDSGetDepotChunkResponse = 5833,
MDSGetDepotChunkChunk = 5834,
MDSUpdateContentServerConfig = 5835, // obsolete
MDSGetServerListForUser = 5836,
MDSGetServerListForUserResponse = 5837,
ClientMDSRegisterAppBuild = 5838, // obsolete
ClientMDSRegisterAppBuildResponse = 5839, // obsolete
ClientMDSSetAppBuildLive = 5840, // obsolete
ClientMDSSetAppBuildLiveResponse = 5841, // obsolete
ClientMDSGetPrevDepotBuild = 5842, // obsolete
ClientMDSGetPrevDepotBuildResponse = 5843, // obsolete
MDSToCSFlushChunk = 5844,
ClientMDSSignInstallScript = 5845, // obsolete
ClientMDSSignInstallScriptResponse = 5846, // obsolete
MDSMigrateChunk = 5847,
MDSMigrateChunkResponse = 5848,
CSBase = 6200,
CSPing = 6201,
CSPingResponse = 6202,
GMSBase = 6400,
GMSGameServerReplicate = 6401,
ClientGMSServerQuery = 6403,
GMSClientServerQueryResponse = 6404,
AMGMSGameServerUpdate = 6405,
AMGMSGameServerRemove = 6406,
GameServerOutOfDate = 6407,
DeviceAuthorizationBase = 6500,
ClientAuthorizeLocalDeviceRequest = 6501,
ClientAuthorizeLocalDevice = 6502, // obsolete
ClientAuthorizeLocalDeviceResponse = 6502,
ClientDeauthorizeDeviceRequest = 6503,
ClientDeauthorizeDevice = 6504,
ClientUseLocalDeviceAuthorizations = 6505,
ClientGetAuthorizedDevices = 6506,
ClientGetAuthorizedDevicesResponse = 6507,
AMNotifySessionDeviceAuthorized = 6508,
ClientAuthorizeLocalDeviceNotification = 6509,
MMSBase = 6600,
ClientMMSCreateLobby = 6601,
ClientMMSCreateLobbyResponse = 6602,
ClientMMSJoinLobby = 6603,
ClientMMSJoinLobbyResponse = 6604,
ClientMMSLeaveLobby = 6605,
ClientMMSLeaveLobbyResponse = 6606,
ClientMMSGetLobbyList = 6607,
ClientMMSGetLobbyListResponse = 6608,
ClientMMSSetLobbyData = 6609,
ClientMMSSetLobbyDataResponse = 6610,
ClientMMSGetLobbyData = 6611,
ClientMMSLobbyData = 6612,
ClientMMSSendLobbyChatMsg = 6613,
ClientMMSLobbyChatMsg = 6614,
ClientMMSSetLobbyOwner = 6615,
ClientMMSSetLobbyOwnerResponse = 6616,
ClientMMSSetLobbyGameServer = 6617,
ClientMMSLobbyGameServerSet = 6618,
ClientMMSUserJoinedLobby = 6619,
ClientMMSUserLeftLobby = 6620,
ClientMMSInviteToLobby = 6621,
ClientMMSFlushFrenemyListCache = 6622,
ClientMMSFlushFrenemyListCacheResponse = 6623,
ClientMMSSetLobbyLinked = 6624,
NonStdMsgBase = 6800,
NonStdMsgMemcached = 6801,
NonStdMsgHTTPServer = 6802,
NonStdMsgHTTPClient = 6803,
NonStdMsgWGResponse = 6804,
NonStdMsgPHPSimulator = 6805,
NonStdMsgChase = 6806,
NonStdMsgDFSTransfer = 6807,
NonStdMsgTests = 6808,
NonStdMsgUMQpipeAAPL = 6809,
NonStdMsgSyslog = 6810, // obsolete
NonStdMsgLogsink = 6811,
NonStdMsgSteam2Emulator = 6812,
NonStdMsgRTMPServer = 6813,
UDSBase = 7000,
ClientUDSP2PSessionStarted = 7001,
ClientUDSP2PSessionEnded = 7002,
UDSRenderUserAuth = 7003,
UDSRenderUserAuthResponse = 7004,
ClientUDSInviteToGame = 7005,
UDSFindSession = 7006, // obsolete "renamed to UDSHasSession"
UDSHasSession = 7006,
UDSFindSessionResponse = 7007, // obsolete "renamed to UDSHasSessionResponse"
UDSHasSessionResponse = 7007,
MPASBase = 7100,
MPASVacBanReset = 7101,
KGSBase = 7200,
KGSAllocateKeyRange = 7201, // obsolete
KGSAllocateKeyRangeResponse = 7202, // obsolete
KGSGenerateKeys = 7203, // obsolete
KGSGenerateKeysResponse = 7204, // obsolete
KGSRemapKeys = 7205, // obsolete
KGSRemapKeysResponse = 7206, // obsolete
KGSGenerateGameStopWCKeys = 7207, // obsolete
KGSGenerateGameStopWCKeysResponse = 7208, // obsolete
UCMBase = 7300,
ClientUCMAddScreenshot = 7301,
ClientUCMAddScreenshotResponse = 7302,
UCMValidateObjectExists = 7303, // obsolete
UCMValidateObjectExistsResponse = 7304, // obsolete
UCMResetCommunityContent = 7307,
UCMResetCommunityContentResponse = 7308,
ClientUCMDeleteScreenshot = 7309,
ClientUCMDeleteScreenshotResponse = 7310,
ClientUCMPublishFile = 7311,
ClientUCMPublishFileResponse = 7312,
ClientUCMGetPublishedFileDetails = 7313, // obsolete
ClientUCMGetPublishedFileDetailsResponse = 7314, // obsolete
ClientUCMDeletePublishedFile = 7315,
ClientUCMDeletePublishedFileResponse = 7316,
ClientUCMEnumerateUserPublishedFiles = 7317,
ClientUCMEnumerateUserPublishedFilesResponse = 7318,
ClientUCMSubscribePublishedFile = 7319, // obsolete
ClientUCMSubscribePublishedFileResponse = 7320, // obsolete
ClientUCMEnumerateUserSubscribedFiles = 7321,
ClientUCMEnumerateUserSubscribedFilesResponse = 7322,
ClientUCMUnsubscribePublishedFile = 7323, // obsolete
ClientUCMUnsubscribePublishedFileResponse = 7324, // obsolete
ClientUCMUpdatePublishedFile = 7325,
ClientUCMUpdatePublishedFileResponse = 7326,
UCMUpdatePublishedFile = 7327,
UCMUpdatePublishedFileResponse = 7328,
UCMDeletePublishedFile = 7329,
UCMDeletePublishedFileResponse = 7330,
UCMUpdatePublishedFileStat = 7331,
UCMUpdatePublishedFileBan = 7332,
UCMUpdatePublishedFileBanResponse = 7333,
UCMUpdateTaggedScreenshot = 7334, // obsolete
UCMAddTaggedScreenshot = 7335, // obsolete
UCMRemoveTaggedScreenshot = 7336, // obsolete
UCMReloadPublishedFile = 7337,
UCMReloadUserFileListCaches = 7338,
UCMPublishedFileReported = 7339,
UCMUpdatePublishedFileIncompatibleStatus = 7340,
UCMPublishedFilePreviewAdd = 7341,
UCMPublishedFilePreviewAddResponse = 7342,
UCMPublishedFilePreviewRemove = 7343,
UCMPublishedFilePreviewRemoveResponse = 7344,
UCMPublishedFilePreviewChangeSortOrder = 7345, // obsolete
UCMPublishedFilePreviewChangeSortOrderResponse = 7346, // obsolete
ClientUCMPublishedFileSubscribed = 7347,
ClientUCMPublishedFileUnsubscribed = 7348,
UCMPublishedFileSubscribed = 7349,
UCMPublishedFileUnsubscribed = 7350,
UCMPublishFile = 7351,
UCMPublishFileResponse = 7352,
UCMPublishedFileChildAdd = 7353,
UCMPublishedFileChildAddResponse = 7354,
UCMPublishedFileChildRemove = 7355,
UCMPublishedFileChildRemoveResponse = 7356,
UCMPublishedFileChildChangeSortOrder = 7357, // obsolete
UCMPublishedFileChildChangeSortOrderResponse = 7358, // obsolete
UCMPublishedFileParentChanged = 7359,
ClientUCMGetPublishedFilesForUser = 7360,
ClientUCMGetPublishedFilesForUserResponse = 7361,
UCMGetPublishedFilesForUser = 7362, // obsolete
UCMGetPublishedFilesForUserResponse = 7363, // obsolete
ClientUCMSetUserPublishedFileAction = 7364,
ClientUCMSetUserPublishedFileActionResponse = 7365,
ClientUCMEnumeratePublishedFilesByUserAction = 7366,
ClientUCMEnumeratePublishedFilesByUserActionResponse = 7367,
ClientUCMPublishedFileDeleted = 7368,
UCMGetUserSubscribedFiles = 7369,
UCMGetUserSubscribedFilesResponse = 7370,
UCMFixStatsPublishedFile = 7371,
UCMDeleteOldScreenshot = 7372, // obsolete
UCMDeleteOldScreenshotResponse = 7373, // obsolete
UCMDeleteOldVideo = 7374, // obsolete
UCMDeleteOldVideoResponse = 7375, // obsolete
UCMUpdateOldScreenshotPrivacy = 7376, // obsolete
UCMUpdateOldScreenshotPrivacyResponse = 7377, // obsolete
ClientUCMEnumerateUserSubscribedFilesWithUpdates = 7378,
ClientUCMEnumerateUserSubscribedFilesWithUpdatesResponse = 7379,
UCMPublishedFileContentUpdated = 7380,
UCMPublishedFileUpdated = 7381,
ClientWorkshopItemChangesRequest = 7382,
ClientWorkshopItemChangesResponse = 7383,
ClientWorkshopItemInfoRequest = 7384,
ClientWorkshopItemInfoResponse = 7385,
FSBase = 7500,
ClientRichPresenceUpload = 7501,
ClientRichPresenceRequest = 7502,
ClientRichPresenceInfo = 7503,
FSRichPresenceRequest = 7504,
FSRichPresenceResponse = 7505,
FSComputeFrenematrix = 7506,
FSComputeFrenematrixResponse = 7507,
FSPlayStatusNotification = 7508,
FSPublishPersonaStatus = 7509,
FSAddOrRemoveFollower = 7510,
FSAddOrRemoveFollowerResponse = 7511,
FSUpdateFollowingList = 7512,
FSCommentNotification = 7513,
FSCommentNotificationViewed = 7514,
ClientFSGetFollowerCount = 7515,
ClientFSGetFollowerCountResponse = 7516,
ClientFSGetIsFollowing = 7517,
ClientFSGetIsFollowingResponse = 7518,
ClientFSEnumerateFollowingList = 7519,
ClientFSEnumerateFollowingListResponse = 7520,
FSGetPendingNotificationCount = 7521,
FSGetPendingNotificationCountResponse = 7522,
ClientFSOfflineMessageNotification = 7523,
ClientFSRequestOfflineMessageCount = 7524,
ClientFSGetFriendMessageHistory = 7525,
ClientFSGetFriendMessageHistoryResponse = 7526,
ClientFSGetFriendMessageHistoryForOfflineMessages = 7527,
ClientFSGetFriendsSteamLevels = 7528,
ClientFSGetFriendsSteamLevelsResponse = 7529,
FSRequestFriendData = 7530,
DRMRange2 = 7600,
CEGVersionSetEnableDisableRequest = 7600,
CEGVersionSetEnableDisableResponse = 7601,
CEGPropStatusDRMSRequest = 7602,
CEGPropStatusDRMSResponse = 7603,
CEGWhackFailureReportRequest = 7604,
CEGWhackFailureReportResponse = 7605,
DRMSFetchVersionSet = 7606,
DRMSFetchVersionSetResponse = 7607,
EconBase = 7700,
EconTrading_InitiateTradeRequest = 7701,
EconTrading_InitiateTradeProposed = 7702,
EconTrading_InitiateTradeResponse = 7703,
EconTrading_InitiateTradeResult = 7704,
EconTrading_StartSession = 7705,
EconTrading_CancelTradeRequest = 7706,
EconFlushInventoryCache = 7707,
EconFlushInventoryCacheResponse = 7708,
EconCDKeyProcessTransaction = 7711,
EconCDKeyProcessTransactionResponse = 7712,
EconGetErrorLogs = 7713,
EconGetErrorLogsResponse = 7714,
RMRange = 7800,
RMTestVerisignOTP = 7800,
RMTestVerisignOTPResponse = 7801,
RMDeleteMemcachedKeys = 7803,
RMRemoteInvoke = 7804,
BadLoginIPList = 7805,
RMMsgTraceAddTrigger = 7806,
RMMsgTraceRemoveTrigger = 7807,
RMMsgTraceEvent = 7808,
UGSBase = 7900,
UGSUpdateGlobalStats = 7900,
ClientUGSGetGlobalStats = 7901,
ClientUGSGetGlobalStatsResponse = 7902,
StoreBase = 8000,
StoreUpdateRecommendationCount = 8000, // obsolete
UMQBase = 8100,
UMQLogonRequest = 8100,
UMQLogonResponse = 8101,
UMQLogoffRequest = 8102,
UMQLogoffResponse = 8103,
UMQSendChatMessage = 8104,
UMQIncomingChatMessage = 8105,
UMQPoll = 8106,
UMQPollResults = 8107,
UMQ2AM_ClientMsgBatch = 8108,
UMQEnqueueMobileSalePromotions = 8109, // obsolete
UMQEnqueueMobileAnnouncements = 8110, // obsolete
WorkshopBase = 8200,
WorkshopAcceptTOSRequest = 8200, // obsolete
WorkshopAcceptTOSResponse = 8201, // obsolete
WebAPIBase = 8300,
WebAPIValidateOAuth2Token = 8300,
WebAPIValidateOAuth2TokenResponse = 8301,
WebAPIInvalidateTokensForAccount = 8302, // obsolete
WebAPIRegisterGCInterfaces = 8303,
WebAPIInvalidateOAuthClientCache = 8304,
WebAPIInvalidateOAuthTokenCache = 8305,
WebAPISetSecrets = 8306,
BackpackBase = 8400,
BackpackAddToCurrency = 8401,
BackpackAddToCurrencyResponse = 8402,
CREBase = 8500,
CRERankByTrend = 8501, // obsolete
CRERankByTrendResponse = 8502, // obsolete
CREItemVoteSummary = 8503,
CREItemVoteSummaryResponse = 8504,
CRERankByVote = 8505, // obsolete
CRERankByVoteResponse = 8506, // obsolete
CREUpdateUserPublishedItemVote = 8507,
CREUpdateUserPublishedItemVoteResponse = 8508,
CREGetUserPublishedItemVoteDetails = 8509,
CREGetUserPublishedItemVoteDetailsResponse = 8510,
CREEnumeratePublishedFiles = 8511,
CREEnumeratePublishedFilesResponse = 8512,
CREPublishedFileVoteAdded = 8513,
SecretsBase = 8600,
SecretsRequestCredentialPair = 8600,
SecretsCredentialPairResponse = 8601,
SecretsRequestServerIdentity = 8602, // obsolete
SecretsServerIdentityResponse = 8603, // obsolete
SecretsUpdateServerIdentities = 8604, // obsolete
BoxMonitorBase = 8700,
BoxMonitorReportRequest = 8700,
BoxMonitorReportResponse = 8701,
LogsinkBase = 8800,
LogsinkWriteReport = 8800,
PICSBase = 8900,
ClientPICSChangesSinceRequest = 8901,
ClientPICSChangesSinceResponse = 8902,
ClientPICSProductInfoRequest = 8903,
ClientPICSProductInfoResponse = 8904,
ClientPICSAccessTokenRequest = 8905,
ClientPICSAccessTokenResponse = 8906,
WorkerProcess = 9000,
WorkerProcessPingRequest = 9000,
WorkerProcessPingResponse = 9001,
WorkerProcessShutdown = 9002,
DRMWorkerProcess = 9100,
DRMWorkerProcessDRMAndSign = 9100,
DRMWorkerProcessDRMAndSignResponse = 9101,
DRMWorkerProcessSteamworksInfoRequest = 9102,
DRMWorkerProcessSteamworksInfoResponse = 9103,
DRMWorkerProcessInstallDRMDLLRequest = 9104,
DRMWorkerProcessInstallDRMDLLResponse = 9105,
DRMWorkerProcessSecretIdStringRequest = 9106,
DRMWorkerProcessSecretIdStringResponse = 9107,
DRMWorkerProcessGetDRMGuidsFromFileRequest = 9108, // obsolete
DRMWorkerProcessGetDRMGuidsFromFileResponse = 9109, // obsolete
DRMWorkerProcessInstallProcessedFilesRequest = 9110,
DRMWorkerProcessInstallProcessedFilesResponse = 9111,
DRMWorkerProcessExamineBlobRequest = 9112,
DRMWorkerProcessExamineBlobResponse = 9113,
DRMWorkerProcessDescribeSecretRequest = 9114,
DRMWorkerProcessDescribeSecretResponse = 9115,
DRMWorkerProcessBackfillOriginalRequest = 9116,
DRMWorkerProcessBackfillOriginalResponse = 9117,
DRMWorkerProcessValidateDRMDLLRequest = 9118,
DRMWorkerProcessValidateDRMDLLResponse = 9119,
DRMWorkerProcessValidateFileRequest = 9120,
DRMWorkerProcessValidateFileResponse = 9121,
DRMWorkerProcessSplitAndInstallRequest = 9122,
DRMWorkerProcessSplitAndInstallResponse = 9123,
DRMWorkerProcessGetBlobRequest = 9124,
DRMWorkerProcessGetBlobResponse = 9125,
DRMWorkerProcessEvaluateCrashRequest = 9126,
DRMWorkerProcessEvaluateCrashResponse = 9127,
DRMWorkerProcessAnalyzeFileRequest = 9128,
DRMWorkerProcessAnalyzeFileResponse = 9129,
DRMWorkerProcessUnpackBlobRequest = 9130,
DRMWorkerProcessUnpackBlobResponse = 9131,
DRMWorkerProcessInstallAllRequest = 9132,
DRMWorkerProcessInstallAllResponse = 9133,
TestWorkerProcess = 9200,
TestWorkerProcessLoadUnloadModuleRequest = 9200,
TestWorkerProcessLoadUnloadModuleResponse = 9201,
TestWorkerProcessServiceModuleCallRequest = 9202,
TestWorkerProcessServiceModuleCallResponse = 9203,
QuestServerBase = 9300,
ClientGetEmoticonList = 9330,
ClientEmoticonList = 9331,
ClientSharedLibraryBase = 9400, // obsolete "renamed to SLCBase"
SLCBase = 9400,
SLCUserSessionStatus = 9400,
SLCRequestUserSessionStatus = 9401,
SLCSharedLicensesLockStatus = 9402,
ClientSharedLicensesLockStatus = 9403, // obsolete
ClientSharedLicensesStopPlaying = 9404, // obsolete
ClientSharedLibraryLockStatus = 9405,
ClientSharedLibraryStopPlaying = 9406,
SLCOwnerLibraryChanged = 9407,
SLCSharedLibraryChanged = 9408,
RemoteClientBase = 9500,
RemoteClientAuth = 9500,
RemoteClientAuthResponse = 9501,
RemoteClientAppStatus = 9502,
RemoteClientStartStream = 9503,
RemoteClientStartStreamResponse = 9504,
RemoteClientPing = 9505,
RemoteClientPingResponse = 9506,
ClientUnlockStreaming = 9507,
ClientUnlockStreamingResponse = 9508,
RemoteClientAcceptEULA = 9509,
RemoteClientGetControllerConfig = 9510,
RemoteClientGetControllerConfigResposne = 9511,
RemoteClientStreamingEnabled = 9512,
ClientConcurrentSessionsBase = 9600,
ClientPlayingSessionState = 9600,
ClientKickPlayingSession = 9601,
ClientBroadcastBase = 9700,
ClientBroadcastInit = 9700,
ClientBroadcastFrames = 9701,
ClientBroadcastDisconnect = 9702,
ClientBroadcastScreenshot = 9703,
ClientBroadcastUploadConfig = 9704,
BaseClient3 = 9800,
ClientVoiceCallPreAuthorize = 9800,
ClientVoiceCallPreAuthorizeResponse = 9801,
}
export enum EUniverse {
Invalid = 0,
Public = 1,
Beta = 2,
Internal = 3,
Dev = 4,
Max = 5,
}
export enum EChatEntryType {
Invalid = 0,
ChatMsg = 1,
Typing = 2,
InviteGame = 3,
Emote = 4, // removed "No longer supported by clients"
LobbyGameStart = 5, // removed "Listen for LobbyGameCreated_t callback instead"
LeftConversation = 6,
Entered = 7,
WasKicked = 8,
WasBanned = 9,
Disconnected = 10,
HistoricalChat = 11,
Reserved1 = 12,
Reserved2 = 13,
LinkBlocked = 14,
}
export enum EPersonaState {
Offline = 0,
Online = 1,
Busy = 2,
Away = 3,
Snooze = 4,
LookingToTrade = 5,
LookingToPlay = 6,
Max = 7,
}
export enum EAccountType {
Invalid = 0,
Individual = 1,
Multiseat = 2,
GameServer = 3,
AnonGameServer = 4,
Pending = 5,
ContentServer = 6,
Clan = 7,
Chat = 8,
ConsoleUser = 9,
AnonUser = 10,
Max = 11,
}
export enum EFriendRelationship {
None = 0,
Blocked = 1,
RequestRecipient = 2,
Friend = 3,
RequestInitiator = 4,
Ignored = 5,
IgnoredFriend = 6,
SuggestedFriend = 7,
Max = 8,
}
export enum EAccountFlags {
NormalUser = 0,
PersonaNameSet = 1,
Unbannable = 2,
PasswordSet = 4,
Support = 8,
Admin = 16,
Supervisor = 32,
AppEditor = 64,
HWIDSet = 128,
PersonalQASet = 256,
VacBeta = 512,
Debug = 1024,
Disabled = 2048,
LimitedUser = 4096,
LimitedUserForce = 8192,
EmailValidated = 16384,
MarketingTreatment = 32768,
OGGInviteOptOut = 65536,
ForcePasswordChange = 131072,
ForceEmailVerification = 262144,
LogonExtraSecurity = 524288,
LogonExtraSecurityDisabled = 1048576,
Steam2MigrationComplete = 2097152,
NeedLogs = 4194304,
Lockdown = 8388608,
MasterAppEditor = 16777216,
BannedFromWebAPI = 33554432,
ClansOnlyFromFriends = 67108864,
GlobalModerator = 134217728,
ParentalSettings = 268435456,
ThirdPartySupport = 536870912,
NeedsSSANextSteamLogon = 1073741824,
}
export enum EClanPermission {
Nobody = 0,
Owner = 1,
Officer = 2,
OwnerAndOfficer = 3,
Member = 4,
Moderator = 8,
OwnerOfficerModerator = Owner | Officer | Moderator, // 11
AllMembers = Owner | Officer | Moderator | Member, // 15
OGGGameOwner = 16,
NonMember = 128,
MemberAllowed = NonMember | Member, // 132
ModeratorAllowed = NonMember | Member | Moderator, // 140
OfficerAllowed = NonMember | Member | Moderator | Officer, // 142
OwnerAllowed = NonMember | Member | Moderator | Officer | Owner, // 143
Anybody = NonMember | Member | Moderator | Officer | Owner, // 143
}
export enum EChatPermission {
Close = 1,
Invite = 2,
Talk = 8,
Kick = 16,
Mute = 32,
SetMetadata = 64,
ChangePermissions = 128,
Ban = 256,
ChangeAccess = 512,
EveryoneNotInClanDefault = Talk, // 8
EveryoneDefault = Talk | Invite, // 10
// todo: this doesn't seem correct...
MemberDefault = Ban | Kick | Talk | Invite, // 282
OfficerDefault = Ban | Kick | Talk | Invite, // 282
OwnerDefault = ChangeAccess | Ban | SetMetadata | Mute | Kick | Talk | Invite | Close, // 891
Mask = 1019,
}
export enum EFriendFlags {
None = 0,
Blocked = 1,
FriendshipRequested = 2,
Immediate = 4,
ClanMember = 8,
OnGameServer = 16,
RequestingFriendship = 128,
RequestingInfo = 256,
Ignored = 512,
IgnoredFriend = 1024,
Suggested = 2048,
ChatMember = 4096,
FlagAll = 65535,
}
export enum EPersonaStateFlag {
HasRichPresence = 1,
InJoinableGame = 2,
Golden = 4, // removed "no longer has any effect"
OnlineUsingWeb = 256, // removed "renamed to ClientTypeWeb"
ClientTypeWeb = 256,
OnlineUsingMobile = 512, // removed "renamed to ClientTypeMobile"
ClientTypeMobile = 512,
OnlineUsingBigPicture = 1024, // removed "renamed to ClientTypeTenfoot"
ClientTypeTenfoot = 1024,
OnlineUsingVR = 2048, // removed "renamed to ClientTypeVR"
ClientTypeVR = 2048,
LaunchTypeGamepad = 4096,
}
export enum EClientPersonaStateFlag {
Status = 1,
PlayerName = 2,
QueryPort = 4,
SourceID = 8,
Presence = 16,
Metadata = 32, // removed
LastSeen = 64,
ClanInfo = 128,
GameExtraInfo = 256,
GameDataBlob = 512,
ClanTag = 1024,
Facebook = 2048,
}
export enum EAppUsageEvent {
GameLaunch = 1,
GameLaunchTrial = 2,
Media = 3,
PreloadStart = 4,
PreloadFinish = 5,
MarketingMessageView = 6,
InGameAdViewed = 7,
GameLaunchFreeWeekend = 8,
}
export enum ELicenseFlags {
None = 0,
Renew = 0x01,
RenewalFailed = 0x02,
Pending = 0x04,
Expired = 0x08,
CancelledByUser = 0x10,
CancelledByAdmin = 0x20,
LowViolenceContent = 0x40,
ImportedFromSteam2 = 0x80,
ForceRunRestriction = 0x100,
RegionRestrictionExpired = 0x200,
CancelledByFriendlyFraudLock = 0x400,
NotActivated = 0x800,
}
export enum ELicenseType {
NoLicense = 0,
SinglePurchase = 1,
SinglePurchaseLimitedUse = 2,
RecurringCharge = 3,
RecurringChargeLimitedUse = 4,
RecurringChargeLimitedUseWithOverages = 5,
RecurringOption = 6,
LimitedUseDelayedActivation = 7,
}
export enum EPaymentMethod {
None = 0,
ActivationCode = 1,
CreditCard = 2,
Giropay = 3,
PayPal = 4,
Ideal = 5,
PaySafeCard = 6,
Sofort = 7,
GuestPass = 8,
WebMoney = 9,
MoneyBookers = 10,
AliPay = 11,
Yandex = 12,
Kiosk = 13,
Qiwi = 14,
GameStop = 15,
HardwarePromo = 16,
MoPay = 17,
BoletoBancario = 18,
BoaCompraGold = 19,
BancoDoBrasilOnline = 20,
ItauOnline = 21,
BradescoOnline = 22,
Pagseguro = 23,
VisaBrazil = 24,
AmexBrazil = 25,
Aura = 26,
Hipercard = 27,
MastercardBrazil = 28,
DinersCardBrazil = 29,
AuthorizedDevice = 30,
MOLPoints = 31,
ClickAndBuy = 32,
Beeline = 33,
Konbini = 34,
EClubPoints = 35,
CreditCardJapan = 36,
BankTransferJapan = 37,
PayEasyJapan = 38, // removed "renamed to PayEasy"
PayEasy = 38,
Zong = 39,
CultureVoucher = 40,
BookVoucher = 41,
HappymoneyVoucher = 42,
ConvenientStoreVoucher = 43,
GameVoucher = 44,
Multibanco = 45,
Payshop = 46,
Maestro = 47, // removed "renamed to MaestroBoaCompra"
MaestroBoaCompra = 47,
OXXO = 48,
ToditoCash = 49,
Carnet = 50,
SPEI = 51,
ThreePay = 52,
IsBank = 53,
Garanti = 54,
Akbank = 55,
YapiKredi = 56,
Halkbank = 57,
BankAsya = 58,
Finansbank = 59,
DenizBank = 60,
PTT = 61,
CashU = 62,
AutoGrant = 64,
WebMoneyJapan = 65,
OneCard = 66,
PSE = 67,
Exito = 68,
Efecty = 69,
Paloto = 70,
PinValidda = 71,
MangirKart = 72,
BancoCreditoDePeru = 73,
BBVAContinental = 74,
SafetyPay = 75,
PagoEfectivo = 76,
Trustly = 77,
UnionPay = 78,
BitCoin = 79,
Wallet = 128,
Valve = 129,
SteamPressMaster = 130, // removed "renamed to MasterComp"
MasterComp = 130,
StorePromotion = 131, // removed "renamed to Promotional"
Promotional = 131,
OEMTicket = 256,
Split = 512,
Complimentary = 1024,
}
export enum EPurchaseResultDetail {
NoDetail = 0,
AVSFailure = 1,
InsufficientFunds = 2,
ContactSupport = 3,
Timeout = 4,
InvalidPackage = 5,
InvalidPaymentMethod = 6,
InvalidData = 7,
OthersInProgress = 8,
AlreadyPurchased = 9,
WrongPrice = 10,
FraudCheckFailed = 11,
CancelledByUser = 12,
RestrictedCountry = 13,
BadActivationCode = 14,
DuplicateActivationCode = 15,
UseOtherPaymentMethod = 16,
UseOtherFunctionSource = 17,
InvalidShippingAddress = 18,
RegionNotSupported = 19,
AcctIsBlocked = 20,
AcctNotVerified = 21,
InvalidAccount = 22,
StoreBillingCountryMismatch = 23,
DoesNotOwnRequiredApp = 24,
CanceledByNewTransaction = 25,
ForceCanceledPending = 26,
FailCurrencyTransProvider = 27,
FailedCyberCafe = 28,
NeedsPreApproval = 29,
PreApprovalDenied = 30,
WalletCurrencyMismatch = 31,
EmailNotValidated = 32,
ExpiredCard = 33,
TransactionExpired = 34,
WouldExceedMaxWallet = 35,
MustLoginPS3AppForPurchase = 36,
CannotShipToPOBox = 37,
InsufficientInventory = 38,
CannotGiftShippedGoods = 39,
CannotShipInternationally = 40,
BillingAgreementCancelled = 41,
InvalidCoupon = 42,
ExpiredCoupon = 43,
AccountLocked = 44,
OtherAbortableInProgress = 45,
ExceededSteamLimit = 46,
OverlappingPackagesInCart = 47,
NoWallet = 48,
NoCachedPaymentMethod = 49,
CannotRedeemCodeFromClient = 50,
PurchaseAmountNoSupportedByProvider = 51,
OverlappingPackagesInPendingTransaction = 52,
RateLimited = 53,
OwnsExcludedApp = 54,
CreditCardBinMismatchesType = 55,
CartValueTooHigh = 56,
BillingAgreementAlreadyExists = 57,
POSACodeNotActivated = 58,
CannotShipToCountry = 59,
HungTransactionCancelled = 60,
PaypalInternalError = 61,
UnknownGlobalCollectError = 62,
InvalidTaxAddress = 63,
PhysicalProductLimitExceeded = 64,
PurchaseCannotBeReplayed = 65,
DelayedCompletion = 66,
BundleTypeCannotBeGifted = 67,
}
export enum EIntroducerRouting {
FileShare = 0, // removed
P2PVoiceChat = 1,
P2PNetworking = 2,
}
export enum EServerFlags {
None = 0,
Active = 1,
Secure = 2,
Dedicated = 4,
Linux = 8,
Passworded = 16,
Private = 32,
}
export enum EDenyReason {
InvalidVersion = 1,
Generic = 2,
NotLoggedOn = 3,
NoLicense = 4,
Cheater = 5,
LoggedInElseWhere = 6,
UnknownText = 7,
IncompatibleAnticheat = 8,
MemoryCorruption = 9,
IncompatibleSoftware = 10,
SteamConnectionLost = 11,
SteamConnectionError = 12,
SteamResponseTimedOut = 13,
SteamValidationStalled = 14,
SteamOwnerLeftGuestUser = 15,
}
export enum EClanRank {
None = 0,
Owner = 1,
Officer = 2,
Member = 3,
Moderator = 4,
}
export enum EClanRelationship {
None = 0,
Blocked = 1,
Invited = 2,
Member = 3,
Kicked = 4,
KickAcknowledged = 5,
}
export enum EAuthSessionResponse {
OK = 0,
UserNotConnectedToSteam = 1,
NoLicenseOrExpired = 2,
VACBanned = 3,
LoggedInElseWhere = 4,
VACCheckTimedOut = 5,
AuthTicketCanceled = 6,
AuthTicketInvalidAlreadyUsed = 7,
AuthTicketInvalid = 8,
PublisherIssuedBan = 9,
}
export enum EChatRoomEnterResponse {
Success = 1,
DoesntExist = 2,
NotAllowed = 3,
Full = 4,
Error = 5,
Banned = 6,
Limited = 7,
ClanDisabled = 8,
CommunityBan = 9,
MemberBlockedYou = 10,
YouBlockedMember = 11,
// these appear to have been removed
NoRankingDataLobby = 12, // removed
NoRankingDataUser = 13, // removed
RankOutOfRange = 14, // removed
}
export enum EChatRoomType {
Friend = 1,
MUC = 2,
Lobby = 3,
}
export enum EChatInfoType {
StateChange = 1,
InfoUpdate = 2,
MemberLimitChange = 3,
}
export enum EChatAction {
InviteChat = 1,
Kick = 2,
Ban = 3,
UnBan = 4,
StartVoiceSpeak = 5,
EndVoiceSpeak = 6,
LockChat = 7,
UnlockChat = 8,
CloseChat = 9,
SetJoinable = 10,
SetUnjoinable = 11,
SetOwner = 12,
SetInvisibleToFriends = 13,
SetVisibleToFriends = 14,
SetModerated = 15,
SetUnmoderated = 16,
}
export enum EChatActionResult {
Success = 1,
Error = 2,
NotPermitted = 3,
NotAllowedOnClanMember = 4,
NotAllowedOnBannedUser = 5,
NotAllowedOnChatOwner = 6,
NotAllowedOnSelf = 7,
ChatDoesntExist = 8,
ChatFull = 9,
VoiceSlotsFull = 10,
}
export enum EAppInfoSection {
Unknown = 0,
All = 1,
First = 2,
Common = 2,
Extended = 3,
Config = 4,
Stats = 5,
Install = 6,
Depots = 7,
VAC = 8, // removed
VAC_UNUSED = 8, // removed
DRM = 9, // removed
DRM_UNUSED = 9, // removed
UFS = 10,
OGG = 11,
Items = 12, // removed
ItemsUNUSED = 12, // removed
Policies = 13,
SysReqs = 14,
Community = 15,
Store = 16,
Max = 17,
}
export enum EContentDownloadSourceType {
Invalid = 0,
CS = 1,
CDN = 2,
LCS = 3,
ProxyCache = 4,
LANPeer = 5,
Max = 5,
}
export enum EPlatformType {
Unknown = 0,
Win32 = 1,
Win64 = 2,
Linux = 3, // removed "split to Linux64 and Linux32"
Linux64 = 3,
OSX = 4,
PS3 = 5,
Linux32 = 6,
Max = 6,
}
export enum EOSType {
Unknown = -1,
IOSUnknown = -600,
AndroidUnknown = -500,
UMQ = -400,
PS3 = -300,
MacOSUnknown = -102,
MacOS104 = -101,
MacOS105 = -100,
MacOS1058 = -99,
MacOS106 = -95,
MacOS1063 = -94,
MacOS1064_slgu = -93,
MacOS1067 = -92,
MacOS107 = -90,
MacOS108 = -89,
MacOS109 = -88,
MacOS1010 = -87,
MacOS1011 = -86,
MacOS1012 = -85,
MacOSMax = -1,
LinuxUnknown = -203,
Linux22 = -202,
Linux24 = -201,
Linux26 = -200,
Linux32 = -199,
Linux35 = -198,
Linux36 = -197,
Linux310 = -196,
LinuxMax = -103,
WinUnknown = 0,
Win311 = 1,
Win95 = 2,
Win98 = 3,
WinME = 4,
WinNT = 5,
Win200 = 6, // removed "renamed to Win2000"
Win2000 = 6,
WinXP = 7,
Win2003 = 8,
WinVista = 9,
Win7 = 10, // removed "renamed to Windows7"
Windows7 = 10,
Win2008 = 11,
Win2012 = 12,
Win8 = 13, // removed "renamed to Windows8"
Windows8 = 13,
Win81 = 14, // removed "renamed to Windows81"
Windows81 = 14,
Win2012R2 = 15,
Win10 = 16, // removed "renamed to Windows10"
Windows10 = 16,
WinMAX = 15,
Max = 26,
}
export enum EServerType {
Invalid = -1,
First = 0,
Shell = 0,
GM = 1,
BUM = 2, // removed
BUMOBOSOLETE = 2, // removed
AM = 3,
BS = 4,
VS = 5,
ATS = 6,
CM = 7,
FBS = 8,
FG = 9, // removed "renamed to BoxMonitor"
BoxMonitor = 9,
SS = 10,
DRMS = 11,
HubOBSOLETE = 12, // removed
Console = 13,
ASBOBSOLETE = 14, // removed
PICS = 14,
Client = 15,
BootstrapOBSOLETE = 16, // removed,
DP = 17,
WG = 18,
SM = 19,
SLC = 20,
UFS = 21,
Util = 23,
DSS = 24, // removed "renamed to Community"
Community = 24,
P2PRelayOBSOLETE = 25, // removed
AppInformation = 26,
Spare = 27,
FTS = 28,
EPM = 29, // removed
EPMOBSOLETE = 29, // removed
PS = 30,
IS = 31,
CCS = 32,
DFS = 33,
LBS = 34,
MDS = 35,
CS = 36,
GC = 37,
NS = 38,
OGS = 39,
WebAPI = 40,
UDS = 41,
MMS = 42,
GMS = 43,
KGS = 44,
UCM = 45,
RM = 46,
FS = 47,
Econ = 48,
Backpack = 49,
UGS = 50,
Store = 51, // removed "renamed to StoreFeature"
StoreFeature = 51,
MoneyStats = 52,
CRE = 53,
UMQ = 54,
Workshop = 55,
BRP = 56,
GCH = 57,
MPAS = 58,
Trade = 59,
Secrets = 60,
Logsink = 61,
Market = 62,
Quest = 63,
WDS = 64,
ACS = 65,
PNP = 66,
TaxForm = 67,
ExternalMonitor = 68,
Parental = 69,
PartnerUpload = 70,
Partner = 71,
ES = 72,
DepotWebContent = 73,
ExternalConfig = 74,
GameNotifications = 75,
MarketRepl = 76,
MarketSearch = 77,
Localization = 78,
Steam2Emulator = 79,
PublicTest = 80,
SolrMgr = 81,
BroadcastRelay = 82,
BroadcastDirectory = 83,
VideoManager = 84,
TradeOffer = 85,
BroadcastChat = 86,
Phone = 87,
AccountScore = 88,
Support = 89,
LogRequest = 90,
LogWorker = 91,
EmailDelivery = 92,
InventoryManagement = 93,
Auth = 94,
StoreCatalog = 95,
HLTVRelay = 96,
Max = 97,
}
export enum EBillingType {
NoCost = 0,
BillOnceOnly = 1,
BillMonthly = 2,
ProofOfPrepurchaseOnly = 3,
GuestPass = 4,
HardwarePromo = 5,
Gift = 6,
AutoGrant = 7,
OEMTicket = 8,
RecurringOption = 9,
BillOnceOrCDKey = 10,
Repurchaseable = 11,
FreeOnDemand = 12,
Rental = 13,
CommercialLicense = 14,
FreeCommercialLicense = 15,
NumBillingTypes = 16,
}
export enum EActivationCodeClass {
WonCDKey = 0,
ValveCDKey = 1,
Doom3CDKey = 2,
DBLookup = 3,
Steam2010Key = 4,
Max = 5,
Test = 2147483647,
Invalid = 4294967295,
}
export enum EChatMemberStateChange {
Entered = 0x01,
Left = 0x02,
Disconnected = 0x04,
Kicked = 0x08,
Banned = 0x10,
VoiceSpeaking = 0x1000,
VoiceDoneSpeaking = 0x2000,
}
export enum ERegionCode {
USEast = 0x00,
USWest = 0x01,
SouthAmerica = 0x02,
Europe = 0x03,
Asia = 0x04,
Australia = 0x05,
MiddleEast = 0x06,
Africa = 0x07,
World = 0xFF,
}
export enum ECurrencyCode {
Invalid = 0,
USD = 1,
GBP = 2,
EUR = 3,
CHF = 4,
RUB = 5,
PLN = 6,
BRL = 7,
JPY = 8,
NOK = 9,
IDR = 10,
MYR = 11,
PHP = 12,
SGD = 13,
THB = 14,
VND = 15,
KRW = 16,
TRY = 17,
UAH = 18,
MXN = 19,
CAD = 20,
AUD = 21,
NZD = 22,
CNY = 23,
INR = 24,
CLP = 25,
PEN = 26,
COP = 27,
ZAR = 28,
HKD = 29,
TWD = 30,
SAR = 31,
AED = 32,
ARS = 34,
ILS = 35,
BYN = 36,
KZT = 37,
KWD = 38,
QAR = 39,
CRC = 40,
UYU = 41,
Max = 42,
}
export enum EDepotFileFlag {
UserConfig = 1,
VersionedUserConfig = 2,
Encrypted = 4,
ReadOnly = 8,
Hidden = 16,
Executable = 32,
Directory = 64,
CustomExecutable = 128,
InstallScript = 256,
Symlink = 512,
}
export enum EWorkshopEnumerationType {
RankedByVote = 0,
Recent = 1,
Trending = 2,
FavoriteOfFriends = 3,
VotedByFriends = 4,
ContentByFriends = 5,
RecentFromFollowedUsers = 6,
}
export enum EPublishedFileVisibility {
Public = 0,
FriendsOnly = 1,
Private = 2,
}
export enum EWorkshopFileType {
First = 0,
Community = 0,
Microtransaction = 1,
Collection = 2,
Art = 3,
Video = 4,
Screenshot = 5,
Game = 6,
Software = 7,
Concept = 8,
WebGuide = 9,
IntegratedGuide = 10,
Merch = 11,
ControllerBinding = 12,
SteamworksAccessInvite = 13,
SteamVideo = 14,
GameManagedItem = 15,
Max = 16,
}
export enum EWorkshopFileAction {
Played = 0,
Completed = 1,
}
export enum EEconTradeResponse {
Accepted = 0,
Declined = 1,
TradeBannedInitiator = 2,
TradeBannedTarget = 3,
TargetAlreadyTrading = 4,
Disabled = 5,
NotLoggedIn = 6,
Cancel = 7,
TooSoon = 8,
TooSoonPenalty = 9,
ConnectionFailed = 10,
AlreadyTrading = 11,
AlreadyHasTradeRequest = 12,
NoResponse = 13,
CyberCafeInitiator = 14,
CyberCafeTarget = 15,
SchoolLabInitiator = 16,
SchoolLabTarget = 16,
InitiatorBlockedTarget = 18,
InitiatorNeedsVerifiedEmail = 20,
InitiatorNeedsSteamGuard = 21,
TargetAccountCannotTrade = 22,
InitiatorSteamGuardDuration = 23,
InitiatorPasswordResetProbation = 24,
InitiatorNewDeviceCooldown = 25,
InitiatorSentInvalidCookie = 26,
NeedsEmailConfirmation = 27,
InitiatorRecentEmailChange = 28,
NeedsMobileConfirmation = 29,
TradingHoldForClearedTradeOffersInitiator = 30,
WouldExceedMaxAssetCount = 31,
OKToDeliver = 50,
}
export enum EMarketingMessageFlags {
None = 0,
HighPriority = 1,
PlatformWindows = 2,
PlatformMac = 4,
PlatformLinux = 8,
PlatformRestrictions = PlatformWindows | PlatformMac | PlatformLinux,
}
export enum ENewsUpdateType {
AppNews = 0,
SteamAds = 1,
SteamNews = 2,
CDDBUpdate = 3,
ClientUpdate = 4,
}
export enum ESystemIMType {
RawText = 0,
InvalidCard = 1,
RecurringPurchaseFailed = 2,
CardWillExpire = 3,
SubscriptionExpired = 4,
GuestPassReceived = 5,
GuestPassGranted = 6,
GiftRevoked = 7,
SupportMessage = 8,
SupportMessageClearAlert = 9,
Max = 10,
}
export enum EChatFlags {
Locked = 1,
InvisibleToFriends = 2,
Moderated = 4,
Unjoinable = 8,
}
export enum ERemoteStoragePlatform {
None = 0,
Windows = 1,
OSX = 2,
PS3 = 4,
Linux = 8,
Reserved1 = 8, // removed
Reserved2 = 16,
All = -1,
}
export enum EDRMBlobDownloadType {
Error = 0,
File = 1,
Parts = 2,
Compressed = 4,
AllMask = 7,
IsJob = 8,
HighPriority = 16,
AddTimestamp = 32,
LowPriority = 64,
}
export enum EDRMBlobDownloadErrorDetail {
None = 0,
DownloadFailed = 1,
TargetLocked = 2,
OpenZip = 3,
ReadZipDirectory = 4,
UnexpectedZipEntry = 5,
UnzipFullFile = 6,
UnknownBlobType = 7,
UnzipStrips = 8,
UnzipMergeGuid = 9,
UnzipSignature = 10,
ApplyStrips = 11,
ApplyMergeGuid = 12,
ApplySignature = 13,
AppIdMismatch = 14,
AppIdUnexpected = 15,
AppliedSignatureCorrupt = 16,
ApplyValveSignatureHeader = 17,
UnzipValveSignatureHeader = 18,
PathManipulationError = 19,
TargetLocked_Base = 65536,
TargetLocked_Max = 131071,
NextBase = 131072,
}
export enum EClientStat {
P2PConnectionsUDP = 0,
P2PConnectionsRelay = 1,
P2PGameConnections = 2,
P2PVoiceConnections = 3,
BytesDownloaded = 4,
Max = 5,
}
export enum EClientStatAggregateMethod {
LatestOnly = 0,
Sum = 1,
Event = 2,
Scalar = 3,
}
export enum ELeaderboardDataRequest {
Global = 0,
GlobalAroundUser = 1,
Friends = 2,
Users = 3,
}
export enum ELeaderboardSortMethod {
None = 0,
Ascending = 1,
Descending = 2,
}
export enum ELeaderboardDisplayType {
None = 0,
Numeric = 1,
TimeSeconds = 2,
TimeMilliSeconds = 3,
}
export enum ELeaderboardUploadScoreMethod {
None = 0,
KeepBest = 1,
ForceUpdate = 2,
}
export enum EUCMFilePrivacyState {
Invalid = -1,
Private = 2,
FriendsOnly = 4,
Public = 8,
All = Public | FriendsOnly | Private, // 14
}
export enum EResult {
Invalid = 0,
OK = 1,
Fail = 2,
NoConnection = 3,
InvalidPassword = 5,
LoggedInElsewhere = 6,
InvalidProtocolVer = 7,
InvalidParam = 8,
FileNotFound = 9,
Busy = 10,
InvalidState = 11,
InvalidName = 12,
InvalidEmail = 13,
DuplicateName = 14,
AccessDenied = 15,
Timeout = 16,
Banned = 17,
AccountNotFound = 18,
InvalidSteamID = 19,
ServiceUnavailable = 20,
NotLoggedOn = 21,
Pending = 22,
EncryptionFailure = 23,
InsufficientPrivilege = 24,
LimitExceeded = 25,
Revoked = 26,
Expired = 27,
AlreadyRedeemed = 28,
DuplicateRequest = 29,
AlreadyOwned = 30,
IPNotFound = 31,
PersistFailed = 32,
LockingFailed = 33,
LogonSessionReplaced = 34,
ConnectFailed = 35,
HandshakeFailed = 36,
IOFailure = 37,
RemoteDisconnect = 38,
ShoppingCartNotFound = 39,
Blocked = 40,
Ignored = 41,
NoMatch = 42,
AccountDisabled = 43,
ServiceReadOnly = 44,
AccountNotFeatured = 45,
AdministratorOK = 46,
ContentVersion = 47,
TryAnotherCM = 48,
PasswordRequiredToKickSession = 49,
AlreadyLoggedInElsewhere = 50,
Suspended = 51,
Cancelled = 52,
DataCorruption = 53,
DiskFull = 54,
RemoteCallFailed = 55,
PasswordNotSet = 56, // removed "renamed to PasswordUnset"
PasswordUnset = 56,
ExternalAccountUnlinked = 57,
PSNTicketInvalid = 58,
ExternalAccountAlreadyLinked = 59,
RemoteFileConflict = 60,
IllegalPassword = 61,
SameAsPreviousValue = 62,
AccountLogonDenied = 63,
CannotUseOldPassword = 64,
InvalidLoginAuthCode = 65,
AccountLogonDeniedNoMailSent = 66, // removed "renamed to AccountLogonDeniedNoMail"
AccountLogonDeniedNoMail = 66,
HardwareNotCapableOfIPT = 67,
IPTInitError = 68,
ParentalControlRestricted = 69,
FacebookQueryError = 70,
ExpiredLoginAuthCode = 71,
IPLoginRestrictionFailed = 72,
AccountLocked = 73, // removed "renamed to AccountLockedDown"
AccountLockedDown = 73,
AccountLogonDeniedVerifiedEmailRequired = 74,
NoMatchingURL = 75,
BadResponse = 76,
RequirePasswordReEntry = 77,
ValueOutOfRange = 78,
UnexpectedError = 79,
Disabled = 80,
InvalidCEGSubmission = 81,
RestrictedDevice = 82,
RegionLocked = 83,
RateLimitExceeded = 84,
AccountLogonDeniedNeedTwoFactorCode = 85, // removed "renamed to AccountLoginDeniedNeedTwoFactor"
AccountLoginDeniedNeedTwoFactor = 85,
ItemOrEntryHasBeenDeleted = 86, // removed "renamed to ItemDeleted"
ItemDeleted = 86,
AccountLoginDeniedThrottle = 87,
TwoFactorCodeMismatch = 88,
TwoFactorActivationCodeMismatch = 89,
AccountAssociatedToMultiplePlayers = 90, // removed "renamed to AccountAssociatedToMultiplePartners"
AccountAssociatedToMultiplePartners = 90,
NotModified = 91,
NoMobileDeviceAvailable = 92, // removed "renamed to NoMobileDevice"
NoMobileDevice = 92,
TimeIsOutOfSync = 93, // removed "renamed to TimeNotSynced"
TimeNotSynced = 93,
SMSCodeFailed = 94,
TooManyAccountsAccessThisResource = 95, // removed "renamed to AccountLimitExceeded"
AccountLimitExceeded = 95,
AccountActivityLimitExceeded = 96,
PhoneActivityLimitExceeded = 97,
RefundToWallet = 98,
EmailSendFailure = 99,
NotSettled = 100,
NeedCaptcha = 101,
GSLTDenied = 102,
GSOwnerDenied = 103,
InvalidItemType = 104,
IPBanned = 105,
GSLTExpired = 106,
InsufficientFunds = 107,
TooManyPending = 108,
NoSiteLicensesFound = 109,
WGNetworkSendExceeded = 110,
} | the_stack |
import { ExecContext } from "../helperFunctions/ExecContext";
import {
getLastOperationTrackingResultCall,
ignoredStringLiteral,
runIfIdentifierExists,
ignoredArrayExpression,
createGetMemoArray,
getLastOpValueCall,
ignoredIdentifier,
getTrackingVarName,
ignoreNode,
createSetMemoValue,
getLastOperationTrackingResultWithoutResettingCall,
getTrackingIdentifier,
runIfTrackingIdentifierExists
} from "../babelPluginHelpers";
import traverseConcat from "../traverseConcat";
import mapInnerHTMLAssignment from "./domHelpers/mapInnerHTMLAssignment";
import addElOrigin, {
addElAttributeValueOrigin,
addElAttributeNameOrigin,
trackSetElementStyle
} from "./domHelpers/addElOrigin";
import * as MemoValueNames from "../MemoValueNames";
import { consoleLog } from "../helperFunctions/logging";
import { safelyReadProperty } from "../util";
import * as OperationTypes from "../OperationTypes";
import { getShortOperationName, getShortExtraArgName } from "../names";
const propertyValueExtraArgName = getShortExtraArgName("propertyValue");
export default <any>{
argNames: log => {
if (log.astArgs.assignmentType === "MemberExpression") {
return ["object", "propertyName", "argument"];
} else {
// e.g. "x += fn()" turns into [x, x+=mem(fn()), getMem()]
return ["currentValue", "newValue", "argument"];
}
},
canInferResult: (args, extraArgs, astArgs, runtimeArgs) => {
if (astArgs.operator === "+=") {
if (astArgs.type === "MemberExpression") {
return !!runtimeArgs.assignment;
} else {
return (
args[0][1] &&
typeof args[0][0] === "string" &&
args[2][1] &&
typeof args[2][0] === "string"
);
}
}
return false;
},
exec: function AssignmentExpressionExec(
args,
astArgs,
ctx: ExecContext,
logData: any
) {
var ret;
const assignmentType = astArgs.type;
const operator = astArgs.operator;
if (assignmentType === "MemberExpression") {
const [objArg, propertyNameArg, argumentArg] = args;
var obj = objArg[0];
var propName = propertyNameArg[0];
var objT = objArg[1];
var propNameT = propertyNameArg[1];
var currentValue, currentValueT;
if (operator !== "=") {
// For simple assignment we don't need to know the current value,
// avoid problems where getter sets a property value which would
// cause infinite recursion
currentValue = obj[propName];
currentValueT = ctx.createOperationLog({
operation: "memexpAsLeftAssExp",
args: {
object: [obj, objT],
propertyName: [propName, propNameT]
},
extraArgs: {
[propertyValueExtraArgName]: [
currentValue,
ctx.getObjectPropertyTrackingValue(obj, propName)
]
},
astArgs: {},
result: currentValue,
loc: logData.loc
});
}
var argument = argumentArg[0];
let newValue;
switch (operator) {
case "=":
newValue = argument;
break;
case "+=":
newValue = obj[propName] + argument;
break;
case "-=":
newValue = obj[propName] - argument;
break;
case "*=":
newValue = obj[propName] * argument;
break;
case "/=":
newValue = obj[propName] / argument;
break;
case "|=":
newValue = obj[propName] | argument;
break;
case "%=":
newValue = obj[propName] % argument;
break;
case "&=":
newValue = obj[propName] & argument;
break;
case "**=":
newValue = obj[propName] ** argument;
break;
case "<<=":
newValue = obj[propName] << argument;
break;
case ">>=":
newValue = obj[propName] >> argument;
break;
case ">>>=":
newValue = obj[propName] >>> argument;
break;
case "^=":
newValue = obj[propName] ^ argument;
break;
default:
throw Error("unknown operator " + operator);
}
obj[propName] = newValue;
ret = newValue;
const assignmentExpressionT = ctx.createOperationLog({
result: ret,
operation: "assignmentExpression",
args: [[currentValue, currentValueT], [newValue, null], argumentArg],
astArgs: {
operator,
generated: true
},
loc: logData.loc
});
ctx.trackObjectPropertyAssignment(
obj,
propName,
assignmentExpressionT,
propNameT
);
logData.runtimeArgs = { assignment: assignmentExpressionT };
const objIsHTMLNode = typeof Node !== "undefined" && obj instanceof Node;
if (objIsHTMLNode) {
if (propName === "innerHTML") {
mapInnerHTMLAssignment(obj, argumentArg, "assignInnerHTML", 0);
} else if (["text", "textContent", "nodeValue"].includes(propName)) {
if (obj.nodeType === Node.TEXT_NODE) {
addElOrigin(obj, "textValue", {
trackingValue: argumentArg[1]
});
} else if (obj.nodeType === Node.ELEMENT_NODE) {
if (obj.childNodes.length > 0) {
// can be 0 still if textValue is ""
addElOrigin(obj.childNodes[0], "textValue", {
trackingValue: argumentArg[1]
});
}
} else {
// e.g. document fragments etc... should ideally handle this one day
}
} else if (
// This is overly broad (and will track "elOrigins" for arbitraty property names),
// but at least it makes sure all attributes are tracked
safelyReadProperty(obj, "nodeType") === Node.ELEMENT_NODE &&
typeof propName === "string"
) {
let attrName = propName;
if (attrName === "className") {
attrName = "class";
}
addElAttributeValueOrigin(obj, attrName, {
trackingValue: argumentArg[1]
});
addElAttributeNameOrigin(obj, attrName, { trackingValue: propNameT });
}
} else if (
typeof CSSStyleDeclaration !== "undefined" &&
obj instanceof CSSStyleDeclaration &&
obj["__element"]
) {
trackSetElementStyle(
obj["__element"],
propName,
ctx.createOperationLog({
operation: OperationTypes.styleAssignment,
loc: logData.loc,
args: {
styleName: [null, propNameT],
styleValue: argumentArg
},
result: propName + ": " + newValue
})
);
}
} else if (assignmentType === "Identifier") {
const [currentValueArg, newValueArg, argumentArg] = args;
ret = newValueArg[0];
} else {
throw Error("unknown: " + assignmentType);
}
return ret;
},
traverse(operationLog, charIndex) {
const { operator } = operationLog.astArgs;
if (operator === "=") {
return {
operationLog: operationLog.args.argument,
charIndex: charIndex
};
} else if (operator === "+=") {
if (operationLog.runtimeArgs && operationLog.runtimeArgs.assignment) {
return {
operationLog: operationLog.runtimeArgs.assignment,
charIndex
};
}
return traverseConcat(
operationLog.args.currentValue,
operationLog.args.argument,
charIndex
);
} else {
return;
}
},
visitor(path) {
path.node.ignore = true;
const type = path.node.left.type;
let operationArguments;
let trackingAssignment: any = null;
if (path.node.left.type === "MemberExpression") {
var property;
if (path.node.left.computed === true) {
property = path.node.left.property;
} else {
property = this.t.stringLiteral(path.node.left.property.name);
property.loc = path.node.left.property.loc;
}
operationArguments = [
[path.node.left.object, getLastOperationTrackingResultCall()],
[property, getLastOperationTrackingResultCall()],
[path.node.right, getLastOperationTrackingResultCall()]
];
} else if (path.node.left.type === "Identifier") {
var right = createSetMemoValue(
MemoValueNames.lastAssignmentExpressionArgument,
path.node.right,
getLastOperationTrackingResultCall()
);
path.node.right = right;
trackingAssignment = runIfTrackingIdentifierExists(
path.node.left.name,
path.scope,
ignoreNode(
this.t.assignmentExpression(
"=",
getTrackingIdentifier(path.node.left.name),
// Normally we want to reset the value after an operation, but the problem is
// that after the tracking assignment the result value of the assignment operation could
// be read.
// Like this: `a = (b = 4)`
// If we use reset the last tracking value the `a =` assignment will lose the tracking value
// (In theory we could detect if the result is used somehow and only not reset if we know it's used
// base on the AST)
getLastOperationTrackingResultWithoutResettingCall()
)
)
);
const identifierAssignedTo = path.node.left;
// we have to check if it exists because outside strict mode
// you can assign to undeclared global variables
const identifierValue = runIfTrackingIdentifierExists(
identifierAssignedTo.name,
path.scope,
identifierAssignedTo
);
operationArguments = [
[identifierValue, getLastOperationTrackingResultCall()],
[path.node, getLastOperationTrackingResultCall()],
createGetMemoArray(MemoValueNames.lastAssignmentExpressionArgument)
];
} else if (path.node.left.type === "ObjectPattern") {
console.log(
"assignment expression with objectpattern - not handled right now"
);
return;
} else if (path.node.left.type === "ArrayPattern") {
console.log(
"assignment expression with arraypattern - not handled right now"
);
return;
} else {
throw Error(
"unhandled assignmentexpression node.left type " + path.node.left.type
);
}
const operation = this.createNode!(
operationArguments,
{
operator: ignoredStringLiteral(path.node.operator),
type: ignoredStringLiteral(type)
},
path.node.loc
);
if (trackingAssignment) {
path.replaceWith(
this.t.sequenceExpression([
operation,
trackingAssignment,
getLastOpValueCall()
])
);
} else {
path.replaceWith(operation);
}
}
}; | the_stack |
'use strict';
import { errors } from 'azure-iot-common';
import * as machina from 'machina';
import * as tss from 'tss.js';
import { Tpm, TPM_HANDLE, TPM_ALG_ID, TPM_RC, TPM_PT, TPMA_OBJECT, TPMT_PUBLIC, TPM2B_PRIVATE } from 'tss.js';
import * as crypto from 'crypto';
import base32Encode = require('base32-encode');
import * as dbg from 'debug';
const debug = dbg('azure-iot-security-tpm:TpmSecurityClient');
/**
* @private
*/
export class TpmSecurityClient {
private static readonly _aes128SymDef: tss.TPMT_SYM_DEF_OBJECT = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 128, TPM_ALG_ID.CFB);
private static readonly _ekPersistentHandle: TPM_HANDLE = new TPM_HANDLE(0x81010001);
private static readonly _srkPersistentHandle: TPM_HANDLE = new TPM_HANDLE(0x81000001);
private static readonly _idKeyPersistentHandle: TPM_HANDLE = new TPM_HANDLE(0x81000100);
private static readonly _tpmNonceSize: number = 20; // See TPM Structures v1.2
private static readonly _ekTemplate: TPMT_PUBLIC = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
TPMA_OBJECT.restricted | TPMA_OBJECT.decrypt | TPMA_OBJECT.fixedTPM | TPMA_OBJECT.fixedParent |
TPMA_OBJECT.adminWithPolicy | TPMA_OBJECT.sensitiveDataOrigin,
Buffer.from('837197674484b3f81a90cc8d46a5d724fd52d76e06520b64f2a1da1b331469aa', 'hex'),
new tss.TPMS_RSA_PARMS(TpmSecurityClient._aes128SymDef, new tss.TPMS_NULL_ASYM_SCHEME(), 2048, 0),
new tss.TPM2B_PUBLIC_KEY_RSA());
private static readonly _srkTemplate: TPMT_PUBLIC = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
TPMA_OBJECT.restricted | TPMA_OBJECT.decrypt | TPMA_OBJECT.fixedTPM | TPMA_OBJECT.fixedParent |
TPMA_OBJECT.noDA | TPMA_OBJECT.userWithAuth | TPMA_OBJECT.sensitiveDataOrigin,
null,
new tss.TPMS_RSA_PARMS(TpmSecurityClient._aes128SymDef, new tss.TPMS_NULL_ASYM_SCHEME(), 2048, 0),
new tss.TPM2B_PUBLIC_KEY_RSA());
private _ek: TPMT_PUBLIC = null;
private _srk: TPMT_PUBLIC = null;
private _registrationId: string = '';
private _tpm: Tpm;
private _fsm: machina.Fsm;
private _idKeyPub: TPMT_PUBLIC;
private _encUriData: tss.TPM2B_DATA;
constructor(registrationId?: string, customTpm?: any) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_002: [The `customTpm` argument, if present` will be used at the underlying TPM provider. Otherwise the TPM provider will the tss TPM client with a parameter of `false` for simulator use.] */
this._tpm = customTpm ? customTpm : new Tpm(false);
if (registrationId) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_001: [The `registrationId` argument if present will be returned as the `registrationId` for subsequent calls to `getRegistrationId`.] */
this._registrationId = registrationId;
}
this._fsm = new machina.Fsm({
initialState: 'disconnected',
states: {
disconnected: {
_onEnter: (callback, err) => {
this._ek = null;
this._srk = null;
this._idKeyPub = null;
if (callback) {
if (err) {
callback(err);
} else {
callback(null, null);
}
}
},
connect: (connectCallback) => this._fsm.transition('connecting', connectCallback),
getEndorsementKey: (callback) => {
this._fsm.handle('connect', (err, _result) => {
if (err) {
callback(err);
} else {
this._fsm.handle('getEndorsementKey', callback);
}
});
},
getStorageRootKey: (callback) => {
this._fsm.handle('connect', (err, _result) => {
if (err) {
callback(err);
} else {
this._fsm.handle('getStorageRootKey', callback);
}
});
},
signWithIdentity: (dataToSign, callback) => {
this._fsm.handle('connect', (err, _result) => {
if (err) {
callback(err);
} else {
this._fsm.handle('signWithIdentity', dataToSign, callback);
}
});
},
activateIdentityKey: (identityKey, callback) => {
this._fsm.handle('connect', (err, _result) => {
if (err) {
callback(err);
} else {
this._fsm.handle('activateIdentityKey', identityKey, callback);
}
});
}
},
connecting: {
_onEnter: (callback) => {
try {
this._tpm.connect(() => {
this._createPersistentPrimary('EK', tss.Endorsement, TpmSecurityClient._ekPersistentHandle, TpmSecurityClient._ekTemplate, (ekCreateErr: Error, ekPublicKey: TPMT_PUBLIC) => {
if (ekCreateErr) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_007: [Any errors from interacting with the TPM hardware will cause in SecurityDeviceError to be returned in the err parameter of the callback.] */
this._fsm.transition('disconnected', callback, ekCreateErr);
} else {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_006: [The `getEndorsementKey` function shall query the TPM hardware and return the `endorsementKey` in the callback.] */
this._ek = ekPublicKey;
this._createPersistentPrimary('SRK', tss.Owner, TpmSecurityClient._srkPersistentHandle, TpmSecurityClient._srkTemplate, (srkCreateErr: Error, srkPublicKey: TPMT_PUBLIC) => {
if (srkCreateErr) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_009: [Any errors from interacting with the TPM hardware will cause in SecurityDeviceError to be returned in the err parameter of the callback.] */
this._fsm.transition('disconnected', callback, srkCreateErr);
} else {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_008: [The `getStorageRootKey` function shall query the TPM hardware and return the `storageRootKey` in the callback.] */
this._srk = srkPublicKey;
this._readPersistentPrimary('IDENTITY', TpmSecurityClient._idKeyPersistentHandle, (_readIdErr: Error, idkPublicKey: TPMT_PUBLIC) => {
//
// Not any kind of fatal error if we can't retrieve the identity public portion. This device might not have ever been provisioned.
// If there is a signing operation attempted before an activate is attempted, an error will occur.
//
this._idKeyPub = idkPublicKey;
this._fsm.transition('connected', callback);
});
}
});
}
});
});
} catch (err) {
this._fsm.transition('disconnected', callback, err);
}
},
'*': () => this._fsm.deferUntilTransition()
},
connected: {
_onEnter: (callback) => {
callback(null);
},
getEndorsementKey: (callback) => {
callback(null, this._ek.asTpm2B());
},
getStorageRootKey: (callback) => {
callback(null, this._srk.asTpm2B());
},
signWithIdentity: (dataToSign, callback) => {
this._signData(dataToSign, (err: Error, signedData: Buffer) => {
if (err) {
debug('Error from signing data: ' + err);
this._fsm.transition('disconnected', callback, err);
} else {
callback(null, signedData);
}
});
},
activateIdentityKey: (identityKey, callback) => {
this._activateIdentityKey(identityKey, (err: Error) => {
if (err) {
debug('Error from activate: ' + err);
this._fsm.transition('disconnected', callback, err);
} else {
callback(null, null);
}
});
},
}
}
});
this._fsm.on('transition', (data) => debug('TPM security State Machine: ' + data.fromState + ' -> ' + data.toState + ' (' + data.action + ')'));
this._fsm.on('handling', (data) => debug('TPM security State Machine: handling ' + data.inputType));
}
/**
* @method module:azure-iot-security-tpm.TpmSecurityClient#getEndorsementKey
* @description Query the endorsement key on the TPM.
* @param {function} callback Invoked upon completion of the operation.
* If the err argument is non-null then the endorsementKey
* parameter will be undefined.
*/
getEndorsementKey(callback: (err: Error, endorsementKey?: Buffer) => void): void {
this._fsm.handle('getEndorsementKey', callback);
}
/**
* @method module:azure-iot-security-tpm.TpmSecurityClient#getStorageRootKey
* @description Query the storage root key on the TPM.
* @param {function} callback Invoked upon completion of the operation.
* If the err argument is non-null then the storageRootKey
* parameter will be undefined.
*/
getStorageRootKey(callback: (err: Error, storageKey?: Buffer) => void): void {
this._fsm.handle('getStorageRootKey', callback);
}
/**
* @method module:azure-iot-security-tpm.TpmSecurityClient#signWithIdentity
* @description Perform a cryptographic signing operation utilizing the TPM hardware.
* @param {Buffer} dataToSign A buffer of data to sign. The signing key will have been previously
* imported into the TPM via an activateIdentityKey.
* @param {function} callback Invoked upon completion of the operation.
* If the err argument is non-null then the signedData
* parameter will be undefined.
*/
signWithIdentity(dataToSign: Buffer, callback: (err: Error, signedData?: Buffer) => void): void {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_011: [If `dataToSign` is falsy, an ReferenceError will be thrown.] */
if (!dataToSign || dataToSign.length === 0) {
throw new ReferenceError('\'dataToSign\' cannot be \'' + dataToSign + '\'');
}
this._fsm.handle('signWithIdentity', dataToSign, callback);
}
/**
* @method module:azure-iot-security-tpm.TpmSecurityClient#activateIdentityKey
* @description Activate the provided key into the TPM for use in signing operations later.
* @param {function} callback Invoked upon completion of the operation.
*/
activateIdentityKey(identityKey: Buffer, callback: (err: Error) => void): void {
if (!identityKey || identityKey.length === 0) {
throw new ReferenceError('\'identityKey\' cannot be \'' + identityKey + '\'');
}
this._fsm.handle('activateIdentityKey', identityKey, callback);
}
/**
* @method module:azure-iot-security-tpm.TpmSecurityClient#getRegistrationId
* @description Returns the registrationId originally provided to the client, or, if not provided
* it constructs one around the endorsement key.
* @param {function} callback Invoked upon completion of the operation.
* If the err argument is non-null then the registrationId
* parameter will be undefined.
*/
getRegistrationId(callback: (err: Error, registrationId?: string) => void): void {
if (this._registrationId) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_003: [If the TpmSecurityClient was given a `registrationId` at creation, that `registrationId` will be returned.] */
callback(null, this._registrationId);
} else {
this.getEndorsementKey( (endorsementError: Error, endorsementKey: Buffer) => {
if (endorsementError) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_005: [Any errors from interacting with the TPM hardware will cause an SecurityDeviceError to be returned in the err parameter of the callback.] */
callback(endorsementError);
} else {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_004: [If not provided, the `registrationId` will be constructed and returned as follows:
The endorsementKey will be queried.
The endorsementKey will be hashed utilizing SHA256.
The resultant digest will be base 32 encoded in conformance with the `RFC4648` specification.
The resultant string will have terminating `=` characters removed.] */
const hash = crypto.createHash('sha256');
hash.update(endorsementKey);
this._registrationId = (base32Encode(hash.digest(), 'RFC4648').toLowerCase()).replace(/=/g, '');
callback(null, this._registrationId);
}
});
}
}
private _createPersistentPrimary(name: string, hierarchy: TPM_HANDLE, handle: TPM_HANDLE, template: TPMT_PUBLIC, callback: (err: Error, resultPublicKey?: TPMT_PUBLIC) => void): void {
const checkErrorAndContinue = (opName, next, errorOut) => {
return (err, resp) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug(opName + '(' + name + ') returned ' + TPM_RC[rc]);
if (rc === TPM_RC.SUCCESS) {
next(resp);
} else {
errorOut(err);
}
};
};
this._tpm.allowErrors().ReadPublic(
handle,
checkErrorAndContinue(
'ReadPublic',
(resp: tss.ReadPublicResponse) => { // SUCCESS: an EK already exists.
debug('ReadPublic(' + name + ') returned ' + TPM_RC[TPM_RC.SUCCESS] + '; PUB: ' + resp.outPublic.toString());
callback(null, resp.outPublic);
},
() => { // Recoverable error: just create a new EK.
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_017: [If the endorsement key does NOT exist, a new key will be created.] */
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_018: [If the storage root key does NOT exist, a new key will be created.] */
this._tpm.withSession(tss.NullPwSession).CreatePrimary(
hierarchy,
new tss.TPMS_SENSITIVE_CREATE(),
template,
null,
null,
checkErrorAndContinue('CreatePrimary', (resp: tss.CreatePrimaryResponse) => {
this._tpm.withSession(tss.NullPwSession).EvictControl(
tss.Owner,
resp.handle,
handle,
checkErrorAndContinue('EvictControl', () => {
debug('EvictControl(0x' + resp.handle.handle.toString(16) + ', 0x' + handle.handle.toString(16) + ') returned ' + TPM_RC[TPM_RC.SUCCESS]);
this._tpm.FlushContext(
resp.handle,
checkErrorAndContinue('FlushContext', () => {
callback(null, resp.outPublic); // SUCCESS: an EK has been created.
},
callback)
);
},
callback)
);
},
callback)
);
}
)
);
}
private _readPersistentPrimary(name: string, handle: TPM_HANDLE, callback: (err: Error, resultPublicKey: TPMT_PUBLIC) => void): void {
this._tpm.allowErrors().ReadPublic(handle, (err: tss.TpmError, resp: tss.ReadPublicResponse) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('ReadPublic(' + name + ') returned ' + TPM_RC[rc] + (rc === TPM_RC.SUCCESS ? '; PUB: ' + resp.outPublic.toString() : ''));
if (rc !== TPM_RC.SUCCESS) {
debug('readPersistentPrimary failed for: ' + name);
callback(new errors.SecurityDeviceError('Authorization unable to find a persistent identity key.'), null);
} else {
callback(null, resp.outPublic);
}
});
}
private _getPropsAndHashAlg(callback: (err: tss.TpmError, algorithm?: TPM_ALG_ID, properties?: tss.TPML_TAGGED_TPM_PROPERTY) => void): void {
const idKeyHashAlg: TPM_ALG_ID = (<tss.TPMS_SCHEME_HMAC>(<tss.TPMS_KEYEDHASH_PARMS>this._idKeyPub.parameters).scheme).hashAlg;
this._tpm.GetCapability(tss.TPM_CAP.TPM_PROPERTIES, TPM_PT.INPUT_BUFFER, 1, (err: tss.TpmError, caps: tss.GetCapabilityResponse) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('GetCapability returned: ' + TPM_RC[rc]);
if (rc === TPM_RC.SUCCESS) {
const props = <tss.TPML_TAGGED_TPM_PROPERTY>caps.capabilityData;
callback(null, idKeyHashAlg, props);
} else {
callback(err);
}
});
}
private _signData(dataToSign: Buffer, callback: (err: Error, signedData?: Buffer) => void): void {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_013: [If `signWithIdentity` is invoked without a previous successful invocation of `activateIdentityKey`, the callback will be invoked with `err` of `InvalidOperationError`] */
if (!this._idKeyPub) {
return callback(new errors.InvalidOperationError('activateIdentityKey must be invoked before any signing is attempted.'));
}
this._getPropsAndHashAlg((err, idKeyHashAlg, props) => {
if (err) {
const secErr = new errors.SecurityDeviceError('Could not get TPM capabilities');
(<any>secErr).tpmError = err;
callback(secErr);
} else if (props.tpmProperty.length !== 1 || props.tpmProperty[0].property !== TPM_PT.INPUT_BUFFER) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_015: [If the tpm device is not properly configured, the callback will be invoked with `err` of `SecurityDeviceError`.] */
callback(new errors.SecurityDeviceError('Unexpected result of TPM2_GetCapability(TPM_PT.INPUT_BUFFER)'));
} else {
const maxInputBuffer: number = props.tpmProperty[0].value;
if (dataToSign.length <= maxInputBuffer) {
this._tpm.withSession(tss.NullPwSession).HMAC(TpmSecurityClient._idKeyPersistentHandle, dataToSign, idKeyHashAlg, (err: tss.TpmError, signature: Buffer) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('HMAC returned: ' + TPM_RC[rc]);
if (rc === TPM_RC.SUCCESS) {
callback(null, signature);
} else {
callback(err);
}
});
} else {
let curPos: number = 0;
let bytesLeft: number = dataToSign.length;
let hSequence: TPM_HANDLE = null;
let loopFn = () => {
if (bytesLeft > maxInputBuffer) {
let sliceCurPos = curPos;
bytesLeft -= maxInputBuffer;
curPos += maxInputBuffer;
this._tpm.withSession(tss.NullPwSession).SequenceUpdate(hSequence, dataToSign.slice(sliceCurPos, sliceCurPos + maxInputBuffer), loopFn);
} else {
this._tpm.withSession(tss.NullPwSession).SequenceComplete(hSequence, dataToSign.slice(curPos, curPos + bytesLeft), new TPM_HANDLE(tss.TPM_RH.NULL), (err: tss.TpmError, resp: tss.SequenceCompleteResponse) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('SequenceComplete returned: ' + TPM_RC[rc]);
if (rc === TPM_RC.SUCCESS) {
callback(null, resp.result);
} else {
callback(err);
}
});
}
};
this._tpm.withSession(tss.NullPwSession).HMAC_Start(TpmSecurityClient._idKeyPersistentHandle, Buffer.alloc(0), idKeyHashAlg, (err: tss.TpmError, hSeq: TPM_HANDLE) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('HMAC_Start returned: ' + TPM_RC[rc]);
if (err) {
const secErr = new errors.SecurityDeviceError('Could not hash key');
(<any>secErr).tpmError = err;
callback(secErr);
} else {
hSequence = hSeq;
loopFn();
}
});
}
}
});
}
private _activateIdentityKey(activationBlob: Buffer, activateCallback: (err: Error) => void): void {
let credentialBlob: tss.TPMS_ID_OBJECT;
let encodedSecret: tss.TPM2B_ENCRYPTED_SECRET;
let idKeyDupBlob: tss.TPM2B_PRIVATE;
let encWrapKey: tss.TPM2B_ENCRYPTED_SECRET;
//
// Un-marshal components of the activation blob received from the provisioning service.
//
let buf: tss.TpmBuffer = activationBlob instanceof Buffer ? new tss.TpmBuffer(activationBlob) : activationBlob;
credentialBlob = buf.createSizedObj(tss.TPMS_ID_OBJECT);
encodedSecret = buf.createObj(tss.TPM2B_ENCRYPTED_SECRET);
idKeyDupBlob = buf.createObj(tss.TPM2B_PRIVATE);
encWrapKey = buf.createObj(tss.TPM2B_ENCRYPTED_SECRET);
this._idKeyPub = buf.createSizedObj(TPMT_PUBLIC);
this._encUriData = buf.createObj(tss.TPM2B_DATA);
debug('The value of the encUriData: ' + this._encUriData.toString());
if (!buf.isOk())
return activateCallback(new errors.SecurityDeviceError('Could not unmarshal activation data'));
if (buf.curPos !== buf.size)
debug('WARNING: Activation Blob sent by DPS has contains extra unidentified data');
//
// Start a policy session to be used with ActivateCredential()
//
this._tpm.GetRandom(TpmSecurityClient._tpmNonceSize, (err: tss.TpmError, nonce: Buffer) => {
if (err) {
const secErr = new errors.SecurityDeviceError('Could not get random nonce');
(<any>secErr).tpmError = err;
activateCallback(secErr);
} else {
this._tpm.StartAuthSession(null, null, nonce, null, tss.TPM_SE.POLICY, tss.NullSymDef, TPM_ALG_ID.SHA256, (err: tss.TpmError, resp: tss.StartAuthSessionResponse) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('StartAuthSession(POLICY_SESS) returned ' + TPM_RC[rc] + '; sess handle: ' + resp.handle.handle.toString(16));
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Authorization session unable to be created. RC value: ' + TPM_RC[rc].toString()));
} else {
let policySession = new tss.Session(resp.handle, resp.nonceTPM);
//
// Apply the policy necessary to authorize an EK on Windows
//
// this._tpm.withSession(tss.NullPwSession).PolicySecret(tss.Endorsement, policySession.SessIn.sessionHandle, null, null, null, 0, (err: tss.TpmError, _resp: tss.PolicySecretResponse) => {
this._tpm.PolicySecret(tss.Endorsement, policySession.SessIn.sessionHandle, null, null, null, 0, (err: tss.TpmError, _resp: tss.PolicySecretResponse) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('PolicySecret() returned ' + TPM_RC[rc]);
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Unable to apply the necessary policy to authorize the EK. RC value: ' + TPM_RC[rc].toString()));
} else {
//
// Use ActivateCredential() to decrypt symmetric key that is used as an inner protector
// of the duplication blob of the new Device ID key generated by DRS.
//
this._tpm.withSessions(tss.NullPwSession, policySession).ActivateCredential(TpmSecurityClient._srkPersistentHandle, TpmSecurityClient._ekPersistentHandle, credentialBlob, encodedSecret.secret, (err: tss.TpmError, innerWrapKey: Buffer) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('ActivateCredential() returned ' + TPM_RC[rc] + '; innerWrapKey size ' + innerWrapKey.length);
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Unable to decrypt the symmetric key used to protect duplication blob. RC value: ' + TPM_RC[rc].toString()));
} else if (innerWrapKey.length === 0) {
activateCallback(new errors.SecurityDeviceError('Unable to unwrap inner key - must have administrator privilege'));
} else {
//
// Initialize parameters of the symmetric key used by DRS
// Note that the client uses the key size chosen by DRS, but other parameters are fixed (an AES key in CFB mode).
//
let symDef = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, innerWrapKey.length * 8, TPM_ALG_ID.CFB);
//
// Import the new Device ID key issued by DRS to the device's TPM
//
this._tpm.withSession(tss.NullPwSession).Import(TpmSecurityClient._srkPersistentHandle, innerWrapKey, this._idKeyPub, idKeyDupBlob, encWrapKey.secret, symDef, (err: tss.TpmError, idKeyPrivate: TPM2B_PRIVATE) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('Import() returned ' + TPM_RC[rc] + '; idKeyPrivate size ' + idKeyPrivate.buffer.length);
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Unable to import the device id key into the TPM. RC value: ' + TPM_RC[rc].toString()));
} else {
//
// Load the imported key into the TPM
//
this._tpm.withSession(tss.NullPwSession).Load(TpmSecurityClient._srkPersistentHandle, idKeyPrivate, this._idKeyPub, (err: tss.TpmError, hIdKey: TPM_HANDLE) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('Load() returned ' + TPM_RC[rc] + '; ID key handle: 0x' + hIdKey.handle.toString(16));
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Unable to load the device id key into the TPM. RC value: ' + TPM_RC[rc].toString()));
} else {
//
// Remove possibly existing persistent instance of the previous Device ID key
//
this._tpm.allowErrors().withSession(tss.NullPwSession).EvictControl(tss.Owner, TpmSecurityClient._idKeyPersistentHandle, TpmSecurityClient._idKeyPersistentHandle, () => {
//
// Persist the new Device ID key
//
this._tpm.withSession(tss.NullPwSession).EvictControl(tss.Owner, hIdKey, TpmSecurityClient._idKeyPersistentHandle, (err: tss.TpmError) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
if (rc !== TPM_RC.SUCCESS) {
/*Codes_SRS_NODE_TPM_SECURITY_CLIENT_06_016: [If an error is encountered activating the identity key, the callback with be invoked with an `Error` of `SecurityDeviceError`.] */
activateCallback(new errors.SecurityDeviceError('Unable to persist the device id key into the TPM. RC value: ' + TPM_RC[rc].toString()));
} else {
//
// Free the ID Key transient handle and the session object. Doesn't matter if it "fails". Go on at this point./
//
this._tpm.FlushContext(hIdKey, (err: tss.TpmError) => {
const rc = err ? err.responseCode : TPM_RC.SUCCESS;
debug('FlushContext(TRANS_ID_KEY) returned ' + TPM_RC[rc]);
if (err) {
const secErr = new errors.SecurityDeviceError('Could not get TPM capabilities');
(<any>secErr).tpmError = err;
activateCallback(secErr);
} else {
this._tpm.FlushContext(policySession.SessIn.sessionHandle, (err: tss.TpmError) => {
debug('FlushContext(POLICY_SESS) returned ' + TPM_RC[rc]);
if (err) {
const secErr = new errors.SecurityDeviceError('Could not get TPM capabilities');
(<any>secErr).tpmError = err;
activateCallback(secErr);
} else {
activateCallback(null);
}
});
}
});
}
});
});
}
});
}
});
}
});
}
});
}
});
}
});
}
} | the_stack |
const defaultConfig = {
debug: { automagic: false, build: false, hooks: false, performance: false, shortcodes: false, stacks: false },
distDir: 'public',
srcDir: 'src',
rootDir: process.cwd(),
build: {
numberOfWorkers: -1,
shuffleRequests: false,
},
server: {
prefix: '',
},
shortcodes: {
closePattern: '}}',
openPattern: '{{',
},
hooks: {
disable: [],
},
origin: '',
plugins: {},
};
jest.mock('../validations.ts', () => ({
getDefaultConfig: () => defaultConfig,
}));
jest.mock('cosmiconfig', () => {
return {
cosmiconfigSync: () => ({
search: () => ({ config: defaultConfig }),
}),
};
});
describe('#getConfig', () => {
const { resolve } = require('path');
const output = {
$$internal: {
ssrComponents: resolve(process.cwd(), './___ELDER___/compiled'),
clientComponents: resolve(process.cwd(), `./public/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./public/_elderjs`),
// findComponent: () => {},
logPrefix: '[Elder.js]:',
serverPrefix: '',
},
build: false,
debug: {
automagic: false,
build: false,
hooks: false,
performance: false,
shortcodes: false,
stacks: false,
},
distDir: resolve(process.cwd(), './public'),
rootDir: process.cwd(),
srcDir: resolve(process.cwd(), './src'),
server: false,
prefix: '',
shortcodes: {
closePattern: '}}',
openPattern: '{{',
},
hooks: {
disable: [],
},
origin: '',
plugins: {},
context: 'unknown',
worker: false,
};
beforeEach(() => {
jest.resetModules();
});
it('sets the expected default', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
// eslint-disable-next-line global-require
const getConfig = require('../getConfig').default;
expect(getConfig()).toStrictEqual(
expect.objectContaining({
...output,
$$internal: {
...output.$$internal,
findComponent: expect.anything(),
},
}),
);
});
describe('it accepts custom initalization options', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
// eslint-disable-next-line global-require
const getConfig = require('../getConfig').default;
const common = {
distDir: resolve(process.cwd(), './t/public'),
rootDir: resolve(process.cwd(), './t'),
srcDir: resolve(process.cwd(), './t/src'),
};
const common$$Internal = {
ssrComponents: resolve(process.cwd(), './t/___ELDER___/compiled'),
clientComponents: resolve(process.cwd(), `./t/public/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/_elderjs`),
// findComponent: () => {},
logPrefix: '[Elder.js]:',
};
it('gives back a custom context such as serverless', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'serverless', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'serverless',
}),
);
expect(r.$$internal).toMatchObject(common$$Internal);
});
it('sets a server without a prefix', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: false,
}),
);
expect(r.$$internal).toMatchObject(common$$Internal);
});
it('sets a server with a server.prefix without leading or trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', server: { prefix: 'testing' }, rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a server.prefix with a trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', server: { prefix: 'testing/' }, rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a server.prefix with a leading "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', server: { prefix: '/testing' }, rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a server.prefix with a leading and trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', server: { prefix: '/testing/' }, rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a prefix without a leading or trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', prefix: 'testing', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a prefix with a leading "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', prefix: '/testing', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a prefix with a trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', prefix: '/testing/', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets a server with a prefix with a leading and trailing "/"', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'server', prefix: '/testing/', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'server',
server: {
prefix: '/testing',
},
prefix: '/testing',
}),
);
expect(r.$$internal).toMatchObject({
...common$$Internal,
clientComponents: resolve(process.cwd(), `./t/public/testing/_elderjs/svelte`),
distElder: resolve(process.cwd(), `./t/public/testing/_elderjs`),
});
});
it('sets build with default', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
const r = getConfig({ context: 'build', rootDir: 't' });
expect(r).toStrictEqual(
expect.objectContaining({
...common,
context: 'build',
build: {
numberOfWorkers: -1,
shuffleRequests: false,
},
}),
);
expect(r.$$internal).toMatchObject(common$$Internal);
});
});
describe('Css Options', () => {
it('sets the publicCssFile', () => {
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte.css-0050caf1.map'],
};
});
// eslint-disable-next-line global-require
const getConfig = require('../getConfig').default;
expect(getConfig({ css: 'file' })).toStrictEqual(
expect.objectContaining({
...output,
$$internal: {
...output.$$internal,
findComponent: expect.anything(),
publicCssFile: expect.stringContaining('svelte-3449427d.css'),
},
}),
);
});
it('throws an error on multiple css for publicCssFile', () => {
// eslint-disable-next-line global-require
const getConfig = require('../getConfig').default;
jest.mock('fs-extra', () => {
return {
ensureDirSync: () => {},
readdirSync: () => ['svelte-3449427d.css', 'svelte-3449427213123.css', 'svelte.css-0050caf1.map'],
};
});
expect(() => {
getConfig({ css: 'file' });
}).toThrow(/Race condition has caused multiple css/gim);
});
});
}); | the_stack |
import { Matrix4 } from 'three'
import { Debug, Log, ParserRegistry } from '../globals'
import { defaults } from '../utils'
import StructureParser from './structure-parser'
import Entity, { EntityTypeString } from '../structure/entity'
import Unitcell, { UnitcellParams } from '../symmetry/unitcell'
import Assembly, { AssemblyPart } from '../symmetry/assembly'
import { WaterNames } from '../structure/structure-constants'
import {
assignSecondaryStructure, buildUnitcellAssembly,
calculateBonds, calculateChainnames, calculateSecondaryStructure
} from '../structure/structure-utils'
import Streamer from '../streamer/streamer';
import { ParserParameters } from './parser';
import { NumberArray } from '../types';
import { Structure } from '../ngl';
// PDB helix record encoding
const HelixTypes: {[k: number]: string} = {
1: 'h', // Right-handed alpha (default)
2: 'h', // Right-handed omega
3: 'i', // Right-handed pi
4: 'h', // Right-handed gamma
5: 'g', // Right-handed 310
6: 'h', // Left-handed alpha
7: 'h', // Left-handed omega
8: 'h', // Left-handed gamma
9: 'h', // 27 ribbon/helix
10: 'h', // Polyproline
0: 'h' //Used to be ''
}
const dAminoAcids = [
'DAL', // D-ALANINE
'DAR', // D-ARGININE
'DSG', // D-ASPARAGINE
'DAS', // D-ASPARTIC ACID
'DCY', // D-CYSTEINE
'DGL', // D-GLUTAMIC ACID
'DGN', // D-GLUTAMINE
'DHI', // D-HISTIDINE
'DIL', // D-ISOLEUCINE
'DLE', // D-LEUCINE
'DLY', // D-LYSINE
'MED', // D-METHIONINE
'DPN', // D-PHENYLALANINE
'DPR', // D-PROLINE
'DSN', // D-SERINE
'DTH', // D-THREONINE
'DTR', // D-TRYPTOPHAN
'DTY', // D-TYROSINE
'DVA', // D-VALINE
'DNE' // D-NORLEUCINE
// ??? // D-SELENOCYSTEINE
]
const entityKeyList = [
'MOL_ID', 'MOLECULE', 'CHAIN', 'FRAGMENT', 'SYNONYM',
'EC', 'ENGINEERED', 'MUTATION', 'OTHER_DETAILS'
]
const reWhitespace = /\s+/
function getModresId (resno: number, chainname?: string, inscode?: string) {
let id = `${resno}`
if (chainname) id += `:${chainname}`
if (inscode) id += `^${inscode}`
return id
}
export interface PdbParserParameters extends ParserParameters {
hex: boolean
}
class PdbParser extends StructureParser {
/**
* Create a pdb parser
* @param {Streamer} streamer - streamer object
* @param {Object} params - params object
* @param {Boolean} params.hex - hexadecimal parsing of
* atom numbers >99.999 and
* residue numbers >9.999
* @return {undefined}
*/
constructor (streamer: Streamer, params?: Partial<PdbParserParameters>) {
const p = params || {}
super(streamer, p)
this.hex = defaults(p.hex, false)
}
get type () { return 'pdb' }
_parse () {
// http://www.wwpdb.org/documentation/file-format.php
if (Debug) Log.time('PdbParser._parse ' + this.name)
let isLegacy = false
const headerLine = this.streamer.peekLines(1)[ 0 ]
const headerId = headerLine.substr(62, 4)
const legacyId = headerLine.substr(72, 4)
if (headerId === legacyId && legacyId.trim()) {
isLegacy = true
}
const isPqr = this.type === 'pqr'
const isPdbqt = this.type === 'pdbqt'
const s: Structure = this.structure
const sb = this.structureBuilder
const hex = this.hex
let serialRadix = 10
let resnoRadix = 10
const firstModelOnly = this.firstModelOnly
const asTrajectory = this.asTrajectory
const cAlphaOnly = this.cAlphaOnly
const frames = s.frames
const boxes = s.boxes
let doFrames = false
let currentFrame: NumberArray, currentCoord: number
const biomolDict = s.biomolDict
let currentBiomol: Assembly
let currentPart: AssemblyPart
let currentMatrix: Matrix4
let line, recordName
let serial, chainname: string, resno: number, resname: string, occupancy: number
let inscode: string, atomname, hetero: number, bfactor: number, altloc
let formalCharge: number
let startChain, startResi, startIcode
let endChain, endResi, endIcode
let serialDict: {[k: number]: number} = {}
const unitcellDict: Partial<{
origx: Matrix4
scale: Matrix4
a: number
b: number
c: number
alpha: number
beta: number
gamma: number
spacegroup: string
}> = {}
const bondDict: {[k: string]: boolean} = {}
const entityDataList: {chainList: string[], name: string}[] = []
let currentEntityData: {chainList: string[], name: string}
let currentEntityKey: 'MOL_ID'|'MOLECULE'|'CHAIN'|'FRAGMENT'|'SYNONYM'|'EC'|'ENGINEERED'|'MUTATION'|'OTHER_DETAILS'
// MOL_ID Numbers each component; also used in SOURCE to associate
// the information.
// MOLECULE Name of the macromolecule.
// CHAIN Comma-separated list of chain identifier(s).
// FRAGMENT Specifies a domain or region of the molecule.
// SYNONYM Comma-separated list of synonyms for the MOLECULE.
// EC The Enzyme Commission number associated with the molecule.
// If there is more than one EC number, they are presented
// as a comma-separated list.
// ENGINEERED Indicates that the molecule was produced using
// recombinant technology or by purely chemical synthesis.
// MUTATION Indicates if there is a mutation.
// OTHER_DETAILS Additional comments.
const hetnameDict: {[k: string]: string} = {}
const modresDict: {[k: string]: any} = {}
const chainDict: {[k: string]: number} = {}
let chainIdx: number, chainid: string, newChain: boolean
let currentChainname: string, currentResno: number, currentResname: string, currentInscode: string
const seqresDict: {[k: string]: string[]} = {}
let currentSeqresChainname: string
const secStruct = {
helices: [] as any[],
sheets: [] as any[]
}
const helices = secStruct.helices
const sheets = secStruct.sheets
const atomMap = s.atomMap
const atomStore = s.atomStore
atomStore.resize(Math.round(this.streamer.data.length / 80))
if (isPqr || isPdbqt) atomStore.addField('partialCharge', 1, 'float32')
if (isPqr) atomStore.addField('radius', 1, 'float32')
const ap1 = s.getAtomProxy()
const ap2 = s.getAtomProxy()
let idx = 0
let modelIdx = 0
let pendingStart = true
function _parseChunkOfLines (_i: number, _n: number, lines: string[]) {
for (let i = _i; i < _n; ++i) {
line = lines[ i ]
recordName = line.substr(0, 6)
if (recordName === 'ATOM ' || recordName === 'HETATM') {
// http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
// PQR: Field_name Atom_number Atom_name Residue_name Chain_ID Residue_number X Y Z Charge Radius
if (pendingStart) {
if (asTrajectory) {
if (doFrames) {
currentFrame = new Float32Array(atomStore.count * 3)
frames.push(currentFrame)
} else {
currentFrame = []
}
currentCoord = 0
} else {
if (!firstModelOnly) serialDict = {}
}
chainIdx = 1
chainid = chainIdx.toString()
newChain = true
pendingStart = false
}
if (firstModelOnly && modelIdx > 0) continue
let x, y, z, ls: string[], dd = 0
if (isPqr) {
ls = line.split(reWhitespace)
dd = ls.length === 10 ? 1 : 0
atomname = ls[ 2 ]
if (cAlphaOnly && atomname !== 'CA') continue
x = parseFloat(ls[ 6 - dd ])
y = parseFloat(ls[ 7 - dd ])
z = parseFloat(ls[ 8 - dd ])
} else {
atomname = line.substr(12, 4).trim()
if (cAlphaOnly && atomname !== 'CA') continue
x = parseFloat(line.substr(30, 8))
y = parseFloat(line.substr(38, 8))
z = parseFloat(line.substr(46, 8))
}
if (asTrajectory) {
const j = currentCoord * 3
currentFrame[ j + 0 ] = x
currentFrame[ j + 1 ] = y
currentFrame[ j + 2 ] = z
currentCoord += 1
if (doFrames) continue
}
let element
if (isPqr) {
serial = parseInt(ls![ 1 ])
element = ''
hetero = (line[ 0 ] === 'H') ? 1 : 0
chainname = dd ? '' : ls![ 4 ]
resno = parseInt(ls![ 5 - dd! ])
inscode = ''
resname = ls![ 3 ]
altloc = ''
occupancy = 1.0
} else {
serial = parseInt(line.substr(6, 5), serialRadix)
if (hex && serial === 99999) {
serialRadix = 16
}
hetero = (line[ 0 ] === 'H') ? 1 : 0
chainname = line[ 21 ].trim()
resno = parseInt(line.substr(22, 4), resnoRadix)
if (hex && resno === 9999) {
resnoRadix = 16
}
inscode = line[ 26 ].trim()
resname = line.substr(17, 4).trim() || 'MOL'
bfactor = parseFloat(line.substr(60, 6))
altloc = line[ 16 ].trim()
occupancy = parseFloat(line.substr(54, 6))
if (!isLegacy) {
if (isPdbqt) {
element = line.substr(12, 2).trim()
} else {
element = line.substr(76, 2).trim()
if (!chainname) {
chainname = line.substr(72, 4).trim() // segid
}
}
// Where specified, formalCharge is of form "2-" or "1+"
formalCharge = parseInt((line.substr(79,1) + line.substr(78, 1)).trim())
}
}
atomStore.growIfFull()
atomStore.atomTypeId[ idx ] = atomMap.add(atomname, element)
atomStore.x[ idx ] = x
atomStore.y[ idx ] = y
atomStore.z[ idx ] = z
atomStore.serial[ idx ] = serial
atomStore.altloc[ idx ] = altloc.charCodeAt(0)
atomStore.occupancy[ idx ] = isNaN(occupancy) ? 0 : occupancy
if (isPqr) {
atomStore.partialCharge![ idx ] = parseFloat(ls![ 9 - dd! ])
atomStore.radius[ idx ] = parseFloat(ls![ 10 - dd! ])
} else {
atomStore.bfactor[ idx ] = isNaN(bfactor) ? 0 : bfactor
if (isPdbqt) {
atomStore.partialCharge![ idx ] = parseFloat(line.substr(70, 6))
}
// isFinite check will reject undefined (in legacy case) and NaN values
if (isFinite(formalCharge)) {
if (!atomStore.formalCharge) {
atomStore.addField('formalCharge', 1, 'int8')
}
atomStore.formalCharge![ idx ] = formalCharge
}
}
const modresId = getModresId(resno, chainname, inscode)
// TODO instead of looking at MODRES look at SEQRES and
// missing residues in REMARK 465
if (hetero && !modresDict[modresId] && !dAminoAcids.includes(resname)) {
if (currentChainname !== chainname || currentResname !== resname ||
(!WaterNames.includes(resname) &&
(currentResno !== resno || currentInscode !== inscode))
) {
chainIdx += 1
chainid = chainIdx.toString()
currentResno = resno
currentResname = resname
currentInscode = inscode
}
} else if (!newChain && currentChainname !== chainname) {
chainIdx += 1
chainid = chainIdx.toString()
}
sb.addAtom(modelIdx, chainname, chainid, resname, resno, hetero, undefined, inscode)
serialDict[ serial ] = idx
idx += 1
newChain = false
currentChainname = chainname
} else if (recordName === 'CONECT') {
const fromIdx = serialDict[ parseInt(line.substr(6, 5)) ]
const pos = [ 11, 16, 21, 26 ]
const bondIndex: {[k: number]: number} = {}
if (fromIdx === undefined) {
// Log.log( "missing CONNECT serial" );
continue
}
for (let j = 0; j < 4; ++j) {
let toIdx = parseInt(line.substr(pos[ j ], 5))
if (Number.isNaN(toIdx)) continue
toIdx = serialDict[ toIdx ]
if (toIdx === undefined) {
// Log.log( "missing CONNECT serial" );
continue
}/* else if( toIdx < fromIdx ){
// likely a duplicate in standard PDB format
// but not necessarily, so better remove duplicates
// in a pass after parsing (and auto bonding)
continue;
} */
if (fromIdx < toIdx) {
ap1.index = fromIdx
ap2.index = toIdx
} else {
ap1.index = toIdx
ap2.index = fromIdx
}
// interpret records where a 'toIdx' atom is given multiple times
// as double/triple bonds, e.g. CONECT 1529 1528 1528 is a double bond
if (bondIndex[ toIdx ] !== undefined) {
s.bondStore.bondOrder[ bondIndex[ toIdx ] ] += 1
} else {
const hash = ap1.index + '|' + ap2.index
if (bondDict[ hash ] === undefined) {
bondDict[ hash ] = true
bondIndex[ toIdx ] = s.bondStore.count
s.bondStore.addBond(ap1, ap2, 1) // start/assume with single bond
}
}
}
} else if (recordName === 'HELIX ') {
startChain = line[ 19 ].trim()
startResi = parseInt(line.substr(21, 4))
startIcode = line[ 25 ].trim()
endChain = line[ 31 ].trim()
endResi = parseInt(line.substr(33, 4))
endIcode = line[ 37 ].trim()
let helixType = parseInt(line.substr(39, 1))
helixType = (HelixTypes[ helixType ] || HelixTypes[0]).charCodeAt(0)
helices.push([
startChain, startResi, startIcode,
endChain, endResi, endIcode,
helixType
])
} else if (recordName === 'SHEET ') {
startChain = line[ 21 ].trim()
startResi = parseInt(line.substr(22, 4))
startIcode = line[ 26 ].trim()
endChain = line[ 32 ].trim()
endResi = parseInt(line.substr(33, 4))
endIcode = line[ 37 ].trim()
sheets.push([
startChain, startResi, startIcode,
endChain, endResi, endIcode
])
} else if (recordName === 'HETNAM') {
hetnameDict[ line.substr(11, 3) ] = line.substr(15).trim()
} else if (recordName === 'SEQRES') {
const seqresChainname = line[11].trim()
if (seqresChainname !== currentSeqresChainname) {
seqresDict[ seqresChainname ] = []
currentSeqresChainname = seqresChainname
}
seqresDict[ seqresChainname ].push(
...line.substr(19).trim().split(reWhitespace)
)
} else if (recordName === 'MODRES') {
// MODRES 2SRC PTR A 527 TYR O-PHOSPHOTYROSINE
const resname = line.substr(12, 3).trim()
const chainname = line[16].trim()
const inscode = line[22].trim()
const resno = parseInt(line.substr(18, 4).trim())
const id = getModresId(resno, chainname, inscode)
modresDict[ id ] = { resname, chainname, inscode, resno }
} else if (recordName === 'COMPND') {
const comp = line.substr(10, 70).trim()
const keyEnd = comp.indexOf(':')
const key = comp.substring(0, keyEnd)
let value
if (entityKeyList.includes(key)) {
currentEntityKey = key as 'MOL_ID'|'MOLECULE'|'CHAIN'|'FRAGMENT'|'SYNONYM'|'EC'|'ENGINEERED'|'MUTATION'|'OTHER_DETAILS'
value = comp.substring(keyEnd + 2)
} else {
value = comp
}
value = value.replace(/;$/, '')
if (currentEntityKey === 'MOL_ID') {
currentEntityData = {
chainList: [],
name: ''
}
entityDataList.push(currentEntityData)
} else if (currentEntityKey === 'MOLECULE') {
if (currentEntityData.name) currentEntityData.name += ' '
currentEntityData.name += value
} else if (currentEntityKey === 'CHAIN') {
Array.prototype.push.apply(
currentEntityData.chainList,
value.split(/\s*,\s*/)
)
}
} else if (line.startsWith('TER')) {
const cp = s.getChainProxy(s.chainStore.count - 1)
chainDict[ cp.chainname ] = cp.index
chainIdx += 1
chainid = chainIdx.toString()
newChain = true
} else if (recordName === 'REMARK' && line.substr(7, 3) === '350') {
if (line.substr(11, 12) === 'BIOMOLECULE:') {
let name = line.substr(23).trim()
if (/^(0|[1-9][0-9]*)$/.test(name)) name = 'BU' + name
currentBiomol = new Assembly(name)
biomolDict[ name ] = currentBiomol
} else if (line.substr(13, 5) === 'BIOMT') {
const biomt = line.split(/\s+/)
const row = parseInt(line[ 18 ]) - 1
if (row === 0) {
currentMatrix = new Matrix4()
currentPart.matrixList.push(currentMatrix)
}
const biomtElms = currentMatrix.elements
biomtElms[ 4 * 0 + row ] = parseFloat(biomt[ 4 ])
biomtElms[ 4 * 1 + row ] = parseFloat(biomt[ 5 ])
biomtElms[ 4 * 2 + row ] = parseFloat(biomt[ 6 ])
biomtElms[ 4 * 3 + row ] = parseFloat(biomt[ 7 ])
} else if (
line.substr(11, 30) === 'APPLY THE FOLLOWING TO CHAINS:' ||
line.substr(11, 30) === ' AND CHAINS:'
) {
if (line.substr(11, 5) === 'APPLY') {
currentPart = currentBiomol.addPart()
}
const chainList = line.substr(41, 30).split(',')
for (let j = 0, jl = chainList.length; j < jl; ++j) {
const c = chainList[ j ].trim()
if (c) currentPart.chainList.push(c)
}
}
} else if (recordName === 'HEADER') {
s.id = line.substr(62, 4)
} else if (recordName === 'TITLE ') {
s.title += (s.title ? ' ' : '') + line.substr(10, 70).trim()
} else if (recordName === 'MODEL ') {
pendingStart = true
} else if (recordName === 'ENDMDL' || line.trim() === 'END') {
if (pendingStart) continue
if (asTrajectory && !doFrames) {
frames.push(new Float32Array(currentFrame))
doFrames = true
}
modelIdx += 1
pendingStart = true
} else if (line.substr(0, 5) === 'MTRIX') {
// ignore 'given' operators
if (line[ 59 ] === '1') continue
if (!currentBiomol || currentBiomol.name !== 'NCS') {
const ncsName = 'NCS'
currentBiomol = new Assembly(ncsName)
biomolDict[ ncsName ] = currentBiomol
currentPart = currentBiomol.addPart()
}
const ncs = line.split(/\s+/)
const ncsRow = parseInt(line[ 5 ]) - 1
if (ncsRow === 0) {
currentMatrix = new Matrix4()
currentPart.matrixList.push(currentMatrix)
}
const ncsElms = currentMatrix.elements
ncsElms[ 4 * 0 + ncsRow ] = parseFloat(ncs[ 2 ])
ncsElms[ 4 * 1 + ncsRow ] = parseFloat(ncs[ 3 ])
ncsElms[ 4 * 2 + ncsRow ] = parseFloat(ncs[ 4 ])
ncsElms[ 4 * 3 + ncsRow ] = parseFloat(ncs[ 5 ])
} else if (line.substr(0, 5) === 'ORIGX') {
if (!unitcellDict.origx) {
unitcellDict.origx = new Matrix4()
}
const orgix = line.split(/\s+/)
const origxRow = parseInt(line[ 5 ]) - 1
const origxElms = unitcellDict.origx.elements
origxElms[ 4 * 0 + origxRow ] = parseFloat(orgix[ 1 ])
origxElms[ 4 * 1 + origxRow ] = parseFloat(orgix[ 2 ])
origxElms[ 4 * 2 + origxRow ] = parseFloat(orgix[ 3 ])
origxElms[ 4 * 3 + origxRow ] = parseFloat(orgix[ 4 ])
} else if (line.substr(0, 5) === 'SCALE') {
if (!unitcellDict.scale) {
unitcellDict.scale = new Matrix4()
}
const scale = line.split(/\s+/)
const scaleRow = parseInt(line[ 5 ]) - 1
const scaleElms = unitcellDict.scale.elements
scaleElms[ 4 * 0 + scaleRow ] = parseFloat(scale[ 1 ])
scaleElms[ 4 * 1 + scaleRow ] = parseFloat(scale[ 2 ])
scaleElms[ 4 * 2 + scaleRow ] = parseFloat(scale[ 3 ])
scaleElms[ 4 * 3 + scaleRow ] = parseFloat(scale[ 4 ])
} else if (recordName === 'CRYST1') {
// CRYST1 55.989 55.989 55.989 90.00 90.00 90.00 P 1 1
// 7 - 15 Real(9.3) a (Angstroms)
// 16 - 24 Real(9.3) b (Angstroms)
// 25 - 33 Real(9.3) c (Angstroms)
// 34 - 40 Real(7.2) alpha alpha (degrees).
// 41 - 47 Real(7.2) beta beta (degrees).
// 48 - 54 Real(7.2) gamma gamma (degrees).
// 56 - 66 LString sGroup Space group.
// 67 - 70 Integer z Z value.
const aLength = parseFloat(line.substr(6, 9))
const bLength = parseFloat(line.substr(15, 9))
const cLength = parseFloat(line.substr(24, 9))
const alpha = parseFloat(line.substr(33, 7))
const beta = parseFloat(line.substr(40, 7))
const gamma = parseFloat(line.substr(47, 7))
const sGroup = line.substr(55, 11).trim()
// const zValue = parseInt( line.substr( 66, 4 ) );
const box = new Float32Array(9)
box[ 0 ] = aLength
box[ 4 ] = bLength
box[ 8 ] = cLength
boxes.push(box)
if (modelIdx === 0) {
unitcellDict.a = aLength
unitcellDict.b = bLength
unitcellDict.c = cLength
unitcellDict.alpha = alpha
unitcellDict.beta = beta
unitcellDict.gamma = gamma
unitcellDict.spacegroup = sGroup
}
}
}
}
this.streamer.eachChunkOfLines(function (lines/*, chunkNo, chunkCount */) {
_parseChunkOfLines(0, lines.length, lines)
})
// finalize ensures resname will be defined for all rp.resname
// (required in entity handling below)
sb.finalize()
//
const en = entityDataList.length
if (en) {
s.eachChain(function (cp) {
cp.entityIndex = en
})
entityDataList.forEach(function (e, i) {
const chainIndexList = e.chainList.map(function (chainname) {
return chainDict[ chainname ]
})
s.entityList.push(new Entity(
s, i, e.name, 'polymer', chainIndexList
))
})
let ei = entityDataList.length
const rp = s.getResidueProxy()
const residueDict: {[k: string]: number[]} = {}
s.eachChain(function (cp) {
if (cp.entityIndex === en) {
rp.index = cp.residueOffset
if (!residueDict[ rp.resname ]) {
residueDict[ rp.resname ] = []
}
residueDict[ rp.resname ].push(cp.index)
}
})
Object.keys(residueDict).forEach(function (resname) {
const chainList = residueDict[ resname ]
let type: EntityTypeString = 'non-polymer'
let name = hetnameDict[ resname ] || resname
if (WaterNames.includes(resname)) {
name = 'water'
type = 'water'
}
s.entityList.push(new Entity(
s, ei, name, type, chainList
))
ei += 1
})
}
//
if (unitcellDict.a !== undefined) {
s.unitcell = new Unitcell(unitcellDict as UnitcellParams)
} else {
s.unitcell = undefined
}
if (helices.length || sheets.length) {
assignSecondaryStructure(s, secStruct)
}
s.finalizeAtoms()
if (!isLegacy) calculateChainnames(s)
calculateBonds(s)
s.finalizeBonds()
if (!helices.length && !sheets.length) {
calculateSecondaryStructure(s)
}
buildUnitcellAssembly(s)
if (Debug) Log.timeEnd('PdbParser._parse ' + this.name)
}
}
ParserRegistry.add('pdb', PdbParser)
ParserRegistry.add('pdb1', PdbParser)
ParserRegistry.add('ent', PdbParser)
export default PdbParser
export {
HelixTypes
} | the_stack |
import { EventHandler } from '@syncfusion/ej2-base';
import { remove } from '@syncfusion/ej2-base';
import { Chart } from '../chart';
import { Axis } from '../axis/axis';
import { AxisModel } from '../axis/axis-model';
import { ZoomMode } from '../utils/enum';
import { removeElement, RectOption, PolygonOption, createTooltip, minMax, getElement } from '../../common/utils/helper';
import { textElement } from '../../common/utils/helper';
import { PathOption, Rect, measureText, TextOption, Size, SvgRenderer, CanvasRenderer } from '@syncfusion/ej2-svg-base';
import { Zoom } from './zooming';
import { zoomComplete, onZooming } from '../../common/model/constants';
import { IZoomCompleteEventArgs, IZoomingEventArgs, IAxisData } from '../../chart/model/chart-interface';
/**
* Zooming Toolkit created here
*
* @private
*/
export class Toolkit {
private chart: Chart;
private selectionColor: string;
private fillColor: string;
private elementOpacity: string;
private elementId: string;
private zoomInElements: Element;
private zoomOutElements: Element;
private zoomElements: Element;
private panElements: Element;
private iconRect: Rect;
private hoveredID: string;
private selectedID: string;
private iconRectOverFill: string = 'transparent';
private iconRectSelectionFill: string = 'transparent';
/** @private */
public zoomCompleteEvtCollection: IZoomCompleteEventArgs[] = [];
/** @private */
constructor(chart: Chart) {
this.chart = chart;
this.elementId = chart.element.id;
this.chart.svgRenderer = new SvgRenderer(this.elementId);
this.selectionColor = chart.theme === 'Bootstrap4' ? '#FFFFFF' :
(chart.theme === 'Tailwind' || chart.theme === 'Bootstrap5' || chart.theme === 'Bootstrap5Dark' || chart.theme === 'TailwindDark') ? '#374151' :
chart.theme === 'Fluent' ? '#201F1E' : chart.theme === 'FluentDark' ? '#A19F9D' : '#ff4081';
this.fillColor = chart.theme === 'Bootstrap4' ? '#495057' :
chart.theme === 'Tailwind' ? '#6B7280' : chart.theme === 'TailwindDark' ? '#D1D5DB' :
chart.theme === 'Fluent' ? '#A19F9D' : chart.theme === 'FluentDark' ? '#484644' : '#737373';
this.iconRectOverFill = chart.theme === 'Bootstrap4' ? '#5A6268' : this.iconRectOverFill;
this.iconRectSelectionFill = chart.theme === 'Bootstrap4' ? '#5B6269' : this.iconRectSelectionFill;
this.iconRect = chart.theme === 'Bootstrap4' ? new Rect(-5, -5, 26, 26) : new Rect(0, 0, 16, 16);
}
/**
* To create the pan button.
*
* @returns {void}
* @private
*/
public createPanButton(childElement: Element, parentElement: Element): void {
const render: SvgRenderer | CanvasRenderer = this.chart.svgRenderer;
const fillColor: string = this.chart.zoomModule.isPanning ? this.selectionColor : this.fillColor;
let direction: string = 'M5,3h2.3L7.275,5.875h1.4L8.65,3H11L8,0L5,3z M3,11V8.7l2.875,0.025v-1.4L3,7.35V5L0,8L3,';
direction += '11z M11,13H8.7l0.025-2.875h-1.4L7.35,13H5l3,3L11,13z M13,5v2.3l-2.875-0.025v1.4L13,8.65V11l3-3L13,5z';
childElement.id = this.elementId + '_Zooming_Pan';
childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Pan'));
this.panElements = childElement;
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_Pan_1', 'transparent', {}, 1, this.iconRect)
) as HTMLElement);
childElement.appendChild(render.drawPath(
new PathOption(
this.elementId + '_Zooming_Pan_2', fillColor, null, null, 1, null,
direction)) as HTMLElement);
parentElement.appendChild(childElement);
this.wireEvents(childElement, this.pan);
}
/**
* To create the zoom button.
*
* @returns {void}
* @private
*/
public createZoomButton(childElement: Element, parentElement: Element): void {
const render: SvgRenderer | CanvasRenderer = this.chart.svgRenderer;
const fillColor: string = this.chart.zoomModule.isPanning ? this.fillColor : this.selectionColor;
const rectColor: string = this.chart.zoomModule.isPanning ? 'transparent' : this.iconRectSelectionFill;
let direction: string = 'M0.001,14.629L1.372,16l4.571-4.571v-0.685l0.228-0.274c1.051,0.868,2.423,1.417,3.885,1.417c3.291,0,';
direction += '5.943-2.651,5.943-5.943S13.395,0,10.103,0S4.16,2.651,4.16,5.943c0,1.508,0.503,2.834,1.417,3.885l-0.274,0.228H4.571';
direction = direction + 'L0.001,14.629L0.001,14.629z M5.943,5.943c0-2.285,1.828-4.114,4.114-4.114s4.114,1.828,4.114,';
childElement.id = this.elementId + '_Zooming_Zoom';
childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Zoom'));
this.zoomElements = childElement;
this.selectedID = this.chart.zoomModule.isPanning ? this.chart.element.id + '_Zooming_Pan_1' : this.elementId + '_Zooming_Zoom_1';
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_Zoom_1', rectColor, {}, 1, this.iconRect)
) as HTMLElement);
childElement.appendChild(render.drawPath(new PathOption(
this.elementId + '_Zooming_Zoom_3', fillColor, null, null, 1, null,
direction + '4.114s-1.828,4.114-4.114,4.114S5.943,8.229,5.943,5.943z')
) as HTMLElement);
parentElement.appendChild(childElement);
this.wireEvents(childElement, this.zoom);
}
/**
* To create the ZoomIn button.
*
* @returns {void}
* @private
*/
public createZoomInButton(childElement: Element, parentElement: Element, chart: Chart): void {
const render: SvgRenderer | CanvasRenderer = this.chart.svgRenderer;
const fillColor: string = this.fillColor;
let direction: string = 'M10.103,0C6.812,0,4.16,2.651,4.16,5.943c0,1.509,0.503,2.834,1.417,3.885l-0.274,0.229H4.571L0,';
direction += '14.628l0,0L1.372,16l4.571-4.572v-0.685l0.228-0.275c1.052,0.868,2.423,1.417,3.885,1.417c3.291,0,5.943-2.651,';
direction += '5.943-5.943C16,2.651,13.395,0,10.103,0z M10.058,10.058c-2.286,0-4.114-1.828-4.114-4.114c0-2.286,1.828-4.114,';
childElement.id = this.elementId + '_Zooming_ZoomIn';
childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('ZoomIn'));
const polygonDirection: string = '12.749,5.466 10.749,5.466 10.749,3.466 9.749,3.466 9.749,5.466 7.749,5.466 7.749,6.466';
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_ZoomIn_1', 'transparent', {}, 1, this.iconRect)
) as HTMLElement);
childElement.appendChild(render.drawPath(
new PathOption(
this.elementId + '_Zooming_ZoomIn_2', fillColor, null, null, 1, null,
direction + '4.114-4.114c2.286,0,4.114,1.828,4.114,4.114C14.172,8.229,12.344,10.058,10.058,10.058z')) as HTMLElement);
childElement.appendChild(render.drawPolygon(
new PolygonOption(
this.elementId + '_Zooming_ZoomIn_3',
polygonDirection + ' 9.749,6.466 9.749,8.466 10.749,8.466 10.749,6.466 12.749,6.466', fillColor)
) as HTMLElement);
this.zoomInElements = childElement;
this.elementOpacity = chart.zoomModule.isPanning ? '0.2' : '1';
childElement.setAttribute('opacity', this.elementOpacity);
parentElement.appendChild(childElement);
this.wireEvents(childElement, this.zoomIn);
}
/**
* To create the ZoomOut button.
*
* @returns {void}
* @private
*/
public createZoomOutButton(childElement: Element, parentElement: Element, chart: Chart): void {
const render: SvgRenderer | CanvasRenderer = this.chart.svgRenderer;
const fillColor: string = this.fillColor;
let direction: string = 'M0,14.622L1.378,16l4.533-4.533v-0.711l0.266-0.266c1.022,0.889,2.4,1.422,3.866,';
direction += '1.422c3.289,0,5.955-2.666,5.955-5.955S13.333,0,10.044,0S4.089,2.667,4.134,5.911c0,1.466,0.533,2.844,';
direction += '1.422,3.866l-0.266,0.266H4.578L0,14.622L0,14.622z M5.911,5.911c0-2.311,1.822-4.133,4.133-4.133s4.133,1.822,4.133,';
childElement.id = this.elementId + '_Zooming_ZoomOut';
childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('ZoomOut'));
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_ZoomOut_1', 'transparent', {}, 1, this.iconRect)
) as HTMLElement);
childElement.appendChild(render.drawPath(
new PathOption(
this.elementId + '_Zooming_ZoomOut_2', fillColor, null, null, 1, null,
direction + '4.133s-1.866,4.133-4.133,4.133S5.911,8.222,5.911,5.911z M12.567,6.466h-5v-1h5V6.466z')) as HTMLElement);
this.zoomOutElements = childElement;
this.elementOpacity = chart.zoomModule.isPanning ? '0.2' : '1';
childElement.setAttribute('opacity', this.elementOpacity);
parentElement.appendChild(childElement);
this.wireEvents(childElement, this.zoomOut);
}
/**
* To create the Reset button.
*
* @returns {void}
* @private
*/
public createResetButton(childElement: Element, parentElement: Element, chart: Chart, isDevice: Boolean): void {
const render: SvgRenderer | CanvasRenderer = this.chart.svgRenderer;
const fillColor: string = this.fillColor;
let size: Size;
let direction: string = 'M12.364,8h-2.182l2.909,3.25L16,8h-2.182c0-3.575-2.618-6.5-5.818-6.5c-1.128,0-2.218,0.366-3.091,';
direction += '1.016l1.055,1.178C6.581,3.328,7.272,3.125,8,3.125C10.4,3.125,12.363,5.319,12.364,8L12.364,8z M11.091,';
direction += '13.484l-1.055-1.178C9.419,12.672,8.728,12.875,8,12.875c-2.4,0-4.364-2.194-4.364-4.875h2.182L2.909,4.75L0,8h2.182c0,';
childElement.id = this.elementId + '_Zooming_Reset';
childElement.setAttribute('aria-label', this.chart.getLocalizedLabel('Reset'));
if (!isDevice) {
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_Reset_1', 'transparent', {}, 1, this.iconRect)
) as HTMLElement);
childElement.appendChild(render.drawPath(
new PathOption(
this.elementId + '_Zooming_Reset_2', fillColor, null, null, 1, null,
direction + '3.575,2.618,6.5,5.818,6.5C9.128,14.5,10.219,14.134,11.091,13.484L11.091,13.484z')) as HTMLElement);
} else {
size = measureText(this.chart.getLocalizedLabel('ResetZoom'), { size: '12px' });
childElement.appendChild(render.drawRectangle(
new RectOption(this.elementId + '_Zooming_Reset_1', 'transparent', {}, 1, new Rect(0, 0, size.width, size.height))
) as HTMLElement);
textElement(
chart.renderer,
new TextOption(
this.elementId + '_Zooming_Reset_2',
0 + size.width / 2, 0 + size.height * 3 / 4,
'middle', this.chart.getLocalizedLabel('ResetZoom'), 'rotate(0,' + (0) + ',' + (0) + ')', 'auto'
),
{ size: '12px' }, 'black', childElement, null, null, null, null, null, null, null, null, chart.enableCanvas
);
}
parentElement.appendChild(childElement);
this.wireEvents(childElement, this.reset);
}
/**
* To bind events.
*
* @returns {void}
* @private
*/
public wireEvents(element: Element, process: Function): void {
EventHandler.add(element, 'mousedown touchstart', process, this);
EventHandler.add(element, 'mouseover', this.showTooltip, this);
EventHandler.add(element, 'mouseout', this.removeTooltip, this);
}
/**
* To show tooltip.
*
* @returns {void}
* @private
*/
private showTooltip(event: MouseEvent): void {
const text: string = (<HTMLElement>event.currentTarget).id.split('_Zooming_')[1];
const left: number = (event.pageX - (measureText(text, { size: '10px' }).width + 5));
const rect: Element = getElement((<HTMLElement>event.currentTarget).id + '_1');
const icon2: Element = getElement((<HTMLElement>event.currentTarget).id + '_2');
const icon3: Element = getElement((<HTMLElement>event.currentTarget).id + '_3');
if (rect) {
this.hoveredID = rect.id;
rect.setAttribute('fill', this.iconRectOverFill);
}
if (icon2) {
icon2.setAttribute('fill', this.selectionColor);
}
if (icon3) {
icon3.setAttribute('fill', this.selectionColor);
}
if (!this.chart.isTouch) {
createTooltip('EJ2_Chart_ZoomTip', this.chart.getLocalizedLabel(text), (event.pageY + 10), left, '10px');
}
}
/** @private */
/* eslint-disable */
public removeTooltip(): void {
if(getElement(this.hoveredID)) {
let rectColor: string = this.chart.zoomModule.isPanning ? (this.hoveredID.indexOf('_Pan_') > -1) ? this.iconRectSelectionFill : 'transparent' : (this.hoveredID.indexOf('_Zoom_') > -1) ? this.iconRectSelectionFill : 'transparent';
getElement(this.hoveredID).setAttribute('fill', rectColor);
}
let icon2: Element = this.hoveredID ? getElement(this.hoveredID.replace('_1', '_2')) : null;
let icon3: Element = this.hoveredID ? getElement(this.hoveredID.replace('_1', '_3')) : null;
if(icon2) {
let iconColor: string = this.chart.zoomModule.isPanning ? (this.hoveredID.indexOf('_Pan_') > -1) ? this.selectionColor : this.fillColor : (this.hoveredID.indexOf('_Zoom_') > -1) ? this.selectionColor : this.fillColor;
icon2.setAttribute('fill', iconColor);
}
if(icon3) {
let iconColor: string = this.chart.zoomModule.isPanning ? this.fillColor : (this.hoveredID.indexOf('_Zoom_') > -1) ? this.selectionColor : this.fillColor;
icon3.setAttribute('fill', iconColor);
}
removeElement('EJ2_Chart_ZoomTip');
}
// Toolkit events function calculation here.
/** @private */
public reset(): boolean {
let chart: Chart = this.chart;
if (!chart.zoomModule.isDevice) {
remove(chart.zoomModule.toolkitElements);
}
let argsData: IZoomCompleteEventArgs;
this.removeTooltip();
chart.svgObject.setAttribute('cursor', 'auto');
let zoomingEventArgs: IZoomingEventArgs;
let zoomedAxisCollection: IAxisData[] = [];
this.zoomCompleteEvtCollection = [];
for (let axis of (chart.axisCollections as Axis[])) {
argsData = {
cancel: false, name: zoomComplete, axis: axis, previousZoomFactor: axis.zoomFactor,
previousZoomPosition: axis.zoomPosition, currentZoomFactor: 1, currentZoomPosition: 0,
previousVisibleRange: axis.visibleRange, currentVisibleRange: null
};
axis.zoomFactor = 1;
axis.zoomPosition = 0;
if (axis.zoomingScrollBar) {
axis.zoomingScrollBar.isScrollUI = false;
}
if (!argsData.cancel) {
axis.zoomFactor = argsData.currentZoomFactor;
axis.zoomPosition = argsData.currentZoomPosition;
this.zoomCompleteEvtCollection.push(argsData);
}
zoomedAxisCollection.push({
zoomFactor: axis.zoomFactor, zoomPosition: axis.zoomFactor, axisName: axis.name,
axisRange: axis.visibleRange
});
}
zoomingEventArgs = { cancel: false, axisCollection: zoomedAxisCollection, name: onZooming };
if (!zoomingEventArgs.cancel && this.chart.isBlazor) {
this.chart.trigger(onZooming, zoomingEventArgs, () => {
this.setDefferedZoom(chart)
});
return false;
} else {
return(this.setDefferedZoom(chart))
}
}
private setDefferedZoom(chart: Chart): boolean {
chart.disableTrackTooltip = false;
chart.zoomModule.isZoomed = chart.zoomModule.isPanning = chart.isChartDrag = chart.delayRedraw = false;
chart.zoomModule.touchMoveList = chart.zoomModule.touchStartList = [];
chart.zoomModule.pinchTarget = null;
chart.removeSvg();
if (chart.enableAutoIntervalOnBothAxis) {
chart.processData(false);
}
chart.refreshAxis();
chart.refreshBound();
this.elementOpacity = '1';
return false;
}
private zoomIn(e: PointerEvent): boolean {
this.zoomInOutCalculation(1, this.chart, this.chart.axisCollections, this.chart.zoomSettings.mode);
return false;
}
private zoomOut(e: PointerEvent): boolean {
this.zoomInOutCalculation(-1, this.chart, this.chart.axisCollections, this.chart.zoomSettings.mode);
return false;
}
private zoom(e: PointerEvent): boolean {
this.chart.zoomModule.isPanning = false;
let zoomModule: Zoom = this.chart.zoomModule;
this.elementOpacity = '1';
this.chart.svgObject.setAttribute('cursor', 'auto');
this.zoomInElements.setAttribute('opacity', this.elementOpacity);
this.zoomOutElements.setAttribute('opacity', this.elementOpacity);
this.applySelection(this.zoomElements.childNodes, this.selectionColor);
this.applySelection(this.panElements.childNodes, '#737373');
if(getElement(this.selectedID)) {
getElement(this.selectedID).setAttribute('fill', 'transparent');
}
this.selectedID = this.chart.element.id + '_Zooming_Zoom_1';
getElement(this.selectedID).setAttribute('fill', this.iconRectSelectionFill);
return false;
}
/** @private */
public pan(): boolean {
let element: void;
this.chart.zoomModule.isPanning = true;
this.chart.svgObject.setAttribute('cursor', 'pointer');
this.elementOpacity = '0.2';
element = this.zoomInElements ? this.zoomInElements.setAttribute('opacity', this.elementOpacity) : null;
element = this.zoomOutElements ? this.zoomOutElements.setAttribute('opacity', this.elementOpacity) : null;
element = this.panElements ? this.applySelection(this.panElements.childNodes, this.selectionColor) : null;
element = this.zoomElements ? this.applySelection(this.zoomElements.childNodes, '#737373') : null;
if(getElement(this.selectedID)) {
getElement(this.selectedID).setAttribute('fill', 'transparent');
}
this.selectedID = this.chart.element.id + '_Zooming_Pan_1';
getElement(this.selectedID).setAttribute('fill', this.iconRectSelectionFill);
return false;
}
private zoomInOutCalculation(scale: number, chart: Chart, axes: AxisModel[], mode: ZoomMode): void {
if (!chart.zoomModule.isPanning && this.elementOpacity !== '0.2') {
let zoomFactor: number;
let zoomPosition: number;
let cumulative: number;
chart.disableTrackTooltip = true;
chart.delayRedraw = true;
let argsData: IZoomCompleteEventArgs;
this.zoomCompleteEvtCollection = [];
for (let axis of (axes as Axis[])) {
argsData = {
cancel: false, name: zoomComplete, axis: axis, previousZoomFactor: axis.zoomFactor,
previousZoomPosition: axis.zoomPosition, currentZoomFactor: axis.zoomFactor, currentZoomPosition: axis.zoomPosition,
previousVisibleRange: axis.visibleRange, currentVisibleRange: null
};
if ((axis.orientation === 'Horizontal' && mode !== 'Y') ||
(axis.orientation === 'Vertical' && mode !== 'X')) {
cumulative = Math.max(Math.max(1 / minMax(axis.zoomFactor, 0, 1), 1) + (0.25 * scale), 1);
zoomFactor = (cumulative === 1) ? 1 : minMax(1 / cumulative, 0, 1);
zoomPosition = (cumulative === 1) ? 0 : axis.zoomPosition + ((axis.zoomFactor - zoomFactor) * 0.5);
if (axis.zoomPosition !== zoomPosition || axis.zoomFactor !== zoomFactor) {
zoomFactor = (zoomPosition + zoomFactor) > 1 ? (1 - zoomPosition) : zoomFactor;
}
argsData.currentZoomFactor = zoomFactor;
argsData.currentZoomPosition = zoomPosition;
if (!argsData.cancel) {
axis.zoomFactor = argsData.currentZoomFactor;
axis.zoomPosition = argsData.currentZoomPosition;
this.zoomCompleteEvtCollection.push(argsData);
}
}
}
}
}
private applySelection(elements: NodeList, color: string): void {
for (let i: number = 1, length: number = elements.length; i < length; i++) {
(elements[i] as HTMLElement).setAttribute('fill', color);
}
}
} | the_stack |
import { handler } from "./github.ts";
import {
cleanupDatabase,
createContext,
createJSONWebhookEvent,
} from "../../utils/test_utils.ts";
import { Database } from "../../utils/database.ts";
import { assert, assertEquals } from "../../test_deps.ts";
import { getMeta, s3, uploadMetaJson } from "../../utils/storage.ts";
const database = new Database(Deno.env.get("MONGO_URI")!);
const decoder = new TextDecoder();
const pushevent = JSON.parse(
await Deno.readTextFile("./api/webhook/testdata/pushevent.json"),
);
const pusheventforbidden = JSON.parse(
await Deno.readTextFile(
"./api/webhook/testdata/pusheventforbidden.json",
),
);
const pusheventBranch = JSON.parse(
await Deno.readTextFile(
"./api/webhook/testdata/pushevent_branch.json",
),
);
const pusheventVersionPrefix = JSON.parse(
await Deno.readTextFile(
"./api/webhook/testdata/pushevent_versionprefix.json",
),
);
Deno.test({
name: "push event no name",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/",
pushevent,
{ name: "" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"error":"no module name specified"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
} finally {
await cleanupDatabase(database);
}
},
});
Deno.test({
name: "push event bad name",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest-2",
pushevent,
{ name: "ltest-2" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"error":"module name is not valid"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
// Check that no versions.json file exists
assertEquals(await getMeta("ltest-2", "versions.json"), undefined);
// Check that no builds are queued
assertEquals(await database._builds.find({}), []);
// Check that there is no module entry in the database
assertEquals(await database.getModule("ltest-2"), null);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event forbidden name",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/frisbee",
pusheventforbidden,
{ name: "frisbee" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"error":"found forbidden word in module name"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
// Check that no versions.json file exists
assertEquals(await getMeta("frisbee", "versions.json"), undefined);
// Check that no builds are queued
assertEquals(await database._builds.find({}), []);
// Check that there is no module entry in the database
assertEquals(await database.getModule("frisbee"), null);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event max registered to repository",
async fn() {
try {
await database.saveModule({
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
await database.saveModule({
name: "ltest3",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
await database.saveModule({
name: "ltest4",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Send push event for ltest5
assertEquals(
await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest5",
pushevent,
{ name: "ltest5" },
{},
),
createContext(),
),
{
body:
'{"success":false,"error":"Max number of modules for one repository (3) has been reached. Please contact ry@deno.land if you need more."}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
// Check that no versions.json file exists
assertEquals(await getMeta("ltest5", "versions.json"), undefined);
// Check that there is no module entry in the database
assertEquals(await database.getModule("ltest5"), null);
// Check that builds were queued
assertEquals(await database._builds.find({}), []);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event success",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{},
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that no versions.json file was created
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event not a tag",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pusheventBranch,
{ name: "ltest2" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"info":"created ref is not tag"}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
// Check that no versions.json file exists
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
// Check that no builds are queued
assertEquals(await database._builds.find({}), []);
// Check that there is no module entry in the database
assertEquals(await database.getModule("ltest2"), null);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event version prefix no match",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{ version_prefix: "v" },
),
createContext(),
);
assertEquals(resp, {
body:
'{"success":false,"info":"ignoring event as the version does not match the version prefix"}',
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
// Check that no versions.json file exists
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
// Check that no builds are queued
assertEquals(await database._builds.find({}), []);
// Check that there is no module entry in the database
assertEquals(await database.getModule("ltest2"), null);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event version prefix match",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pusheventVersionPrefix,
{ name: "ltest2" },
{ version_prefix: "v" },
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "v0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that no versions.json file was created
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event subdir invalid",
async fn() {
try {
// Send push event
assertEquals(
await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{ subdir: "asd" },
),
createContext(),
),
{
body:
'{"success":false,"error":"provided sub directory is not valid as it does not end with a /"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
},
);
// Check that no versions.json file exists
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
// Check that no builds are queued
assertEquals(await database._builds.find({}), []);
// Check that there is no module entry in the database
assertEquals(await database.getModule("ltest2"), null);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event subdir success",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{ subdir: "asd/" },
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
subdir: "asd/",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that no versions.json file was created
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event subdir success leading slash",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{ subdir: "/asd/" },
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
subdir: "asd/",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that no versions.json file was created
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event subdir success non normalized",
async fn() {
try {
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{ subdir: "../../asd/../foo/" },
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
subdir: "foo/",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that no versions.json file was created
assertEquals(await getMeta("ltest2", "versions.json"), undefined);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event already exists",
async fn() {
try {
await uploadMetaJson(
"ltest2",
"versions.json",
{ latest: "0.0.7", versions: ["0.0.7"] },
);
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"error":"version already exists"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that versions.json was not changed
assertEquals(
JSON.parse(decoder.decode(await getMeta("ltest2", "versions.json"))),
{ latest: "0.0.7", versions: ["0.0.7"] },
);
// Check that no new build was queued
assertEquals(await database._builds.find({}), []);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event already queued",
async fn() {
try {
await database.createBuild({
options: {
moduleName: "ltest2",
ref: "0.0.7",
repository: "luca-rand/testing",
type: "github",
version: "0.0.7",
},
status: "queued",
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{},
),
createContext(),
);
assertEquals(resp, {
body:
'{"success":false,"error":"this module version is already being published"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
// Check that the database entry was created
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event previously failed",
async fn() {
try {
await database.createBuild({
options: {
moduleName: "ltest2",
ref: "0.0.7",
repository: "luca-rand/testing",
type: "github",
version: "0.0.7",
},
status: "error",
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest2",
pushevent,
{ name: "ltest2" },
{},
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued in addition to the errored build
assertEquals(builds.length, 2);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
},
status: "error",
},
);
assertEquals(
builds[1],
{
_id: builds[1]._id,
created_at: builds[1].created_at,
options: {
moduleName: "ltest2",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest2","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[1]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
// Check that the database entry was created
const ltest2 = await database.getModule("ltest2");
assert(ltest2);
assert(ltest2.created_at <= new Date());
ltest2.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest2, {
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event rename repository",
async fn() {
try {
const repoId = 274939732;
await database.saveModule({
name: "ltest",
description: "testing things",
repo_id: repoId,
owner: "luca-rand",
repo: "testing-oldname",
star_count: 4,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest",
pushevent,
{ name: "ltest" },
{},
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest",
type: "github",
repository: "luca-rand/testing", // <- new name
ref: "0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"ltest","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event rename repository already exists",
async fn() {
try {
await uploadMetaJson(
"ltest",
"versions.json",
{ latest: "0.0.7", versions: ["0.0.7"] },
);
const repoId = 274939732;
await database.saveModule({
name: "ltest",
description: "testing things",
repo_id: repoId,
owner: "luca-rand",
repo: "testing-oldname",
star_count: 4,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest",
pushevent,
{ name: "ltest" },
{},
),
createContext(),
);
assertEquals(resp, {
body: '{"success":false,"error":"version already exists"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
const ltest = await database.getModule("ltest");
assert(ltest);
assert(ltest.created_at <= new Date());
ltest.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest, {
name: "ltest",
type: "github",
repo_id: repoId,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Check that versions.json was not changed
assertEquals(
JSON.parse(decoder.decode(await getMeta("ltest", "versions.json"))),
{ latest: "0.0.7", versions: ["0.0.7"] },
);
// Check that no new build was queued
assertEquals(await database._builds.find({}), []);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event rename repository already queued",
async fn() {
try {
await database.createBuild({
options: {
moduleName: "ltest",
ref: "0.0.7",
repository: "luca-rand/testing",
type: "github",
version: "0.0.7",
},
status: "queued",
});
const repoId = 274939732;
await database.saveModule({
name: "ltest",
description: "testing things",
repo_id: repoId,
owner: "luca-rand",
repo: "testing-oldname",
star_count: 4,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/ltest",
pushevent,
{ name: "ltest" },
{},
),
createContext(),
);
assertEquals(resp, {
body:
'{"success":false,"error":"this module version is already being published"}',
headers: {
"content-type": "application/json",
},
statusCode: 400,
});
// Check that the database entry was created
const ltest = await database.getModule("ltest");
assert(ltest);
assert(ltest.created_at <= new Date());
ltest.created_at = new Date(2020, 1, 1);
// Check that the database entry
assertEquals(ltest, {
name: "ltest",
type: "github",
repo_id: repoId,
owner: "luca-rand",
repo: "testing",
description: "Move along, just for testing",
star_count: 2,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event at max registered to repository",
async fn() {
try {
await database.saveModule({
name: "ltest2",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
await database.saveModule({
name: "ltest3",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
await database.saveModule({
name: "ltest4",
type: "github",
repo_id: 274939732,
owner: "luca-rand",
repo: "testing",
description: "",
star_count: 4,
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
const res = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/lest4",
pushevent,
{ name: "ltest4" },
{},
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "ltest4",
type: "github",
repository: "luca-rand/testing",
ref: "0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
// Send push event for ltest5
assertEquals(
res,
{
body:
`{"success":true,"data":{"module":"ltest4","version":"0.0.7","repository":"luca-rand/testing","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
},
);
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
});
Deno.test({
name: "push event grandfathered forbidden name",
async fn() {
try {
// grandfathered module with a forbidden name
await database.saveModule({
name: "frisbee",
description: "Move along, just for frisbee",
repo_id: 274939732,
owner: "luca-rand",
repo: "frisbee",
star_count: 4,
type: "github",
is_unlisted: false,
created_at: new Date(2020, 1, 1),
});
// Send push event
const resp = await handler(
createJSONWebhookEvent(
"push",
"/webhook/gh/frisbee",
pusheventforbidden,
{ name: "frisbee" },
{},
),
createContext(),
);
const builds = await database._builds.find({});
// Check that a new build was queued
assertEquals(builds.length, 1);
assertEquals(
builds[0],
{
_id: builds[0]._id,
created_at: builds[0].created_at,
options: {
moduleName: "frisbee",
type: "github",
repository: "luca-rand/frisbee",
ref: "0.0.7",
version: "0.0.7",
},
status: "queued",
},
);
assertEquals(resp, {
body:
`{"success":true,"data":{"module":"frisbee","version":"0.0.7","repository":"luca-rand/frisbee","status_url":"https://deno.land/status/${
builds[0]._id.$oid
}"}}`,
headers: {
"content-type": "application/json",
},
statusCode: 200,
});
} finally {
await cleanupDatabase(database);
await s3.empty();
}
},
}); | the_stack |
import { ComponentFactoryResolver, ComponentRef, Injectable, ViewContainerRef } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { finalize, take } from 'rxjs/operators';
import { forkJoin, Observable, Subject } from 'rxjs';
import { Store } from '@ngrx/store';
import * as parseEmail from 'email-addresses';
import { ComposeMailDialogComponent } from '../../mail/mail-sidebar/compose-mail-dialog/compose-mail-dialog.component';
import {
AppState,
ComposeMailState,
Contact,
ContactsState,
Draft,
DraftState,
GlobalPublicKey,
PGP_MIME_DEFAULT_ATTACHMENT_FILE_NAME,
PGPEncryptionType,
PublicKey,
SecureContent,
UserState,
SIGN_MESSAGE_DEFAULT_ATTACHMENT_FILE_NAME,
SignContentType,
} from '../datatypes';
import { ClearDraft, CreateMail, SendMail, SnackPush, UploadAttachment } from '../actions';
import { Attachment } from '../models';
import { MailService } from './mail.service';
import { OpenPgpService } from './openpgp.service';
import { MessageBuilderService } from './message.builder.service';
import { getCryptoRandom, SharedService } from './shared.service';
import { UserSelectManageService } from '../../shared/services/user-select-manage.service';
import { AutocryptProcessService } from './autocrypt.process.service';
@Injectable({
providedIn: 'root',
})
export class ComposeMailService {
private drafts: DraftState;
private composeMailContainer: ViewContainerRef;
public componentRefList: Array<ComponentRef<ComposeMailDialogComponent>> = [];
private userState: UserState;
minimizedWidth = 192;
originWidth = 640;
windowWidth: number;
maxComposeCount = 5;
composesWidth: number;
countCommonCompose: number;
contacts: Contact[] = [];
constructor(
private store: Store<AppState>,
private openPgpService: OpenPgpService,
private mailService: MailService,
private componentFactoryResolver: ComponentFactoryResolver,
private messageBuilderService: MessageBuilderService,
private sharedService: SharedService,
private userSelectManageService: UserSelectManageService,
private autocryptProcessService: AutocryptProcessService,
) {
this.store
.select((state: AppState) => state.composeMail)
.subscribe((response: ComposeMailState) => {
Object.keys(response.drafts).forEach((key: any) => {
const { usersKeys, drafts } = response;
const draftMail: Draft = drafts[key];
if (draftMail.draft) {
const signFlag = this.openPgpService.getMailboxSignFlag(draftMail.draft.mailbox);
const encryptionTypeForExternal = this.getEncryptionTypeForExternal(draftMail, usersKeys);
if (
draftMail.shouldSave &&
this.drafts[key] &&
this.drafts[key].isPGPInProgress &&
!draftMail.isPGPInProgress
) {
if (!(encryptionTypeForExternal === PGPEncryptionType.PGP_INLINE && signFlag)) {
this.setEncryptedContent(draftMail);
}
this.store.dispatch(new CreateMail({ ...draftMail }));
} else if (draftMail.shouldSend && this.drafts[key]) {
if (
(this.drafts[key].isPGPInProgress &&
!draftMail.isPGPInProgress &&
!draftMail.isProcessingAttachments &&
!draftMail.signContent) ||
(this.drafts[key].isProcessingAttachments &&
!draftMail.isPGPInProgress &&
!draftMail.isProcessingAttachments &&
!draftMail.signContent)
) {
// PGP Encryption has been finished, don't need to set encryption data, if it is PGP/MIME message
if (
!draftMail.isPGPMimeMessage &&
!(encryptionTypeForExternal === PGPEncryptionType.PGP_INLINE && signFlag)
) {
this.setEncryptedContent(draftMail);
}
if (!draftMail.isSaving) {
if (draftMail.draft && draftMail.draft.encryption && draftMail.draft.encryption.password) {
draftMail.draft.encryption.password = '';
}
if (encryptionTypeForExternal === PGPEncryptionType.PGP_INLINE && signFlag) {
this.openPgpService.signPGPInlineMessage(
draftMail.draft.mailbox,
new SecureContent(draftMail.draft),
draftMail.id,
);
} else {
if (signFlag) {
draftMail.draft.sign = SignContentType.BUILTIN;
}
this.store.dispatch(new SendMail({ ...draftMail }));
}
} else {
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
);
}
} else if (this.drafts[key].isPGPMimeInProgress && !draftMail.isPGPMimeInProgress) {
// Finished to encrypt PGP/MIME message context
if (draftMail.pgpMimeContent) {
this.processPGPMimeMessage(draftMail);
} else {
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
);
}
} else if (this.drafts[key].getUserKeyInProgress && !draftMail.getUserKeyInProgress) {
// Finished to get the user keys
let publicKeys: any[] = [];
if (this.getShouldBeEncrypted(draftMail, usersKeys)) {
draftMail.draft.is_encrypted = true;
publicKeys = this.getPublicKeys(draftMail, usersKeys).map(item => item.public_key);
}
if (encryptionTypeForExternal !== undefined && publicKeys.length > 0) {
draftMail.draft.is_encrypted = false;
draftMail.draft.is_subject_encrypted = false;
if (encryptionTypeForExternal === PGPEncryptionType.PGP_INLINE) {
draftMail.draft.encryption_type = PGPEncryptionType.PGP_INLINE;
}
}
if (draftMail.draft && draftMail.draft.encryption && draftMail.draft.encryption.password) {
for (const attachment of draftMail.attachments) {
this.openPgpService.encryptAttachmentWithOnlyPassword(
attachment,
draftMail.draft.encryption.password,
);
}
this.openPgpService.encryptWithOnlyPassword(
draftMail.id,
new SecureContent(draftMail.draft),
draftMail.draft.encryption.password,
);
} else if (publicKeys.length > 0) {
if (this.sharedService.checkRecipients(usersKeys, draftMail?.draft?.receiver || [])) {
// If all recipients are in CTemplar, not need to check autocrypt and ...
for (const attachment of draftMail.attachments) {
this.openPgpService.encryptAttachment(draftMail.draft.mailbox, attachment, publicKeys);
}
this.openPgpService.encrypt(
draftMail.draft.mailbox,
draftMail.id,
new SecureContent(draftMail.draft),
publicKeys,
encryptionTypeForExternal,
signFlag,
);
} else {
const determinedAutocryptStatus =
this.autocryptProcessService.decideAutocryptDefaultEncryptionWithDraft(draftMail, usersKeys);
if (determinedAutocryptStatus.encryptTotally) {
this.buildPGPMimeMessageAndEncrypt(draftMail.id, publicKeys);
} else if (determinedAutocryptStatus.senderAutocryptEnabled) {
draftMail.draft.is_encrypted = false;
draftMail.draft.is_subject_encrypted = false;
this.sendEmailWithDecryptedData(false, draftMail, publicKeys, encryptionTypeForExternal);
} else if (encryptionTypeForExternal === PGPEncryptionType.PGP_MIME) {
this.buildPGPMimeMessageAndEncrypt(draftMail.id, publicKeys);
} else {
for (const attachment of draftMail.attachments) {
this.openPgpService.encryptAttachment(draftMail.draft.mailbox, attachment, publicKeys);
}
this.openPgpService.encrypt(
draftMail.draft.mailbox,
draftMail.id,
new SecureContent(draftMail.draft),
publicKeys,
encryptionTypeForExternal,
);
}
}
} else if (!draftMail.isSaving) {
if (signFlag) {
this.openPgpService.signContents(
draftMail.draft.mailbox,
new SecureContent(draftMail.draft),
draftMail.id,
);
} else {
this.sendEmailWithDecryptedData(true, draftMail, publicKeys, encryptionTypeForExternal);
}
} else {
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
);
}
} else if (signFlag && draftMail.signContent) {
if (encryptionTypeForExternal === PGPEncryptionType.PGP_INLINE) {
draftMail.draft.content = draftMail.signContent;
this.store.dispatch(new SendMail({ ...draftMail }));
} else if (
!draftMail.draft.attachments.some(a => a.name === SIGN_MESSAGE_DEFAULT_ATTACHMENT_FILE_NAME)
) {
const attachment = this.processSignContents(draftMail);
draftMail.draft.attachments.push(attachment);
} else if (!draftMail.isProcessingAttachments) {
this.sendEmailWithDecryptedData(true, draftMail, [], undefined);
}
}
}
}
if (draftMail.isClosed && !draftMail.shouldSend && !draftMail.shouldSave && !draftMail.inProgress) {
this.store.dispatch(new ClearDraft(draftMail));
}
});
this.drafts = { ...response.drafts };
});
this.store
.select((state: AppState) => state.user)
.subscribe((user: UserState) => {
this.userState = user;
});
this.store
.select((state: AppState) => state.contacts)
.subscribe((contactsState: ContactsState) => {
this.contacts = contactsState.contacts;
});
}
private getShouldBeEncrypted(draftMail: Draft, usersKeys: Map<string, GlobalPublicKey>): boolean {
if (draftMail.draft) {
const keys = this.getPublicKeys(draftMail, usersKeys);
return keys.every(key => key.public_key);
}
return false;
}
private getPublicKeys(draftMail: Draft, usersKeys: Map<string, GlobalPublicKey>): Array<PublicKey> {
if (draftMail.draft) {
const receivers: string[] = [
...draftMail.draft.receiver.map(receiver => receiver),
...draftMail.draft.cc.map(cc => cc),
...draftMail.draft.bcc.map(bcc => bcc),
];
let keys: any[] = [];
for (const receiver of receivers) {
const parsedEmail = parseEmail.parseOneAddress(receiver) as parseEmail.ParsedMailbox;
if (usersKeys.has(parsedEmail.address)) {
keys = [...keys, ...usersKeys.get(parsedEmail.address).key];
}
}
return keys;
}
return [];
}
private getEncryptionTypeForExternal(draftMail: Draft, usersKeys: Map<string, GlobalPublicKey>): PGPEncryptionType {
if (draftMail.draft && draftMail.draft.receiver) {
let receivers: string[] = [
...draftMail.draft.receiver.map(
receiver => (parseEmail.parseOneAddress(receiver) as parseEmail.ParsedMailbox).address,
),
];
if (draftMail.draft.cc) {
receivers = [
...receivers,
...draftMail.draft.cc.map(cc => (parseEmail.parseOneAddress(cc) as parseEmail.ParsedMailbox).address),
];
}
if (draftMail.draft.bcc) {
receivers = [
...receivers,
...draftMail.draft.bcc.map(bcc => (parseEmail.parseOneAddress(bcc) as parseEmail.ParsedMailbox).address),
];
}
const isPGPInline = receivers.every(rec => {
if (usersKeys.has(rec) && !usersKeys.get(rec).isFetching) {
const contactInfo: Contact = this.contacts.find((contact: Contact) => contact.email === rec);
if (
contactInfo &&
contactInfo.enabled_encryption &&
contactInfo.encryption_type === PGPEncryptionType.PGP_INLINE
) {
return true;
}
}
return false;
});
if (isPGPInline) {
return PGPEncryptionType.PGP_INLINE;
}
const isPGPMime = receivers.every(rec => {
if (usersKeys.has(rec) && !usersKeys.get(rec).isFetching) {
const contactInfo: Contact = this.contacts.find((contact: Contact) => contact.email === rec);
if (
contactInfo &&
contactInfo.enabled_encryption &&
contactInfo.encryption_type === PGPEncryptionType.PGP_MIME
) {
return true;
}
}
return false;
});
if (isPGPMime) {
return PGPEncryptionType.PGP_MIME;
}
return undefined;
}
return undefined;
}
private setEncryptedContent(draftMail: Draft) {
draftMail.draft.content = draftMail.encryptedContent.content;
if (this.userState.settings) {
draftMail.draft.subject = draftMail.encryptedContent.subject;
}
if (draftMail.draft.encryption && draftMail.draft.encryption.password) {
draftMail.draft.is_subject_encrypted = true;
draftMail.draft.is_encrypted = true;
}
}
/**
* Check if there is encrypted attachment,
* If existed, decrypt and upload again attachment and
* Encrypted or decrypted message is sent by `isEncryptMessageContent` flag
* @param isEncryptMessageContent - Decide to encrypt the message content after proceed attachment
* @param draftMail
* @param publicKeys
* @param encryptionTypeForExternal
* @private
*/
private sendEmailWithDecryptedData(
isEncryptMessageContent: boolean,
draftMail: Draft,
publicKeys: any[] = [],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
encryptionTypeForExternal: PGPEncryptionType,
) {
const encryptedAttachments = draftMail.attachments.filter(attachment => !!attachment.is_encrypted);
if (encryptedAttachments.length > 0) {
forkJoin(
...encryptedAttachments.map(attachment => {
attachment.is_encrypted = false;
attachment.document = attachment.decryptedDocument;
return Observable.create((observer: any) => {
this.mailService
.uploadFile(attachment)
.pipe(finalize(() => observer.complete()))
.subscribe(
event => {
if (event instanceof HttpResponse) {
observer.next(event.body);
}
},
error => observer.error(error),
);
});
}),
)
.pipe(take(1))
.subscribe(
() => {
if (!isEncryptMessageContent || publicKeys.length === 0) {
this.store.dispatch(new SendMail({ ...draftMail }));
} else {
this.openPgpService.encrypt(
draftMail.draft.mailbox,
draftMail.id,
new SecureContent(draftMail.draft),
publicKeys,
);
}
},
() =>
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
),
);
} else if (!isEncryptMessageContent || publicKeys.length === 0) {
this.store.dispatch(new SendMail({ ...draftMail }));
} else {
this.openPgpService.encrypt(
draftMail.draft.mailbox,
draftMail.id,
new SecureContent(draftMail.draft),
publicKeys,
);
}
}
private processSignContents(draftMail: Draft) {
const { signContent, id, draft } = draftMail;
const signFile = new File([signContent], SIGN_MESSAGE_DEFAULT_ATTACHMENT_FILE_NAME, {
type: '',
});
const signAttachmentToUpload: Attachment = {
draftId: id,
document: signFile,
decryptedDocument: signFile,
inProgress: false,
is_inline: false,
is_encrypted: false,
message: draft.id,
name: SIGN_MESSAGE_DEFAULT_ATTACHMENT_FILE_NAME,
size: signFile.size.toString(),
actual_size: signFile.size,
attachmentId: performance.now() + Math.floor(getCryptoRandom() * 1000),
};
const email = this.openPgpService.getMailboxEmail(draft.mailbox);
const publicKey = this.openPgpService.getMailboxPublicKey(draft.mailbox);
const publicKeyFileName = `publickey-${email}.asc`;
const publicKeyFile = new File([publicKey], publicKeyFileName, {
type: '',
});
const publicKeyAttachmentToUpload: Attachment = {
draftId: id,
document: publicKeyFile,
decryptedDocument: publicKeyFile,
inProgress: false,
is_inline: false,
is_encrypted: false,
message: draft.id,
name: publicKeyFileName,
size: publicKeyFile.size.toString(),
actual_size: publicKeyFile.size,
attachmentId: performance.now() + Math.floor(getCryptoRandom() * 1000),
};
this.store.dispatch(new UploadAttachment({ ...signAttachmentToUpload }));
this.store.dispatch(new UploadAttachment({ ...publicKeyAttachmentToUpload }));
return signAttachmentToUpload;
}
/**
* Force Making `encrypted.asc` file with `draftMail.encryptedContent`
* @param draftMail
* @private
*/
private processPGPMimeMessage(draftMail: Draft) {
const { pgpMimeContent, id, draft } = draftMail;
const newDocument = new File([pgpMimeContent], PGP_MIME_DEFAULT_ATTACHMENT_FILE_NAME, {
type: '',
});
const attachmentToUpload: Attachment = {
document: newDocument,
draftId: id,
inProgress: false,
is_inline: false,
is_encrypted: false,
message: draft.id,
name: PGP_MIME_DEFAULT_ATTACHMENT_FILE_NAME,
size: newDocument.size.toString(),
actual_size: newDocument.size,
is_pgp_mime: true,
};
this.store.dispatch(new UploadAttachment({ ...attachmentToUpload, isPGPMimeMessage: true }));
}
/**
* Build PGP/MIME message with the standard format
* @param draftMailId
* @param publicKeys
*/
buildPGPMimeMessageAndEncrypt(draftMailId: number, publicKeys: Array<any>) {
const draftMail: Draft = this.drafts[draftMailId];
if (draftMail?.draft?.id) {
this.messageBuilderService
.getMimeData(
new SecureContent(draftMail.draft),
draftMail.attachments,
true,
true,
true,
PGPEncryptionType.PGP_MIME,
)
.then(mimeData => {
if (mimeData) {
this.openPgpService.encryptForPGPMime(mimeData, draftMail.draft.mailbox, draftMail.id, publicKeys);
} else {
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
);
}
})
.catch(() => {
this.store.dispatch(
new SnackPush({
message: 'Failed to send email, please try again. Email has been saved in draft.',
}),
);
});
} else {
setTimeout(() => {
this.buildPGPMimeMessageAndEncrypt(draftMailId, publicKeys);
}, 500);
}
}
initComposeMailContainer(container: ViewContainerRef) {
this.composeMailContainer = container;
this.componentRefList = [];
}
getWindowWidth(width: any = {}) {
// get current window's width
this.windowWidth = width > 768 && width < 999 ? width - 68 : width;
if (this.windowWidth > this.originWidth) {
this.countCommonCompose =
Math.trunc((this.windowWidth - this.originWidth) / this.minimizedWidth) + 1 > this.maxComposeCount
? this.maxComposeCount
: Math.trunc((this.windowWidth - this.originWidth) / this.minimizedWidth) + 1;
} else {
this.countCommonCompose = 0;
}
let composesWidth = 0;
if (this.componentRefList.length > 0) {
// eslint-disable-next-line no-plusplus
for (let index = this.componentRefList.length - 1; index > -1; index--) {
composesWidth += this.componentRefList[index].instance.isMinimized ? this.minimizedWidth : this.originWidth;
if (composesWidth > this.windowWidth) {
if (!this.componentRefList[index].instance.isMinimized) {
this.componentRefList[index].instance.isComposeVisible = true;
this.componentRefList[index + 1].instance.isComposeVisible = false;
} else {
this.componentRefList[index].instance.isComposeVisible = false;
}
break;
} else {
this.componentRefList[index].instance.isComposeVisible = true;
}
}
}
}
getComposesWidth() {
// get entire width of opened Compose windows
let temporaryWidth = 0;
for (const componentReference of this.componentRefList) {
if (componentReference.instance.isComposeVisible) {
temporaryWidth += componentReference.instance.isMinimized ? this.minimizedWidth : this.originWidth;
}
}
this.composesWidth = temporaryWidth;
}
openComposeMailDialog(inputData: any = {}, onHide: Subject<boolean> = new Subject<boolean>()) {
if (this.userState && this.componentRefList.length < this.maxComposeCount) {
for (const componentReference of this.componentRefList) {
componentReference.instance.isMinimized = true;
}
if (inputData.draft) {
const oldComponentReference = this.componentRefList.find(componentReference => {
return (
componentReference.instance.composeMail.draftMail &&
componentReference.instance.composeMail.draftMail.id &&
inputData.draft.id &&
componentReference.instance.composeMail.draftMail.id === inputData.draft.id
);
});
if (oldComponentReference) {
oldComponentReference.instance.isMinimized = false;
return;
}
if (inputData.draft.send) {
return;
}
}
const factory = this.componentFactoryResolver.resolveComponentFactory(ComposeMailDialogComponent);
const newComponentReference: ComponentRef<ComposeMailDialogComponent> =
this.composeMailContainer.createComponent(factory);
this.componentRefList.push(newComponentReference);
for (const key of Object.keys(inputData)) {
(newComponentReference as any).instance[key] = inputData[key];
}
newComponentReference.instance.isComposeVisible = true;
newComponentReference.instance.isMinimized = false;
this.getComposesWidth();
newComponentReference.instance.hide.subscribe(() => {
const index = this.componentRefList.indexOf(newComponentReference);
this.destroyComponent(newComponentReference, index);
if (onHide) {
onHide.next(true);
}
});
newComponentReference.instance.minimize.subscribe((isMinimized: boolean) => {
if (!isMinimized) {
// when Compose window is maximized
for (const componentReference of this.componentRefList) {
componentReference.instance.isMinimized = true;
componentReference.instance.isFullScreen = false;
componentReference.instance.isComposeVisible = true;
}
newComponentReference.instance.isMinimized = false;
if (this.windowWidth < this.minimizedWidth * (this.componentRefList.length - 1) + this.originWidth) {
let temporaryCount = 0;
// eslint-disable-next-line no-plusplus
for (let index = 0; index < this.componentRefList.length; index++) {
if (temporaryCount === this.componentRefList.length - this.countCommonCompose) {
break;
}
if (this.componentRefList[index].instance.isMinimized) {
temporaryCount += 1;
this.componentRefList[index].instance.isComposeVisible = false;
}
}
}
} else {
// when Compose window is minimized
for (const componentReference of this.componentRefList) {
componentReference.instance.isMinimized = true;
componentReference.instance.isComposeVisible = false;
}
let count = Math.trunc(this.windowWidth / this.minimizedWidth);
if (this.componentRefList.length < count) {
count = this.componentRefList.length;
}
// eslint-disable-next-line no-plusplus
for (let index = this.componentRefList.length - 1; index >= this.componentRefList.length - count; index--) {
this.componentRefList[index].instance.isComposeVisible = true;
}
}
});
newComponentReference.instance.fullScreen.subscribe((isFullScreen: boolean) => {
if (isFullScreen) {
for (const componentReference of this.componentRefList) {
componentReference.instance.isFullScreen = false;
componentReference.instance.isMinimized = true;
}
newComponentReference.instance.isFullScreen = true;
}
});
this.userSelectManageService.updateUserSelectPossiblilityState(true);
} else {
// display error message when user open more than 5 composer
this.store.dispatch(new SnackPush({ message: 'Maximum composer reached.', duration: 5000 }));
}
}
destroyAllComposeMailDialogs(): void {
for (const componentReference of this.componentRefList) {
componentReference.destroy();
}
this.componentRefList = [];
}
private destroyComponent(newComponentReference: ComponentRef<ComposeMailDialogComponent>, index: number) {
newComponentReference.destroy();
this.componentRefList.splice(index, 1);
this.getComposesWidth();
let countNewCompose = (this.windowWidth - this.composesWidth) / this.minimizedWidth;
// eslint-disable-next-line no-plusplus
for (let referenceIndex = this.componentRefList.length; referenceIndex > 0; referenceIndex--) {
if (!this.componentRefList[referenceIndex - 1].instance.isComposeVisible && countNewCompose >= 1) {
countNewCompose -= 1;
this.componentRefList[referenceIndex - 1].instance.isComposeVisible = true;
}
}
}
} | the_stack |
class KWinDriver implements IDriverContext {
public static backendName: string = "kwin";
// TODO: split context implementation
//#region implement properties of IDriverContext (except `setTimeout`)
public get backend(): string {
return KWinDriver.backendName;
}
public get currentSurface(): ISurface {
return new KWinSurface(
(workspace.activeClient) ? workspace.activeClient.screen : 0,
workspace.currentActivity,
workspace.currentDesktop,
);
}
public set currentSurface(value: ISurface) {
const ksrf = value as KWinSurface;
/* NOTE: only supports switching desktops */
// TODO: fousing window on other screen?
// TODO: find a way to change activity
if (workspace.currentDesktop !== ksrf.desktop)
workspace.currentDesktop = ksrf.desktop;
}
public get currentWindow(): Window | null {
const client = workspace.activeClient;
return (client) ? this.windowMap.get(client) : null;
}
public set currentWindow(window: Window | null) {
if (window !== null)
workspace.activeClient = (window.window as KWinWindow).client;
}
public get screens(): ISurface[] {
const screens = [];
for (let screen = 0; screen < workspace.numScreens; screen++)
screens.push(new KWinSurface(
screen, workspace.currentActivity, workspace.currentDesktop));
return screens;
}
public get cursorPosition(): [number, number] | null {
return this.mousePoller.mousePosition;
}
//#endregion
private engine: TilingEngine;
private control: TilingController;
private windowMap: WrapperMap<KWin.Client, Window>;
private entered: boolean;
private mousePoller: KWinMousePoller;
constructor() {
this.engine = new TilingEngine();
this.control = new TilingController(this.engine);
this.windowMap = new WrapperMap(
(client: KWin.Client) => KWinWindow.generateID(client),
(client: KWin.Client) => new Window(new KWinWindow(client)),
);
this.entered = false;
this.mousePoller = new KWinMousePoller();
}
/*
* Main
*/
public main() {
CONFIG = KWINCONFIG = new KWinConfig();
debug(() => "Config: " + KWINCONFIG);
this.bindEvents();
this.bindShortcut();
const clients = workspace.clientList();
for (let i = 0; i < clients.length; i++) {
const window = this.windowMap.add(clients[i]);
this.engine.manage(window);
if (window.state !== WindowState.Unmanaged)
this.bindWindowEvents(window, clients[i]);
else
this.windowMap.remove(clients[i]);
}
this.engine.arrange(this);
}
//#region implement methods of IDriverContext`
public setTimeout(func: () => void, timeout: number) {
KWinSetTimeout(() => this.enter(func), timeout);
}
public showNotification(text: string) {
popupDialog.show(text);
}
//#endregion
private bindShortcut() {
if (!KWin.registerShortcut) {
debug(() => "KWin.registerShortcut doesn't exist. Omitting shortcut binding.");
return;
}
const bind = (seq: string, title: string, input: Shortcut) => {
title = "Krohnkite: " + title;
seq = "Meta+" + seq;
KWin.registerShortcut(title, "", seq, () => {
this.enter(() =>
this.control.onShortcut(this, input));
});
};
bind("J", "Down/Next", Shortcut.Down);
bind("K", "Up/Prev" , Shortcut.Up);
bind("H", "Left" , Shortcut.Left);
bind("L", "Right" , Shortcut.Right);
bind("Shift+J", "Move Down/Next", Shortcut.ShiftDown);
bind("Shift+K", "Move Up/Prev" , Shortcut.ShiftUp);
bind("Shift+H", "Move Left" , Shortcut.ShiftLeft);
bind("Shift+L", "Move Right" , Shortcut.ShiftRight);
bind("Ctrl+J", "Grow Height" , Shortcut.GrowHeight);
bind("Ctrl+K", "Shrink Height" , Shortcut.ShrinkHeight);
bind("Ctrl+H", "Shrink Width" , Shortcut.ShrinkWidth);
bind("Ctrl+L", "Grow Width" , Shortcut.GrowWidth);
bind("I", "Increase", Shortcut.Increase);
bind("D", "Decrease", Shortcut.Decrease);
bind("F", "Float", Shortcut.ToggleFloat);
bind("Shift+F", "Float All", Shortcut.ToggleFloatAll);
bind("", "Cycle Layout", Shortcut.NextLayout); // TODO: remove this shortcut
bind("\\", "Next Layout", Shortcut.NextLayout);
bind("|", "Previous Layout", Shortcut.PreviousLayout);
bind("R", "Rotate", Shortcut.Rotate);
bind("Shift+R", "Rotate Part", Shortcut.RotatePart);
bind("Return", "Set master", Shortcut.SetMaster);
const bindLayout = (seq: string, title: string, layoutClass: ILayoutClass) => {
title = "Krohnkite: " + title + " Layout";
seq = (seq !== "") ? "Meta+" + seq : "";
KWin.registerShortcut(title, "", seq, () => {
this.enter(() =>
this.control.onShortcut(this, Shortcut.SetLayout, layoutClass.id));
});
};
bindLayout("T", "Tile", TileLayout);
bindLayout("M", "Monocle", MonocleLayout);
bindLayout("", "Three Column", ThreeColumnLayout);
bindLayout("", "Spread", SpreadLayout);
bindLayout("", "Stair", StairLayout);
bindLayout("", "Floating", FloatingLayout);
bindLayout("", "Quarter", QuarterLayout);
}
//#region Helper functions
/**
* Binds callback to the signal w/ extra fail-safe measures, like re-entry
* prevention and auto-disconnect on termination.
*/
private connect(signal: QSignal, handler: (..._: any[]) => void): (() => void) {
const wrapper = (...args: any[]) => {
/* HACK: `workspace` become undefined when the script is disabled. */
if (typeof workspace === "undefined")
signal.disconnect(wrapper);
else
this.enter(() => handler.apply(this, args));
};
signal.connect(wrapper);
return wrapper;
}
/**
* Run the given function in a protected(?) context to prevent nested event
* handling.
*
* KWin emits signals as soons as window states are changed, even when
* those states are modified by the script. This causes multiple re-entry
* during event handling, resulting in performance degradation and harder
* debugging.
*/
private enter(callback: () => void) {
if (this.entered)
return;
this.entered = true;
try {
callback();
} catch (e) {
debug(() => "Error raised from line " + e.lineNumber);
debug(() => e);
} finally {
this.entered = false;
}
}
//#endregion
private bindEvents() {
this.connect(workspace.numberScreensChanged, (count: number) =>
this.control.onSurfaceUpdate(this, "screens=" + count));
this.connect(workspace.screenResized, (screen: number) => {
const srf = new KWinSurface(
screen, workspace.currentActivity, workspace.currentDesktop);
this.control.onSurfaceUpdate(this, "resized " + srf.toString());
});
this.connect(workspace.currentActivityChanged, (activity: string) =>
this.control.onCurrentSurfaceChanged(this));
this.connect(workspace.currentDesktopChanged, (desktop: number, client: KWin.Client) =>
this.control.onCurrentSurfaceChanged(this));
this.connect(workspace.clientAdded, (client: KWin.Client) => {
/* NOTE: windowShown can be fired in various situations.
* We need only the first one - when window is created. */
let handled = false;
const handler = () => {
if (handled)
return;
handled = true;
const window = this.windowMap.add(client);
this.control.onWindowAdded(this, window);
if (window.state !== WindowState.Unmanaged)
this.bindWindowEvents(window, client);
else
this.windowMap.remove(client);
client.windowShown.disconnect(wrapper);
};
const wrapper = this.connect(client.windowShown, handler);
this.setTimeout(handler, 50);
});
this.connect(workspace.clientRemoved, (client: KWin.Client) => {
const window = this.windowMap.get(client);
if (window) {
this.control.onWindowRemoved(this, window);
this.windowMap.remove(client);
}
});
this.connect(workspace.clientMaximizeSet, (client: KWin.Client, h: boolean, v: boolean) => {
const maximized = (h === true && v === true);
const window = this.windowMap.get(client);
if (window) {
(window.window as KWinWindow).maximized = maximized;
this.control.onWindowMaximizeChanged(this, window, maximized);
}
});
this.connect(workspace.clientFullScreenSet, (client: KWin.Client, fullScreen: boolean, user: boolean) =>
this.control.onWindowChanged(this, this.windowMap.get(client),
"fullscreen=" + fullScreen + " user=" + user));
this.connect(workspace.clientMinimized, (client: KWin.Client) => {
if (KWINCONFIG.preventMinimize) {
client.minimized = false;
workspace.activeClient = client;
} else
this.control.onWindowChanged(this, this.windowMap.get(client), "minimized");
});
this.connect(workspace.clientUnminimized, (client: KWin.Client) =>
this.control.onWindowChanged(this, this.windowMap.get(client), "unminimized"));
// TODO: options.configChanged.connect(this.onConfigChanged);
/* NOTE: How disappointing. This doesn't work at all. Even an official kwin script tries this.
* https://github.com/KDE/kwin/blob/master/scripts/minimizeall/contents/code/main.js */
}
private bindWindowEvents(window: Window, client: KWin.Client) {
let moving = false;
let resizing = false;
this.connect(client.moveResizedChanged, () => {
debugObj(() => ["moveResizedChanged", {window, move: client.move, resize: client.resize}]);
if (moving !== client.move) {
moving = client.move;
if (moving) {
this.mousePoller.start();
this.control.onWindowMoveStart(window);
} else {
this.control.onWindowMoveOver(this, window);
this.mousePoller.stop();
}
}
if (resizing !== client.resize) {
resizing = client.resize;
if (resizing)
this.control.onWindowResizeStart(window);
else
this.control.onWindowResizeOver(this, window);
}
});
this.connect(client.geometryChanged, () => {
if (moving)
this.control.onWindowMove(window);
else if (resizing)
this.control.onWindowResize(this, window);
else {
if (!window.actualGeometry.equals(window.geometry))
this.control.onWindowGeometryChanged(this, window);
}
});
this.connect(client.activeChanged, () => {
if (client.active)
this.control.onWindowFocused(this, window);
});
this.connect(client.screenChanged, () =>
this.control.onWindowChanged(this, window, "screen=" + client.screen));
this.connect(client.activitiesChanged, () =>
this.control.onWindowChanged(this, window, "activity=" + client.activities.join(",")));
this.connect(client.desktopChanged, () =>
this.control.onWindowChanged(this, window, "desktop=" + client.desktop));
}
// TODO: private onConfigChanged = () => {
// this.loadConfig();
// this.engine.arrange();
// }
/* NOTE: check `bindEvents` for details */
} | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="de_DE">
<context>
<name>MlockMainWindow</name>
<message>
<location filename="mlockmainwindow.ui" line="17"/>
<source>MikroLock</source>
<oldsource>µlock</oldsource>
<translation>MikroLock</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="46"/>
<source>Your mail address:</source>
<translation>E-Posta Adresiniz:</translation>
</message>
<message>
<source>To remain compatible with the Chrome miniLock extension, enter a valid mail address.</source>
<translation type="vanished">Chrome miniLock uzantısıyla uyumlu kalabilmek için geçerli bir posta adresi girin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="126"/>
<source>Your secret passphrase:</source>
<translation>Parolanız:</translation>
</message>
<message>
<source>Enter a secret passphrase which consists of several random words.</source>
<translation type="vanished">Birkaç rastgele kelime içeren gizli bir parola girin.</translation>
</message>
<message>
<source><html><head/><body><p>Enter a secret passphrase which consists of several random words. A weak passphrase may be declined by the original miniLock Chrome extension.</p></body></html></source>
<translation type="vanished"><html><head/><body><p>Birkaç rastgele kelime içeren gizli bir parola girin. Orijinal miniLock Chrome uzantısı zayıf bir parola reddedebilir.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="278"/>
<source>Press this button to get to the file processing screen.</source>
<translation>Dosya işleme ekranına gitmek için bu düğmeye basın.</translation>
</message>
<message>
<source>Generate my miniLock ID</source>
<translation type="vanished">MiniLock kimliğimi oluştur</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="327"/>
<source>Enter your mail address and your passphrase.</source>
<translation>Posta adresinizi ve parolanızı girin.</translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:8pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">mlock uses your email and passphrase to derive your <span style=" font-weight:600;">miniLock ID</span>.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Refer to <a href="http://world.std.com/~reinhold/diceware.html"><span style=" text-decoration: underline; color:#0000ff;">Diceware</span></a> for a method to generate good passphrases.</p></body></html></source>
<translation type="vanished"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:8pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">mlock berechnet Deine <span style=" font-weight:600;">miniLock ID</span> aus der Mail-Adresse und dem Passwort.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Mit der <a href="http://world.std.com/~reinhold/diceware.html"><span style=" text-decoration: underline; color:#0000ff;">Diceware</span></a> Methode kannst Du gute Passwörter erzeugen.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="55"/>
<source><html><head/><body><p>Enter your mail address (or any other value) as salt.</p></body></html></source>
<oldsource><html><head/><body><p>To remain compatible with the Chrome miniLock extension, enter a valid mail address (you may enter anything as salt value).</p></body></html></oldsource>
<translation>Posta adresinizi (veya başka bir değeri) girin</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="135"/>
<source><html><head/><body><p>Enter a secret passphrase (minimum length: 20 characters). If the length does not exceed 40 characters, the passphrase must consist of at least five random words.</p></body></html></source>
<oldsource><html><head/><body><p>Enter a secret passphrase (minimum length: 20 characters). If the length does not exceed 40 characters, the passphrase must consist of at least five random words. A weak passphrase may be declined by the original miniLock Chrome extension.</p></body></html></oldsource>
<translation><html><head/><body><p>Gizli bir parola girin (minimum uzunluk: 20 karakter). Uzunluğu 40 karakteri aşmıyorsa, parolanın en az beş rastgele kelime içermesi gerekir.</p></body></html></translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:8pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">MikroLock uses your email and passphrase to derive your <span style=" font-weight:600;">miniLock ID</span>.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Refer to <a href="http://www.diceware.com"><span style=" text-decoration: underline; color:#0000ff;">Diceware.com</span></a> for a method to generate good passphrases.</p></body></html></source>
<oldsource><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:8pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">µlock uses your email and passphrase to derive your <span style=" font-weight:600;">miniLock ID</span>.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Refer to <a href="http://www.diceware.com"><span style=" text-decoration: underline; color:#0000ff;">Diceware.com</span></a> for a method to generate good passphrases.</p></body></html></oldsource>
<translation type="vanished"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:8pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">MikroLock nutzt die Mail-Adresse und das Passwort, um eine <span style=" font-weight:600;">miniLock ID</span> zu berechnen.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Sieh unter <a href="http://www.diceware.com"><span style=" text-decoration: underline; color:#0000ff;">Diceware.com</span></a> nach, wie man gute Passwörter erzeugen kann.</p></body></html></translation>
</message>
<message>
<source>Send your miniLock ID to others so they can encrypt files to you.<br>Encrypt files to friends using their miniLock IDs. <br><br>Your email is only used to derive your miniLock ID -<br> it remains completely secret and anonymous.</source>
<translation type="vanished">MiniLock kimliğinizi başkalarına gönderin, böylece size dosyaları şifreleyebilirler.<br><br>MiniLock Kimlikleri ile dosyaları şifreleyin.<br><br>E-posta adresiniz yalnızca MiniLock Kimliğinizi oluşturmak için kullanılacaktır - gizli ve anonim kalacaktır.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="424"/>
<source>Select the directory to store the encrypted or decrypted file.</source>
<translation>Şifreli veya şifresi çözülmüş dosyayı saklamak için dizini seçin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="427"/>
<source>Select the destination directory</source>
<translation>Hedef dizini seçin</translation>
</message>
<message>
<source>Enter the directory to store the encrypted or decrypted file.</source>
<translation type="vanished">Gib das Ausgabeverzeichnis ein.</translation>
</message>
<message>
<source><html><head/><body><p>This is your destination directory.</p></body></html></source>
<translation type="vanished"><html><head/><body><p>Dies ist das Ausgabeverzeichnis.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="473"/>
<source>Select a minilock file to decrypt or any other file to encrypt.</source>
<translation>Şifresini çözmek için bir minilock dosyası veya şifrelemek için başka bir dosya seçin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="476"/>
<location filename="mlockmainwindow.cpp" line="383"/>
<source>Select the input file</source>
<translation>Girdi dosyasını seçin</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="549"/>
<source>Drop a file here after selecting the destination directory.</source>
<translation>Hedef dizini seçtikten sonra buraya bir dosya bırakın.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="617"/>
<source><html><head/><body><p><span style=" font-weight:600;">Select the destination directory and the input file.</span></p><p>A miniLock file will be decrypted automatically. </p><p>Any other file will be encrypted.</p><p>You may drag and drop a file onto this window.</p></body></html></source>
<oldsource><html><head/><body><p><span style=" font-weight:600;">Select the destination directory and the input file.</span></p><p>A miniLock file will be decrypted automatically. </p><p>Any other file will be encrypted.</p><p>You may drag and drop files onto this window.</p></body></html></oldsource>
<translation><html><head/><body><p><span style=" font-weight:600;">Hedef dizini ve girdi dosyasını seçin.</span></p><p>MiniLock dosyası otomatik olarak şifresiz çözülür. </p><p>Başka herhangi bir dosya şifrelenir.</p><p>Dosyayı bu pencereye sürükleyip bırakabilirsiniz.</p></body></html></translation>
</message>
<message>
<source>List of recipient miniLock IDs:</source>
<translation type="vanished">Liste der Empfänger-IDs:</translation>
</message>
<message>
<source>Add a miniLock ID of whom should be able to open the file.</source>
<translation type="vanished">Füge eine ID der Person hinzu, die deine miniLock-Datei öffnen darf.</translation>
</message>
<message>
<source>Add miniLock ID</source>
<translation type="vanished">MiniLock-ID hinzufügen</translation>
</message>
<message>
<source><html><head/><body><p>Open a text file which contains one miniLock ID per line and use the entries to replace the recipient IDs above.</p></body></html></source>
<translation type="vanished"><html><head/><body><p>Öffne eine Textdatei, die eine miniLock-ID pro Zeile enthält, und ersetze damit die obigen Empfänger-IDs.</p></body></html></translation>
</message>
<message>
<source>Read list file</source>
<translation type="vanished">Liste einlesen</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="200"/>
<source>Select a function to calculate a key from the input fields above. Always use the same function to generate your Lock-ID.</source>
<translation>Yukarıdaki girdi alanlarından bir anahtarı hesaplamak için bir işlev seçin. Kilit Kimliği'nizi oluşturmak için daima aynı işlevi kullanın.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="203"/>
<source>Key derivation function</source>
<translation>Anahtar Türetme Fonksiyonu</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="209"/>
<source>Select scrypt as key derivation function.</source>
<translation>Anahtar türetme işlevi olarak kriptolama'yı seçin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="212"/>
<source>s&crypt</source>
<translation>scrypt</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="222"/>
<source>Use Argon2 as key derivation function.</source>
<translation>Anahtar türetme işlevi olarak Argon2'yi kullanın.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="225"/>
<source>Argon&2</source>
<translation>Argon2</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="281"/>
<source>Generate my Lock-ID</source>
<translation>Kilit Kimliği'ni oluştur</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="353"/>
<source><html><head/><body><p>MikroLock uses your email and passphrase to derive your <span style=" font-weight:600;">Lock-ID</span>.</p>
<p>Refer to <a href="http://www.diceware.com"><span style=" text-decoration: underline; color:#0000ff;">Diceware.com</span></a> for a method to generate good passphrases.</p></body></html></source>
<translation><html><head/><body><p>MikroLock, türetmek için e-postanızı ve parolanızı kullanır.<span style="font-weight:600;">Lock-ID</span> hesapla.</p>
<p>Ziyaret edin <a href="http://www.diceware.com"><span style=" text-decoration: underline; color:#0000ff;">Diceware.com</span></a> iyi bir parola deyimi üretmek için. </p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="390"/>
<source><html><head/><body><p>Send your Lock-ID to others so they can encrypt files to you.<br/>Encrypt files to friends using their Lock-IDs. <br/><br/>Your email is only used to derive your Lock ID - it remains completely secret and anonymous.</p></body></html></source>
<translation><html><head/><body><p>Send your Lock-ID to others so they can encrypt files to you.<br/>Encrypt files to friends using their Lock-IDs. <br/><br/>Your email is only used to derive your Lock ID - it remains completely secret and anonymous.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="444"/>
<source>This is your destination directory.</source>
<translation>Bu hedef dizininiz.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="648"/>
<source>List of recipient Lock-IDs:</source>
<translation>Alıcı Kilit Kimlikleri Listesi:</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="678"/>
<source>Add a Lock-ID of whom should be able to open the file.</source>
<translation>Dosyayı açabilecek durumda olan bir Lock-ID ekleyin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="681"/>
<source>Add Lock-ID</source>
<translation>Kilit Kimliği Ekle</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="700"/>
<source><html><head/><body><p>Open a text file which contains one Lock-ID per line and use the entries to replace the recipient IDs above.</p></body></html></source>
<translation><html><head/><body><p>Her hat için bir Lock-ID içeren bir metin dosyasını açın ve yukarıdaki alıcı kimliklerini değiştirmek için girdileri kullanın.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="703"/>
<source>Read list of IDs</source>
<translation>Kimliklerin listesini okuyun</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="714"/>
<source>Clear the recipient list.</source>
<translation>Alıcı listesini temizle.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="717"/>
<source>Clear recipients</source>
<translation>Alıcıları temizle</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="730"/>
<source>Omit my ID</source>
<translation>Kimliğimi atla</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="737"/>
<source>Generate a random output filename</source>
<translation>Rastgele bir çıktı dosyası oluştur</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="766"/>
<source>Encrypt the file</source>
<translation>Dosyayı şifreleme</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="800"/>
<source><html><head/><body><p><span style=" font-weight:600;">Encrypt your file!</span></p><p>Add the Lock-ID of each person which should be able to decrypt the file.</p><p>If you omit your own ID, you will not be able to decrypt the resulting file.</p><p>A miniLock file does not give visible hints about the sender nor the recipients.</p></body></html></source>
<translation><html><head/><body><p><span style=" font-weight:600;">Dosyanızı şifreleyin!</span></p><p>Dosyanın şifresini çözebilecek her kişinin Kilit Kimliği'ni ekleyin.</p><p>Kendi kimliğinizi atlarsanız, elde edilen dosyanın şifresini çözemezsiniz.</p><p>Bir miniLock dosyası, gönderen veya alıcılar hakkında görünür ipuçları vermez.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="853"/>
<source>Move to the previous screen.</source>
<translation>Bir önceki ekrana geçin.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="880"/>
<source>This is your Lock-ID.</source>
<translation>Bu senin Lock-ID.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="883"/>
<source><My Lock-ID></source>
<translation><Kilit Kimliğim></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="893"/>
<source>Copy your Lock-ID to the clipboard.</source>
<translation>Lock-ID'nizi panoya kopyalayın.</translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Encrypt your file!</span></p><p>Add the miniLock ID of each person which should be able to decrypt the file.</p><p>If you omit your own ID, you will not be able to decrypt the resulting file.</p><p>A miniLock file does not give visible hints about the sender nor the recipients.</p></body></html></source>
<oldsource><html><head/><body><p><span style=" font-weight:600;">Encrypt your file!</span></p><p>Add the miniLock ID of each person which should be able to decrypt the file.</p><p>You can add up to 128 recipient IDs.</p><p>If you omit your own ID, you will not be able to decrypt the resulting file.</p><p>A miniLock file does not give visible hints about the sender nor the recipients.</p></body></html></oldsource>
<translation type="vanished"><html><head/><body><p><span style=" font-weight:600;">Verschlüssele deine Datei!</span></p><p>Füge die miniLock-ID jeder Person hinzu, die die Datei öffnen soll.</p><p>Wenn Du Deine ID auslässt, kannst du die verschlüsselte Datei nicht öffnen.</p><p>Eine miniLock-Datei enthält keine sichtbaren Hinweise auf Sender oder Empfänger.</p></body></html></translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="1007"/>
<source>&Translation hints</source>
<translation>Tercüme ipuçları</translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Encrypt your file!</span></p><p>Add the miniLock ID of each person which should be able to decrypt the file.</p><p>You can add up to 50 recipient IDs.</p><p>If you omit your own ID, you will not be able to decrypt the resulting file.</p></body></html></source>
<translation type="vanished"><html><head/><body><p><span style=" font-weight:600;">Datei verschlüsseln!</span></p><p>Füge die miniLock-ID jeder Person hinzu, welche die Datei entschlüsseln darf.</p><p>Du kannst bis zu 50 Empfänger-IDs angeben.</p><p>Wenn Du deine eigene ID auslässt, kannst du die verschlüsselte Datei nicht mehr öffnen.</p></body></html></translation>
</message>
<message>
<source>Move to the previous screen</source>
<translation type="vanished">Zum vorherigen Dialog wechseln</translation>
</message>
<message>
<source>This is your miniLock ID</source>
<translation type="vanished">Dies ist Deine miniLock ID</translation>
</message>
<message>
<source><My miniLock ID></source>
<translation type="vanished"><Meine MiniLock ID></translation>
</message>
<message>
<source>Copy your miniLock ID to the clipboard</source>
<translation type="vanished">Kopiere Deine MiniLock ID in die Zwischenablage</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="958"/>
<source>Browse the destination directory.</source>
<translation>Hedef dizine göz atın.</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="985"/>
<source>He&lp</source>
<translation>&Yardım</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="997"/>
<source>&About MikroLock</source>
<oldsource>&About µlock</oldsource>
<translation>&MikroLock Hakkında</translation>
</message>
<message>
<location filename="mlockmainwindow.ui" line="1002"/>
<source>&Manual</source>
<translation>&Hakkında</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="89"/>
<location filename="mlockmainwindow.cpp" line="421"/>
<location filename="mlockmainwindow.cpp" line="560"/>
<source>Input file %1</source>
<translation>%1 giriş dosyası</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="99"/>
<source>The passphrase is too short (minimum: 20 characters).</source>
<translation>Parolanız çok kısa (minimum: 20 karakter).</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="105"/>
<source>The passphrase is strong.</source>
<translation>Parola güçlüdür.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="112"/>
<source>The passphrase must consist of at least five random words. It may be declined by the original miniLock Chrome extension.</source>
<translation>Parolanın en az beş rasgele sözcükten oluşması gerekir. Orijinal miniLock Chrome uzantısı tarafından reddedilebilir.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="133"/>
<source>You do not need to enter an email address here unless you intend to use the Chrome miniLock extension.</source>
<translation>Chrome miniLock uzantısını kullanmayacaksanız burada bir e-posta adresi girmeniz gerekmez.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="180"/>
<source>Scrypt error</source>
<translation>Scrypt hatası</translation>
</message>
<message>
<source>You do not need to enter an email address here unless you want to use the Chrome miniLock extension.</source>
<translation type="vanished">Du musst hier keine Mail-Adresse angeben, wenn du nicht auch das Chrome miniLock-Plugin benutzen willst.</translation>
</message>
<message>
<source>Invalid argument</source>
<translation type="vanished">Ungültiges Argument</translation>
</message>
<message>
<source>%1 is not a minilock file.</source>
<translation type="vanished">%1 ist keine minilock-Datei.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="136"/>
<source>This mail address appears to be valid.</source>
<translation>Bu posta adresi geçerli gibi görünüyor.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="139"/>
<source>This mail address appears to be invalid.</source>
<translation>Bu posta adresi geçersiz görünüyor.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="180"/>
<source>Key derivation failed</source>
<translation>Anahtar türetme başarısız oldu</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="180"/>
<source>Argon2 error</source>
<translation>Argon2 hatası</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="207"/>
<source>%1 file %2...</source>
<translation>%1 dosya %2...</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="209"/>
<source>Decrypting</source>
<translation>Şifresini Çözme</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="209"/>
<source>Encrypting</source>
<translation>Şifreleme</translation>
</message>
<message>
<source>Bad miniLock ID</source>
<translation type="vanished">Ungültige MiniLock ID</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="256"/>
<source>The ID %1 is invalid.</source>
<translation>%1 kimliği geçersiz.</translation>
</message>
<message>
<source>No recipients</source>
<translation type="vanished">Keine Empfänger</translation>
</message>
<message>
<source>You need to define some recipient IDs.</source>
<translation type="vanished">Du musst einige Empfänger IDs angeben.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="256"/>
<source>Bad Lock-ID</source>
<translation>Kötü Kilit-Kimliği</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="284"/>
<source>%1 file %2 in %3s</source>
<translation>Dosya %2, %3 %1</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="286"/>
<source>Decrypted</source>
<translation>Şifrelenmiş</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="286"/>
<source>Encrypted</source>
<translation>Şifre çözülmüş</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="299"/>
<location filename="mlockmainwindow.cpp" line="303"/>
<location filename="mlockmainwindow.cpp" line="307"/>
<location filename="mlockmainwindow.cpp" line="311"/>
<location filename="mlockmainwindow.cpp" line="315"/>
<location filename="mlockmainwindow.cpp" line="319"/>
<location filename="mlockmainwindow.cpp" line="323"/>
<location filename="mlockmainwindow.cpp" line="327"/>
<location filename="mlockmainwindow.cpp" line="331"/>
<location filename="mlockmainwindow.cpp" line="335"/>
<location filename="mlockmainwindow.cpp" line="339"/>
<location filename="mlockmainwindow.cpp" line="343"/>
<location filename="mlockmainwindow.cpp" line="348"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="299"/>
<source>Unknown error.</source>
<translation>Bilinmeyen hata </translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="303"/>
<source>Could not decrypt the file.</source>
<translation>Dosya şifresi çözülemedi.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="307"/>
<source>Could not encrypt the file.</source>
<translation>Dosya şifrelenemedi.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="311"/>
<source>Could not open the file.</source>
<translation>Dosya açılamadı.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="315"/>
<source>Could not read the file.</source>
<translation>Dosya okunamadı.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="319"/>
<source>Could not write the file.</source>
<translation>Dosya yazılamadı.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="323"/>
<source>Could not calculate the hash of the file.</source>
<translation>Dosyanın karmasını hesaplayamadı.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="327"/>
<source>Illegal minilock file format.</source>
<translation>Yasadışı minilock dosya biçimi.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="331"/>
<source>No recipients defined.</source>
<translation>Hiç alıcı tanımlanmadı.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="335"/>
<source>You are not allowed to decrypt the file.</source>
<translation>Dosyanın şifresini çözmenize izin verilmiyor.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="339"/>
<source>Empty input file.</source>
<translation>Boş giriş dosyası.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="343"/>
<source>Output file exists:
%1</source>
<translation>Çıktı dosyası var:
%1</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="348"/>
<source>Undefined error.</source>
<translation>Tanımsız hata.</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="374"/>
<source>Select destination directory</source>
<translation>Hedef dizini seçin</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="393"/>
<source>Process given file</source>
<translation>Verilen dosyayı işleme</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="394"/>
<source>%1 %2
into %3 ?</source>
<translation>%1 %2
in %3 ?</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="395"/>
<source>Decrypt</source>
<translation>Decrypt</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="396"/>
<source>Encrypt</source>
<translation>Encrypt</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="464"/>
<source>About providing translations</source>
<translation>Çeviriler sağlama hakkında</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="465"/>
<source>This GUI was developed using the Qt toolkit, and translations may be provided using the tools Qt Linguist and lrelease.
The ts files for Linguist reside in the src/gui/qt-widgets subdirectory.
The qm file generated by lrelease has to be saved in l10n.
Please send a note to as (at) andre-simon (dot) de if you have issues while translating or if you have finished or updated a translation.</source>
<translation>Bu GUI Qt araç setini kullanarak geliştirildi ve çeviriler Qt Linguist ve lrelease araçlarını kullanarak sağlanabilir.
Dilbilimcinin ts dosyaları src / gui / qt-widgets alt dizininde bulunur.
Lrelease tarafından üretilen qm dosyası l10n'ye kaydedilmelidir.
Çeviri yaparken ya da bir çeviriyi tamamladığınızda veya güncellediğinizde lütfen sorun yaşarsanız, bir (as) andre-simon (nokta) de adresine bir not gönderin.</translation>
</message>
<message>
<source>Decrypt given file</source>
<translation type="vanished">Entschlüssele angegebene Datei</translation>
</message>
<message>
<source>Decrypt %1
into %2 ?</source>
<translation type="vanished">%1 in
%2
entschlüsseln?</translation>
</message>
<message>
<source>Decrypt %1?</source>
<translation type="vanished">%1 entschlüsseln?</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="497"/>
<source>Select the recipient list file</source>
<translation>Alıcı listesi dosyasını seçin</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="555"/>
<source>Enter your mail adress and passphrase</source>
<translation>E-posta adresinizi ve parolanızı girin</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="567"/>
<source>Set input and output parameters</source>
<translation>Giriş ve çıkış parametrelerini ayarla</translation>
</message>
<message>
<location filename="mlockmainwindow.cpp" line="572"/>
<source>Set encryption options for %1</source>
<translation>%1 için şifreleme seçeneklerini ayarla</translation>
</message>
</context>
<context>
<name>ShowManualDialog</name>
<message>
<location filename="showmanualdialog.ui" line="14"/>
<source>MikroLock manual</source>
<oldsource>mlock manual</oldsource>
<translation>MikroLock manual</translation>
</message>
</context>
</TS> | the_stack |
import Delaunay from './delaunay';
const epsilon = 1e-6;
class Polygon {
_: any[];
constructor() {
this._ = [];
}
moveTo(x: any, y: any) {
this._.push([x, y]);
}
closePath() {
this._.push(this._[0].slice());
}
lineTo(x: any, y: any) {
this._.push([x, y]);
}
value() {
return this._.length ? this._ : null;
}
}
export class Voronoi {
delaunay: any;
_circumcenters: Float64Array;
vectors: Float64Array;
xmax: number;
xmin: number;
ymax: number;
ymin: number;
circumcenters: any;
constructor(delaunay: Delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {
if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error("invalid bounds");
this.delaunay = delaunay;
this._circumcenters = new Float64Array(delaunay.points.length);
this.vectors = new Float64Array(delaunay.points.length);
this.xmax = xmax, this.xmin = xmin;
this.ymax = ymax, this.ymin = ymin;
this._init();
}
update() {
this.delaunay.update();
this._init();
return this;
}
_init() {
const { delaunay: { points, hull, triangles }, vectors } = this;
// Compute circumcenters.
const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
for (let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2) {
const t1 = triangles[i] * 2;
const t2 = triangles[i + 1] * 2;
const t3 = triangles[i + 2] * 2;
const x1 = points[t1];
const y1 = points[t1 + 1];
const x2 = points[t2];
const y2 = points[t2 + 1];
const x3 = points[t3];
const y3 = points[t3 + 1];
const dx = x2 - x1;
const dy = y2 - y1;
const ex = x3 - x1;
const ey = y3 - y1;
const bl = dx * dx + dy * dy;
const cl = ex * ex + ey * ey;
const ab = (dx * ey - dy * ex) * 2;
if (!ab) {
// degenerate case (collinear diagram)
x = (x1 + x3) / 2 - 1e8 * ey;
y = (y1 + y3) / 2 + 1e8 * ex;
}
else if (Math.abs(ab) < 1e-8) {
// almost equal points (degenerate triangle)
x = (x1 + x3) / 2;
y = (y1 + y3) / 2;
} else {
const d = 1 / ab;
x = x1 + (ey * bl - dy * cl) * d;
y = y1 + (dx * cl - ex * bl) * d;
}
circumcenters[j] = x;
circumcenters[j + 1] = y;
}
// Compute exterior cell rays.
let h = hull[hull.length - 1];
let p0, p1 = h * 4;
let x0, x1 = points[2 * h];
let y0, y1 = points[2 * h + 1];
vectors.fill(0);
for (let i = 0; i < hull.length; ++i) {
h = hull[i];
p0 = p1, x0 = x1, y0 = y1;
p1 = h * 4, x1 = points[2 * h], y1 = points[2 * h + 1];
vectors[p0 + 2] = vectors[p1] = y0 - y1;
vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;
}
}
*cellPolygons() {
const { delaunay: { points } } = this;
for (let i = 0, n = points.length / 2; i < n; ++i) {
const cell: any = this.cellPolygon(i);
if (cell) cell.index = i, yield cell;
}
}
cellPolygon(i: number) {
const polygon = new Polygon;
return polygon.value();
}
_renderSegment(x0: any, y0: any, x1: any, y1: any, context: { moveTo: (arg0: any, arg1: any) => void; lineTo: (arg0: any, arg1: any) => void; }) {
let S;
const c0 = this._regioncode(x0, y0);
const c1 = this._regioncode(x1, y1);
if (c0 === 0 && c1 === 0) {
context.moveTo(x0, y0);
context.lineTo(x1, y1);
} else if (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) {
context.moveTo(S[0], S[1]);
context.lineTo(S[2], S[3]);
}
}
contains(i: any, x: number | any, y: number | any) {
if ((x = +x, x !== x) || (y = +y, y !== y)) return false;
return this.delaunay._step(i, x, y) === i;
}
*neighbors(i: any) {
const ci = this._clip(i);
if (ci) for (const j of this.delaunay.neighbors(i)) {
const cj = this._clip(j);
// find the common edge
if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {
for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {
if (ci[ai] == cj[aj]
&& ci[ai + 1] == cj[aj + 1]
&& ci[(ai + 2) % li] == cj[(aj + lj - 2) % lj]
&& ci[(ai + 3) % li] == cj[(aj + lj - 1) % lj]
) {
yield j;
break loop;
}
}
}
}
}
_cell(i: string | number) {
const { circumcenters, delaunay: { inedges, halfedges, triangles } } = this;
const e0 = inedges[i];
if (e0 === -1) return null; // coincident point
const points = [];
let e = e0;
do {
const t = Math.floor(e / 3);
points.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);
e = e % 3 === 2 ? e - 2 : e + 1;
if (triangles[e] !== i) break; // bad triangulation
e = halfedges[e];
} while (e !== e0 && e !== -1);
return points;
}
_clip(i: number) {
// degenerate case (1 valid point: return the box)
if (i === 0 && this.delaunay.hull.length === 1) {
return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
}
const points = this._cell(i);
if (points === null) return null;
const { vectors: V } = this;
const v = i * 4;
return V[v] || V[v + 1]
? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3])
: this._clipFinite(i, points);
}
_clipFinite(i: any, points: string | any[]) {
const n = points.length;
let P: any = null;
let x0, y0, x1 = points[n - 2], y1 = points[n - 1];
let c0, c1 = this._regioncode(x1, y1);
let e0, e1;
for (let j = 0; j < n; j += 2) {
x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1];
c0 = c1, c1 = this._regioncode(x1, y1);
if (c0 === 0 && c1 === 0) {
e0 = e1, e1 = 0;
if (P) P.push(x1, y1);
else P = [x1, y1];
} else {
let S, sx0, sy0, sx1, sy1;
if (c0 === 0) {
if ((S = this._clipSegment(x0, y0, x1, y1, c0, c1)) === null) continue;
[sx0, sy0, sx1, sy1] = S;
} else {
if ((S = this._clipSegment(x1, y1, x0, y0, c1, c0)) === null) continue;
[sx1, sy1, sx0, sy0] = S;
e0 = e1, e1 = this._edgecode(sx0, sy0);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
if (P) P.push(sx0, sy0);
else P = [sx0, sy0];
}
e0 = e1, e1 = this._edgecode(sx1, sy1);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
if (P) P.push(sx1, sy1);
else P = [sx1, sy1];
}
}
if (P) {
e0 = e1, e1 = this._edgecode(P[0], P[1]);
if (e0 && e1) this._edge(i, e0, e1, P, P.length);
} else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
}
return P;
}
_clipSegment(x0: number, y0: number, x1: number, y1: number, c0: number, c1: number) {//线段的切割
while (true) {
if (c0 === 0 && c1 === 0) return [x0, y0, x1, y1];
if (c0 & c1) return null;
let x, y, c = c0 || c1;
if (c & 0b1000) x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax;
else if (c & 0b0100) x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin;
else if (c & 0b0010) y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax;
else y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin;
if (c0) x0 = x, y0 = y, c0 = this._regioncode(x0, y0);
else x1 = x, y1 = y, c1 = this._regioncode(x1, y1);
}
}
_clipInfinite(i: any, points: any, vx0: number, vy0: number, vxn: number, vyn: number) {
let P = Array.from(points), p;
if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);
if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);
if (P = this._clipFinite(i, P)) {
for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {
c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);
if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;
}
} else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];
}
return P;
}
_edge(i: any, e0: number, e1: number, P: any[], j: number) {
while (e0 !== e1) {
let x, y;
switch (e0) {
case 0b0101: e0 = 0b0100; continue; // top-left
case 0b0100: e0 = 0b0110, x = this.xmax, y = this.ymin; break; // top
case 0b0110: e0 = 0b0010; continue; // top-right
case 0b0010: e0 = 0b1010, x = this.xmax, y = this.ymax; break; // right
case 0b1010: e0 = 0b1000; continue; // bottom-right
case 0b1000: e0 = 0b1001, x = this.xmin, y = this.ymax; break; // bottom
case 0b1001: e0 = 0b0001; continue; // bottom-left
case 0b0001: e0 = 0b0101, x = this.xmin, y = this.ymin; break; // left
}
if ((P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y)) {
P.splice(j, 0, x, y), j += 2;
}
}
if (P.length > 4) {
for (let i = 0; i < P.length; i += 2) {
const j = (i + 2) % P.length, k = (i + 4) % P.length;
if (P[i] === P[j] && P[j] === P[k]
|| P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1])
P.splice(j, 2), i -= 2;
}
}
return j;
}
_project(x0: any, y0: any, vx: number, vy: number) {
let t = Infinity, c, x, y;
if (vy < 0) { // top
if (y0 <= this.ymin) return null;
if ((c = (this.ymin - y0) / vy) < t) y = this.ymin, x = x0 + (t = c) * vx;
} else if (vy > 0) { // bottom
if (y0 >= this.ymax) return null;
if ((c = (this.ymax - y0) / vy) < t) y = this.ymax, x = x0 + (t = c) * vx;
}
if (vx > 0) { // right
if (x0 >= this.xmax) return null;
if ((c = (this.xmax - x0) / vx) < t) x = this.xmax, y = y0 + (t = c) * vy;
} else if (vx < 0) { // left
if (x0 <= this.xmin) return null;
if ((c = (this.xmin - x0) / vx) < t) x = this.xmin, y = y0 + (t = c) * vy;
}
return [x, y];
}
_edgecode(x: unknown, y: unknown) {
return (x === this.xmin ? 0b0001
: x === this.xmax ? 0b0010 : 0b0000)
| (y === this.ymin ? 0b0100
: y === this.ymax ? 0b1000 : 0b0000);
}
_regioncode(x: number, y: number) {
return (x < this.xmin ? 0b0001
: x > this.xmax ? 0b0010 : 0b0000)
| (y < this.ymin ? 0b0100
: y > this.ymax ? 0b1000 : 0b0000);
}
} | the_stack |
/// <reference types="activex-interop" />
declare namespace SHDocVw {
// tslint:disable-next-line no-const-enum
const enum BrowserBarConstants {
AddressBar = 0x0009,
Tools = 0x000A,
Links = 0x000B,
Search = '{30D02401-6A81-11D0-8274-00C04FD5AE38}',
Favorites = '{EFA24E61-B078-11D0-89E4-00C04FC9E26E}',
History = '{EFA24E62-B078-11D0-89E4-00C04FC9E26E}',
Channels = '{EFA24E63-B078-11D0-89E4-00C04FC9E26E}'
}
// tslint:disable-next-line no-const-enum
const enum BrowserNavConstants {
/** Open the resource or file in a new window. */
OpenInNewWindow = 1,
/** Do not add the resource or file to the history list. The new page replaces the current page in the list. */
NoHistory = 2,
/** If the navigation fails, the autosearch functionality attempts to navigate common root domains (.com, .edu, and so on). If this also fails, the URL is passed to a search engine. */
AllowAutosearch = 16,
/** Causes the current Explorer Bar to navigate to the given item, if possible. */
BrowserBar = 32,
/**
* Internet Explorer 6 for Windows XP SP2 and later. If the navigation fails when a hyperlink is being followed, this constant specifies that the resource should then be bound to the
* moniker using the [**BINDF_HYPERLINK**](https://msdn.microsoft.com/en-us/library/ms775130(v=vs.85).aspx) flag.
*/
Hyperlink = 64,
/** Internet Explorer 6 for Windows XP SP2 and later. Force the URL into the restricted zone. */
EnforceRestricted = 128,
/** Internet Explorer 6 for Windows XP SP2 and later. Use the default Popup Manager to block pop-up windows. */
NewWindowsManaged = 256,
/** Internet Explorer 6 for Windows XP SP2 and later. Block files that normally trigger a file download dialog box. */
UntrustedForDownload = 512,
/** Internet Explorer 6 for Windows XP SP2 and later. Prompt for the installation of ActiveX controls. */
TrustedForActiveX = 1024,
/** Internet Explorer 7. Open the resource or file in a new tab. Allow the destination window to come to the foreground, if necessary. */
OpenInNewTab = 2048,
/** Internet Explorer 7. Open the resource or file in a new background tab; the currently active window and/or tab remains open on top. */
OpenInBackgroundTab = 4096,
/**
* Internet Explorer 7. Maintain state for dynamic navigation based on the filter string entered in the search band text box (wordwheel). Restore the wordwheel text when the navigation
* completes.
*/
KeepWordWheelText = 8192,
/**
* Internet Explorer 8. Open the resource as a replacement for the current or target tab. The existing tab is closed while the new tab takes its place in the tab bar and replaces it in the
* tab group, if any. Browser history is copied forward to the new tab. On Windows Vista, this flag is implied if the navigation would cross integrity levels and **navOpenInNewTab**,
* **navOpenInBackgroundTab**, or **navOpenInNewWindow**> is not specified.
*/
VirtualTab = 16384,
/**
* Internet Explorer 8. Block cross-domain redirect requests. The navigation triggers the
* [**DWebBrowserEvents2::RedirectXDomainBlocked**](https://msdn.microsoft.com/en-us/library/dd565686(v=vs.85).aspx) event if blocked.
*/
BlockRedirectsXDomain = 32768,
/** Internet Explorer 8 and later. Open the resource in a new tab that becomes the foreground tab. */
OpenNewForegroundTab = 65536
}
/** Constants for WebBrowser CommandStateChange */
// tslint:disable-next-line no-const-enum
const enum CommandStateChangeConstants {
CSC_NAVIGATEBACK = 2,
CSC_NAVIGATEFORWARD = 1,
CSC_UPDATECOMMANDS = -1,
}
/** Constants for WebBrowser NewProcess notification */
// tslint:disable-next-line no-const-enum
const enum NewProcessCauseConstants {
ProtectedModeRedirect = 1,
}
// tslint:disable-next-line no-const-enum
const enum OLECMDEXECOPT {
OLECMDEXECOPT_DODEFAULT = 0,
OLECMDEXECOPT_DONTPROMPTUSER = 2,
OLECMDEXECOPT_PROMPTUSER = 1,
OLECMDEXECOPT_SHOWHELP = 3,
}
// tslint:disable-next-line no-const-enum
const enum OLECMDF {
OLECMDF_DEFHIDEONCTXTMENU = 32,
OLECMDF_ENABLED = 2,
OLECMDF_INVISIBLE = 16,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8,
OLECMDF_SUPPORTED = 1,
}
// tslint:disable-next-line no-const-enum
const enum OLECMDID {
OLECMDID_ACTIVEXINSTALLSCOPE = 66,
OLECMDID_ADDTRAVELENTRY = 60,
OLECMDID_ALLOWUILESSSAVEAS = 46,
OLECMDID_CLEARSELECTION = 18,
OLECMDID_CLOSE = 45,
OLECMDID_COPY = 12,
OLECMDID_CUT = 11,
OLECMDID_DELETE = 33,
OLECMDID_DONTDOWNLOADCSS = 47,
OLECMDID_ENABLE_INTERACTION = 36,
OLECMDID_ENABLE_VISIBILITY = 77,
OLECMDID_EXITFULLSCREEN = 81,
OLECMDID_FIND = 32,
OLECMDID_FOCUSVIEWCONTROLS = 57,
OLECMDID_FOCUSVIEWCONTROLSQUERY = 58,
OLECMDID_GETPRINTTEMPLATE = 52,
OLECMDID_GETUSERSCALABLE = 75,
OLECMDID_GETZOOMRANGE = 20,
OLECMDID_HIDETOOLBARS = 24,
OLECMDID_HTTPEQUIV = 34,
OLECMDID_HTTPEQUIV_DONE = 35,
OLECMDID_LAYOUT_VIEWPORT_WIDTH = 71,
OLECMDID_MEDIA_PLAYBACK = 78,
OLECMDID_NEW = 2,
OLECMDID_ONBEFOREUNLOAD = 83,
OLECMDID_ONTOOLBARACTIVATED = 31,
OLECMDID_ONUNLOAD = 37,
OLECMDID_OPEN = 1,
OLECMDID_OPTICAL_GETZOOMRANGE = 64,
OLECMDID_OPTICAL_ZOOM = 63,
OLECMDID_PAGEACTIONBLOCKED = 55,
OLECMDID_PAGEACTIONUIQUERY = 56,
OLECMDID_PAGEAVAILABLE = 74,
OLECMDID_PAGESETUP = 8,
OLECMDID_PASTE = 13,
OLECMDID_PASTESPECIAL = 14,
OLECMDID_POPSTATEEVENT = 69,
OLECMDID_PREREFRESH = 39,
OLECMDID_PRINT = 6,
OLECMDID_PRINT2 = 49,
OLECMDID_PRINTPREVIEW = 7,
OLECMDID_PRINTPREVIEW2 = 50,
OLECMDID_PROPERTIES = 10,
OLECMDID_PROPERTYBAG2 = 38,
OLECMDID_REDO = 16,
OLECMDID_REFRESH = 22,
OLECMDID_SAVE = 3,
OLECMDID_SAVEAS = 4,
OLECMDID_SAVECOPYAS = 5,
OLECMDID_SCROLLCOMPLETE = 82,
OLECMDID_SELECTALL = 17,
OLECMDID_SET_HOST_FULLSCREENMODE = 80,
OLECMDID_SETDOWNLOADSTATE = 29,
OLECMDID_SETFAVICON = 79,
OLECMDID_SETPRINTTEMPLATE = 51,
OLECMDID_SETPROGRESSMAX = 25,
OLECMDID_SETPROGRESSPOS = 26,
OLECMDID_SETPROGRESSTEXT = 27,
OLECMDID_SETTITLE = 28,
OLECMDID_SHOWFIND = 42,
OLECMDID_SHOWMESSAGE = 41,
OLECMDID_SHOWMESSAGE_BLOCKABLE = 84,
OLECMDID_SHOWPAGEACTIONMENU = 59,
OLECMDID_SHOWPAGESETUP = 43,
OLECMDID_SHOWPRINT = 44,
OLECMDID_SHOWSCRIPTERROR = 40,
OLECMDID_SHOWTASKDLG = 68,
OLECMDID_SHOWTASKDLG_BLOCKABLE = 85,
OLECMDID_SPELL = 9,
OLECMDID_STOP = 23,
OLECMDID_STOPDOWNLOAD = 30,
OLECMDID_UNDO = 15,
OLECMDID_UPDATE_CARET = 76,
OLECMDID_UPDATEBACKFORWARDSTATE = 62,
OLECMDID_UPDATECOMMANDS = 21,
OLECMDID_UPDATEPAGESTATUS = 48,
OLECMDID_UPDATETRAVELENTRY = 61,
OLECMDID_UPDATETRAVELENTRY_DATARECOVERY = 67,
OLECMDID_USER_OPTICAL_ZOOM = 73,
OLECMDID_VIEWPORT_MODE = 70,
OLECMDID_VISUAL_VIEWPORT_EXCLUDE_BOTTOM = 72,
OLECMDID_WINDOWSTATECHANGED = 65,
OLECMDID_ZOOM = 19,
}
// tslint:disable-next-line no-const-enum
const enum RefreshConstants {
Normal = 0,
IfExpired = 1,
Completely = 3
}
/** Constants for WebBrowser security icon notification */
// tslint:disable-next-line no-const-enum
const enum SecureLockIconConstants {
secureLockIconMixed = 1,
secureLockIconSecure128Bit = 6,
secureLockIconSecure40Bit = 3,
secureLockIconSecure56Bit = 4,
secureLockIconSecureFortezza = 5,
secureLockIconSecureUnknownBits = 2,
secureLockIconUnsecure = 0,
}
/** Options for ShellWindows FindWindow */
// tslint:disable-next-line no-const-enum
const enum ShellWindowFindWindowOptions {
SWFO_COOKIEPASSED = 4,
SWFO_INCLUDEPENDING = 2,
SWFO_NEEDDISPATCH = 1,
}
/** Constants for ShellWindows registration */
// tslint:disable-next-line no-const-enum
const enum ShellWindowTypeConstants {
SWC_3RDPARTY = 2,
SWC_BROWSER = 1,
SWC_CALLBACK = 4,
SWC_DESKTOP = 8,
SWC_EXPLORER = 0,
}
// tslint:disable-next-line no-const-enum
const enum tagREADYSTATE {
READYSTATE_COMPLETE = 4,
READYSTATE_INTERACTIVE = 3,
READYSTATE_LOADED = 2,
READYSTATE_LOADING = 1,
READYSTATE_UNINITIALIZED = 0,
}
type TargetFrameValues = '_blank' | '_parent' | '_self' | '_top' ;
class CScriptErrorList {
private 'SHDocVw.CScriptErrorList_typekey': CScriptErrorList;
private constructor();
advanceError(): void;
canAdvanceError(): number;
canRetreatError(): number;
getAlwaysShowLockState(): number;
getDetailsPaneOpen(): number;
getErrorChar(): number;
getErrorCode(): number;
getErrorLine(): number;
getErrorMsg(): string;
getErrorUrl(): string;
getPerErrorDisplay(): number;
retreatError(): void;
setDetailsPaneOpen(fDetailsPaneOpen: number): void;
setPerErrorDisplay(fPerErrorDisplay: number): void;
}
/** Internet Explorer Application. */
class InternetExplorer {
private 'SHDocVw.InternetExplorer_typekey': InternetExplorer;
private constructor();
/** Controls whether address bar is shown */
AddressBar: boolean;
/** Returns the application automation object if accessible, this automation object otherwise.. */
readonly Application: any;
/** Query to see if something is still in progress. */
readonly Busy: boolean;
/** Converts client sizes into window sizes. */
ClientToWindow(pcx: number, pcy: number): void;
/** Returns the container/parent automation object, if any. */
readonly Container: any;
/** Returns the active Document automation object, if any. */
readonly Document: any;
/** IOleCommandTarget::Exec */
ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void;
/** Returns file specification of the application, including path. */
readonly FullName: string;
/** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */
FullScreen: boolean;
/** Retrieve the Associated value for the property vtValue in the context of the object. */
GetProperty(Property: string): any;
/** Navigates to the previous item in the history list. */
GoBack(): void;
/** Navigates to the next item in the history list. */
GoForward(): void;
/** Go home/start page. */
GoHome(): void;
/** Go Search Page. */
GoSearch(): void;
/** The vertical dimension (pixels) of the frame window/object. */
Height: number;
/** Returns the HWND of the current IE window. */
readonly HWND: number;
/** The horizontal position (pixels) of the frame window relative to the screen/container. */
Left: number;
/** Gets the short (UI-friendly) name of the URL/file currently viewed. */
readonly LocationName: string;
/** Gets the full URL/path currently viewed. */
readonly LocationURL: string;
/** Controls whether menubar is shown. */
MenuBar: boolean;
/** Returns name of the application. */
readonly Name: string;
/** Navigates to a URL or file. */
Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Navigates to a URL or file or pidl. */
Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Controls if the frame is offline (read from cache) */
Offline: boolean;
/** Returns the automation object of the container/parent if one exists or this automation object. */
readonly Parent: any;
/** Returns the path to the application. */
readonly Path: string;
/** Associates vtValue with the name szProperty in the context of the object. */
PutProperty(Property: string, vtValue: any): void;
/** IOleCommandTarget::QueryStatus */
QueryStatusWB(cmdID: OLECMDID): OLECMDF;
/** Exits application and closes the open document. */
Quit(): void;
readonly ReadyState: tagREADYSTATE;
/** Refresh the currently viewed page. */
Refresh(): void;
/** Refresh the currently viewed page. */
Refresh2(Level?: RefreshConstants): void;
/** Registers OC as a top-level browser (for target name resolution) */
RegisterAsBrowser: boolean;
/** Registers OC as a drop target for navigation */
RegisterAsDropTarget: boolean;
/** Controls whether the window is resizable */
Resizable: boolean;
/** Set BrowserBar to Clsid */
ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void;
/** Controls if any dialog boxes can be shown */
Silent: boolean;
/** Turn on or off the statusbar. */
StatusBar: boolean;
/** Text of Status window. */
StatusText: string;
/** Stops opening a file. */
Stop(): void;
/** Controls if the browser is in theater mode */
TheaterMode: boolean;
/** Controls which toolbar is shown. */
ToolBar: number;
/** The vertical position (pixels) of the frame window relative to the screen/container. */
Top: number;
/** Returns True if this is the top level object. */
readonly TopLevelContainer: boolean;
/** Returns the type of the contained document object. */
readonly Type: string;
/** Determines whether the application is visible or hidden. */
Visible: boolean;
/** The horizontal dimension (pixels) of the frame window/object. */
Width: number;
}
/** Internet Explorer Application with default integrity of Medium */
class InternetExplorerMedium {
private 'SHDocVw.InternetExplorerMedium_typekey': InternetExplorerMedium;
private constructor();
/** Controls whether address bar is shown */
AddressBar: boolean;
/** Returns the application automation object if accessible, this automation object otherwise.. */
readonly Application: any;
/** Query to see if something is still in progress. */
readonly Busy: boolean;
/** Converts client sizes into window sizes. */
ClientToWindow(pcx: number, pcy: number): void;
/** Returns the container/parent automation object, if any. */
readonly Container: any;
/** Returns the active Document automation object, if any. */
readonly Document: any;
/** IOleCommandTarget::Exec */
ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void;
/** Returns file specification of the application, including path. */
readonly FullName: string;
/** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */
FullScreen: boolean;
/** Retrieve the Associated value for the property vtValue in the context of the object. */
GetProperty(Property: string): any;
/** Navigates to the previous item in the history list. */
GoBack(): void;
/** Navigates to the next item in the history list. */
GoForward(): void;
/** Go home/start page. */
GoHome(): void;
/** Go Search Page. */
GoSearch(): void;
/** The vertical dimension (pixels) of the frame window/object. */
Height: number;
/** Returns the HWND of the current IE window. */
readonly HWND: number;
/** The horizontal position (pixels) of the frame window relative to the screen/container. */
Left: number;
/** Gets the short (UI-friendly) name of the URL/file currently viewed. */
readonly LocationName: string;
/** Gets the full URL/path currently viewed. */
readonly LocationURL: string;
/** Controls whether menubar is shown. */
MenuBar: boolean;
/** Returns name of the application. */
readonly Name: string;
/** Navigates to a URL or file. */
Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Navigates to a URL or file or pidl. */
Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Controls if the frame is offline (read from cache) */
Offline: boolean;
/** Returns the automation object of the container/parent if one exists or this automation object. */
readonly Parent: any;
/** Returns the path to the application. */
readonly Path: string;
/** Associates vtValue with the name szProperty in the context of the object. */
PutProperty(Property: string, vtValue: any): void;
/** IOleCommandTarget::QueryStatus */
QueryStatusWB(cmdID: OLECMDID): OLECMDF;
/** Exits application and closes the open document. */
Quit(): void;
readonly ReadyState: tagREADYSTATE;
/** Refresh the currently viewed page. */
Refresh(): void;
/** Refresh the currently viewed page. */
Refresh2(Level?: RefreshConstants): void;
/** Registers OC as a top-level browser (for target name resolution) */
RegisterAsBrowser: boolean;
/** Registers OC as a drop target for navigation */
RegisterAsDropTarget: boolean;
/** Controls whether the window is resizable */
Resizable: boolean;
/** Set BrowserBar to Clsid */
ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void;
/** Controls if any dialog boxes can be shown */
Silent: boolean;
/** Turn on or off the statusbar. */
StatusBar: boolean;
/** Text of Status window. */
StatusText: string;
/** Stops opening a file. */
Stop(): void;
/** Controls if the browser is in theater mode */
TheaterMode: boolean;
/** Controls which toolbar is shown. */
ToolBar: number;
/** The vertical position (pixels) of the frame window relative to the screen/container. */
Top: number;
/** Returns True if this is the top level object. */
readonly TopLevelContainer: boolean;
/** Returns the type of the contained document object. */
readonly Type: string;
/** Determines whether the application is visible or hidden. */
Visible: boolean;
/** The horizontal dimension (pixels) of the frame window/object. */
Width: number;
}
/** Shell Browser Window. */
class ShellBrowserWindow {
private 'SHDocVw.ShellBrowserWindow_typekey': ShellBrowserWindow;
private constructor();
/** Controls whether address bar is shown */
AddressBar: boolean;
/** Returns the application automation object if accessible, this automation object otherwise.. */
readonly Application: any;
/** Query to see if something is still in progress. */
readonly Busy: boolean;
/** Converts client sizes into window sizes. */
ClientToWindow(pcx: number, pcy: number): void;
/** Returns the container/parent automation object, if any. */
readonly Container: any;
/** Returns the active Document automation object, if any. */
readonly Document: any;
/** IOleCommandTarget::Exec */
ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void;
/** Returns file specification of the application, including path. */
readonly FullName: string;
/** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */
FullScreen: boolean;
/** Retrieve the Associated value for the property vtValue in the context of the object. */
GetProperty(Property: string): any;
/** Navigates to the previous item in the history list. */
GoBack(): void;
/** Navigates to the next item in the history list. */
GoForward(): void;
/** Go home/start page. */
GoHome(): void;
/** Go Search Page. */
GoSearch(): void;
/** The vertical dimension (pixels) of the frame window/object. */
Height: number;
/** Returns the HWND of the current IE window. */
readonly HWND: number;
/** The horizontal position (pixels) of the frame window relative to the screen/container. */
Left: number;
/** Gets the short (UI-friendly) name of the URL/file currently viewed. */
readonly LocationName: string;
/** Gets the full URL/path currently viewed. */
readonly LocationURL: string;
/** Controls whether menubar is shown. */
MenuBar: boolean;
/** Returns name of the application. */
readonly Name: string;
/** Navigates to a URL or file. */
Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Navigates to a URL or file or pidl. */
Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Controls if the frame is offline (read from cache) */
Offline: boolean;
/** Returns the automation object of the container/parent if one exists or this automation object. */
readonly Parent: any;
/** Returns the path to the application. */
readonly Path: string;
/** Associates vtValue with the name szProperty in the context of the object. */
PutProperty(Property: string, vtValue: any): void;
/** IOleCommandTarget::QueryStatus */
QueryStatusWB(cmdID: OLECMDID): OLECMDF;
/** Exits application and closes the open document. */
Quit(): void;
readonly ReadyState: tagREADYSTATE;
/** Refresh the currently viewed page. */
Refresh(): void;
/** Refresh the currently viewed page. */
Refresh2(Level?: RefreshConstants): void;
/** Registers OC as a top-level browser (for target name resolution) */
RegisterAsBrowser: boolean;
/** Registers OC as a drop target for navigation */
RegisterAsDropTarget: boolean;
/** Controls whether the window is resizable */
Resizable: boolean;
/** Set BrowserBar to Clsid */
ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void;
/** Controls if any dialog boxes can be shown */
Silent: boolean;
/** Turn on or off the statusbar. */
StatusBar: boolean;
/** Text of Status window. */
StatusText: string;
/** Stops opening a file. */
Stop(): void;
/** Controls if the browser is in theater mode */
TheaterMode: boolean;
/** Controls which toolbar is shown. */
ToolBar: number;
/** The vertical position (pixels) of the frame window relative to the screen/container. */
Top: number;
/** Returns True if this is the top level object. */
readonly TopLevelContainer: boolean;
/** Returns the type of the contained document object. */
readonly Type: string;
/** Determines whether the application is visible or hidden. */
Visible: boolean;
/** The horizontal dimension (pixels) of the frame window/object. */
Width: number;
}
class ShellNameSpace {
private 'SHDocVw.ShellNameSpace_typekey': ShellNameSpace;
private constructor();
Columns: string;
/** number of view types */
readonly CountViewTypes: number;
/** method CreateSubscriptionForSelection */
CreateSubscriptionForSelection(): boolean;
/** method DeleteSubscriptionForSelection */
DeleteSubscriptionForSelection(): boolean;
Depth: number;
/** options */
EnumOptions: number;
/** expands item specified depth */
Expand(var_0: any, iDepth: number): void;
/** method Export */
Export(): void;
Flags: number;
/** method Import */
Import(): void;
/** method InvokeContextMenuCommand */
InvokeContextMenuCommand(strCommand: string): void;
Mode: number;
/** method MoveSelectionDown */
MoveSelectionDown(): void;
/** method MoveSelectionTo */
MoveSelectionTo(): void;
/** method MoveSelectionUp */
MoveSelectionUp(): void;
/** method NewFolder */
NewFolder(): void;
/** method ResetSort */
ResetSort(): void;
/** get the root item */
Root: any;
/** get the selected item */
SelectedItem: any;
/** collection of selected items */
SelectedItems(): any;
/** old, use put_Root() instead */
SetRoot(bstrFullPath: string): void;
/** set view type */
SetViewType(iType: number): void;
/** Query to see if subscriptions are enabled */
readonly SubscriptionsEnabled: boolean;
/** method Synchronize */
Synchronize(): void;
TVFlags: number;
/** unselects all items */
UnselectAll(): void;
}
class ShellUIHelper {
private 'SHDocVw.ShellUIHelper_typekey': ShellUIHelper;
private constructor();
AddChannel(URL: string): void;
AddDesktopComponent(URL: string, Type: string, Left?: any, Top?: any, Width?: any, Height?: any): void;
AddFavorite(URL: string, Title?: any): void;
AddSearchProvider(URL: string): void;
AddService(URL: string): void;
AddToFavoritesBar(URL: string, Title: string, Type?: any): void;
AutoCompleteAttach(Reserved?: any): void;
AutoCompleteSaveForm(Form?: any): void;
AutoScan(strSearch: string, strFailureUrl: string, pvarTargetFrame?: any): void;
BrandImageUri(): string;
BuildNewTabPage(): void;
ContentDiscoveryReset(): void;
CustomizeClearType(fSet: boolean): void;
CustomizeSettings(fSQM: boolean, fPhishing: boolean, bstrLocale: string): void;
DefaultSearchProvider(): string;
DiagnoseConnection(): void;
EnableSuggestedSites(fEnable: boolean): void;
GetCVListData(): string;
GetCVListLocalData(): string;
GetEMIEListData(): string;
GetEMIEListLocalData(): string;
GetExperimentalFlag(bstrFlagString: string): boolean;
GetExperimentalValue(bstrValueString: string): number;
GetNeedIEAutoLaunchFlag(bstrUrl: string): boolean;
HasNeedIEAutoLaunchFlag(bstrUrl: string): boolean;
ImportExportFavorites(fImport: boolean, strImpExpPath: string): void;
InPrivateFilteringEnabled(): boolean;
IsSearchMigrated(): boolean;
IsSearchProviderInstalled(URL: string): number;
IsServiceInstalled(URL: string, Verb: string): number;
IsSubscribed(URL: string): boolean;
IsSuggestedSitesEnabled(): boolean;
LaunchIE(bstrUrl: string, automated: boolean): void;
LaunchInHVSI(bstrUrl: string): void;
msActiveXFilteringEnabled(): boolean;
msAddSiteMode(): void;
msAddTrackingProtectionList(URL: string, bstrFilterName: string): void;
msChangeDefaultBrowser(fChange: boolean): void;
msClearTile(): void;
msDiagnoseConnectionUILess(): void;
msEnableTileNotificationQueue(fChange: boolean): void;
msEnableTileNotificationQueueForSquare150x150(fChange: boolean): void;
msEnableTileNotificationQueueForSquare310x310(fChange: boolean): void;
msEnableTileNotificationQueueForWide310x150(fChange: boolean): void;
msIsSiteMode(): boolean;
msIsSiteModeFirstRun(fPreserveState: boolean): any;
msLaunchInternetOptions(): void;
msLaunchNetworkClientHelp(): void;
msPinnedSiteState(): any;
msProvisionNetworks(bstrProvisioningXml: string): any;
msRemoveScheduledTileNotification(bstrNotificationId: string): void;
msReportSafeUrl(): void;
msScheduledTileNotification(bstrNotificationXml: string, bstrNotificationId: string, bstrNotificationTag: string, startTime?: any, expirationTime?: any): void;
msSiteModeActivate(): void;
msSiteModeAddButtonStyle(uiButtonID: any, bstrIconURL: string, bstrTooltip: string): any;
msSiteModeAddJumpListItem(bstrName: string, bstrActionUri: string, bstrIconUri: string, pvarWindowType?: any): void;
msSiteModeAddThumbBarButton(bstrIconURL: string, bstrTooltip: string): any;
msSiteModeClearBadge(): void;
msSiteModeClearIconOverlay(): void;
msSiteModeClearJumpList(): void;
msSiteModeCreateJumpList(bstrHeader: string): void;
msSiteModeRefreshBadge(): void;
msSiteModeSetIconOverlay(IconUrl: string, pvarDescription?: any): void;
msSiteModeShowButtonStyle(uiButtonID: any, uiStyleID: any): void;
msSiteModeShowJumpList(): void;
msSiteModeShowThumbBar(): void;
msSiteModeUpdateThumbBarButton(ButtonID: any, fEnabled: boolean, fVisible: boolean): void;
msStartPeriodicBadgeUpdate(pollingUri: string, startTime?: any, uiUpdateRecurrence?: any): void;
msStartPeriodicTileUpdate(pollingUris: any, startTime?: any, uiUpdateRecurrence?: any): void;
msStartPeriodicTileUpdateBatch(pollingUris: any, startTime?: any, uiUpdateRecurrence?: any): void;
msStopPeriodicBadgeUpdate(): void;
msStopPeriodicTileUpdate(): void;
msTrackingProtectionEnabled(): boolean;
NavigateAndFind(URL: string, strQuery: string, varTargetFrame: any): void;
NavigateToSuggestedSites(bstrRelativeUrl: string): void;
OpenFavoritesPane(): void;
OpenFavoritesSettings(): void;
PhishingEnabled(): boolean;
RefreshOfflineDesktop(): void;
ResetAllExperimentalFlagsAndValues(): void;
ResetFirstBootMode(): void;
ResetSafeMode(): void;
RunOnceHasShown(): boolean;
RunOnceRequiredSettingsComplete(fComplete: boolean): void;
RunOnceShown(): void;
SearchGuideUrl(): string;
SetActivitiesVisible(fVisible: boolean): void;
SetExperimentalFlag(bstrFlagString: string, vfFlag: boolean): void;
SetExperimentalValue(bstrValueString: string, dwValue: number): void;
SetNeedIEAutoLaunchFlag(bstrUrl: string, flag: boolean): void;
SetRecentlyClosedVisible(fVisible: boolean): void;
ShowBrowserUI(bstrName: string, pvarIn: any): any;
ShowInPrivateHelp(): void;
ShowTabsHelp(): void;
SkipRunOnce(): void;
SkipTabsWelcome(): void;
SqmEnabled(): boolean;
}
/** ShellDispatch Load in Shell Context */
class ShellWindows {
private 'SHDocVw.ShellWindows_typekey': ShellWindows;
private constructor();
/** Get count of open Shell windows */
readonly Count: number;
/** Find the window based on the location */
FindWindowSW(pvarloc: any, pvarlocRoot: any, swClass: number, pHWND: number, swfwOptions: number): any;
/** Return the shell window for the given index */
Item(index?: any): any;
/** Notifies the activation */
OnActivated(lCookie: number, fActive: boolean): void;
/** Notifies on creation and frame name set */
OnCreated(lCookie: number, punk: any): void;
/** Notifies the new location */
OnNavigate(lCookie: number, pvarloc: any): void;
/** Used by IExplore to register different processes */
ProcessAttachDetach(fAttach: boolean): void;
/** Register a window with the list */
Register(pid: any, HWND: number, swClass: number, plCookie: number): void;
/** Register a pending open with the list */
RegisterPending(lThreadId: number, pvarloc: any, pvarlocRoot: any, swClass: number, plCookie: number): void;
/** Remove a window from the list */
Revoke(lCookie: number): void;
}
/** WebBrowser Control */
class WebBrowser {
private 'SHDocVw.WebBrowser_typekey': WebBrowser;
private constructor();
/** Controls whether address bar is shown (ignored by WebBrowser) */
AddressBar: boolean;
/** Returns the application automation object if accessible, this automation object otherwise.. */
readonly Application: any;
/** Query to see if something is still in progress. */
readonly Busy: boolean;
/** Converts client sizes into window sizes. */
ClientToWindow(pcx: number, pcy: number): void;
/** Returns the container/parent automation object, if any. */
readonly Container: any;
/** Returns the active Document automation object, if any. */
readonly Document: any;
/** IOleCommandTarget::Exec */
ExecWB(cmdID: OLECMDID, cmdexecopt: OLECMDEXECOPT, pvaIn?: any, pvaOut?: any): void;
/** Returns file specification of the application, including path. */
readonly FullName: string;
/** Maximizes window and turns off statusbar, toolbar, menubar, and titlebar. */
FullScreen: boolean;
/** Retrieve the Associated value for the property vtValue in the context of the object. */
GetProperty(Property: string): any;
/** Navigates to the previous item in the history list. */
GoBack(): void;
/** Navigates to the next item in the history list. */
GoForward(): void;
/** Go home/start page. */
GoHome(): void;
/** Go Search Page. */
GoSearch(): void;
/** The vertical dimension (pixels) of the frame window/object. */
Height: number;
/** Returns the HWND of the current IE window. */
readonly HWND: number;
/** The horizontal position (pixels) of the frame window relative to the screen/container. */
Left: number;
/** Gets the short (UI-friendly) name of the URL/file currently viewed. */
readonly LocationName: string;
/** Gets the full URL/path currently viewed. */
readonly LocationURL: string;
/** Controls whether menubar is shown. */
MenuBar: boolean;
/** Returns name of the application. */
readonly Name: string;
/** Navigates to a URL or file. */
Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Navigates to a URL or file or pidl. */
Navigate2(URL: any, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Controls if the frame is offline (read from cache) */
Offline: boolean;
/** Returns the automation object of the container/parent if one exists or this automation object. */
readonly Parent: any;
/** Returns the path to the application. */
readonly Path: string;
/** Associates vtValue with the name szProperty in the context of the object. */
PutProperty(Property: string, vtValue: any): void;
/** IOleCommandTarget::QueryStatus */
QueryStatusWB(cmdID: OLECMDID): OLECMDF;
/** Exits application and closes the open document. */
Quit(): void;
readonly ReadyState: tagREADYSTATE;
/** Refresh the currently viewed page. */
Refresh(): void;
/** Refresh the currently viewed page. */
Refresh2(Level?: RefreshConstants): void;
/** Registers OC as a top-level browser (for target name resolution) */
RegisterAsBrowser: boolean;
/** Registers OC as a drop target for navigation */
RegisterAsDropTarget: boolean;
/** Controls whether the window is resizable */
Resizable: boolean;
/** Set BrowserBar to Clsid */
ShowBrowserBar(pvaClsid: string | BrowserBarConstants, pvarShow?: boolean): void;
/** Controls if any dialog boxes can be shown */
Silent: boolean;
/** Turn on or off the statusbar. */
StatusBar: boolean;
/** Text of Status window. */
StatusText: string;
/** Stops opening a file. */
Stop(): void;
/** Controls if the browser is in theater mode */
TheaterMode: boolean;
/** Controls which toolbar is shown. */
ToolBar: number;
/** The vertical position (pixels) of the frame window relative to the screen/container. */
Top: number;
/** Returns True if this is the top level object. */
readonly TopLevelContainer: boolean;
/** Returns the type of the contained document object. */
readonly Type: string;
/** Determines whether the application is visible or hidden. */
Visible: boolean;
/** The horizontal dimension (pixels) of the frame window/object. */
Width: number;
}
/** WebBrowser Control */
class WebBrowser_V1 {
private 'SHDocVw.WebBrowser_V1_typekey': WebBrowser_V1;
private constructor();
/** Returns the application automation object if accessible, this automation object otherwise.. */
readonly Application: any;
/** Query to see if something is still in progress. */
readonly Busy: boolean;
/** Returns the container/parent automation object, if any. */
readonly Container: any;
/** Returns the active Document automation object, if any. */
readonly Document: any;
/** Navigates to the previous item in the history list. */
GoBack(): void;
/** Navigates to the next item in the history list. */
GoForward(): void;
/** Go home/start page. */
GoHome(): void;
/** Go Search Page. */
GoSearch(): void;
/** The vertical dimension (pixels) of the frame window/object. */
Height: number;
/** The horizontal position (pixels) of the frame window relative to the screen/container. */
Left: number;
/** Gets the short (UI-friendly) name of the URL/file currently viewed. */
readonly LocationName: string;
/** Gets the full URL/path currently viewed. */
readonly LocationURL: string;
/** Navigates to a URL or file. */
Navigate(URL: string, Flags?: BrowserNavConstants, TargetFrameName?: TargetFrameValues | string, PostData?: any, Headers?: string): void;
/** Returns the automation object of the container/parent if one exists or this automation object. */
readonly Parent: any;
/** Refresh the currently viewed page. */
Refresh(): void;
/** Refresh the currently viewed page. */
Refresh2(Level?: RefreshConstants): void;
/** Stops opening a file. */
Stop(): void;
/** The vertical position (pixels) of the frame window relative to the screen/container. */
Top: number;
/** Returns True if this is the top level object. */
readonly TopLevelContainer: boolean;
/** Returns the type of the contained document object. */
readonly Type: string;
/** The horizontal dimension (pixels) of the frame window/object. */
Width: number;
}
namespace EventHelperTypes {
type InternetExplorer_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type InternetExplorerMedium_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type ShellBrowserWindow_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type ShellNameSpace_FavoritesSelectionChange_ArgNames = ['cItems', 'hItem', 'strName', 'strUrl', 'cVisits', 'strDate', 'fAvailableOffline'];
type WebBrowser_BeforeNavigate2_ArgNames = ['pDisp', 'URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type WebBrowser_V1_BeforeNavigate_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type WebBrowser_V1_FrameBeforeNavigate_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Cancel'];
type WebBrowser_V1_FrameNewWindow_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Processed'];
type WebBrowser_V1_NewWindow_ArgNames = ['URL', 'Flags', 'TargetFrameName', 'PostData', 'Headers', 'Processed'];
interface InternetExplorer_BeforeNavigate2_Parameter {
Cancel: boolean;
readonly Flags: any;
readonly Headers: any;
readonly pDisp: any;
readonly PostData: any;
readonly TargetFrameName: any;
readonly URL: any;
}
interface InternetExplorerMedium_BeforeNavigate2_Parameter {
Cancel: boolean;
readonly Flags: any;
readonly Headers: any;
readonly pDisp: any;
readonly PostData: any;
readonly TargetFrameName: any;
readonly URL: any;
}
interface ShellBrowserWindow_BeforeNavigate2_Parameter {
Cancel: boolean;
readonly Flags: any;
readonly Headers: any;
readonly pDisp: any;
readonly PostData: any;
readonly TargetFrameName: any;
readonly URL: any;
}
interface ShellNameSpace_FavoritesSelectionChange_Parameter {
readonly cItems: number;
readonly cVisits: number;
readonly fAvailableOffline: number;
readonly hItem: number;
readonly strDate: string;
readonly strName: string;
readonly strUrl: string;
}
interface WebBrowser_BeforeNavigate2_Parameter {
Cancel: boolean;
readonly Flags: any;
readonly Headers: any;
readonly pDisp: any;
readonly PostData: any;
readonly TargetFrameName: any;
readonly URL: any;
}
interface WebBrowser_V1_BeforeNavigate_Parameter {
Cancel: boolean;
readonly Flags: number;
readonly Headers: string;
readonly PostData: any;
readonly TargetFrameName: string;
readonly URL: string;
}
interface WebBrowser_V1_FrameBeforeNavigate_Parameter {
Cancel: boolean;
readonly Flags: number;
readonly Headers: string;
readonly PostData: any;
readonly TargetFrameName: string;
readonly URL: string;
}
interface WebBrowser_V1_FrameNewWindow_Parameter {
readonly Flags: number;
readonly Headers: string;
readonly PostData: any;
Processed: boolean;
readonly TargetFrameName: string;
readonly URL: string;
}
interface WebBrowser_V1_NewWindow_Parameter {
readonly Flags: number;
readonly Headers: string;
readonly PostData: any;
Processed: boolean;
readonly TargetFrameName: string;
readonly URL: string;
}
}
}
interface ActiveXObject {
on(
obj: SHDocVw.InternetExplorer, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.InternetExplorer_BeforeNavigate2_ArgNames,
handler: (this: SHDocVw.InternetExplorer, parameter: SHDocVw.EventHelperTypes.InternetExplorer_BeforeNavigate2_Parameter) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly pDispWindow: any }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.InternetExplorer, parameter: { CX: number, CY: number }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly URL: any }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.InternetExplorer, parameter: { ppDisp: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'],
handler: (this: SHDocVw.InternetExplorer, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly FullScreen: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly MenuBar: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly StatusBar: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly TheaterMode: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly ToolBar: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Visible: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (this: SHDocVw.InternetExplorer,
parameter: { readonly bImpacted: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly szProperty: string }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'],
handler: (this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly PhishingFilterStatus: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (this: SHDocVw.InternetExplorer,
parameter: { readonly SecureLockIcon: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Text: string }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly URL: any, readonly dwCount: number }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly dwUniqueID: number }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Height: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Left: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Resizable: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Top: number }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.InternetExplorer, parameter: { readonly Width: number }) => void): void;
on(
obj: SHDocVw.InternetExplorer, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: (
this: SHDocVw.InternetExplorer, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.InternetExplorerMedium_BeforeNavigate2_ArgNames,
handler: (this: SHDocVw.InternetExplorerMedium, parameter: SHDocVw.EventHelperTypes.InternetExplorerMedium_BeforeNavigate2_Parameter) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDispWindow: any }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { CX: number, CY: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly URL: any }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'],
handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { ppDisp: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'],
handler: (this: SHDocVw.InternetExplorerMedium, parameter: {
ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string,
readonly bstrUrl: string
}) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.InternetExplorerMedium,
parameter: { readonly FullScreen: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly MenuBar: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly StatusBar: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly TheaterMode: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly ToolBar: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Visible: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'],
handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly bImpacted: boolean }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.InternetExplorerMedium,
parameter: { readonly szProperty: string }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'],
handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly PhishingFilterStatus: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly SecureLockIcon: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly Text: string }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly URL: any, readonly dwCount: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwUniqueID: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Height: number }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Left: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (
this: SHDocVw.InternetExplorerMedium, parameter: { readonly Resizable: boolean }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Top: number }) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly Width: number }) => void): void;
on(
obj: SHDocVw.InternetExplorerMedium, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'],
handler: (this: SHDocVw.InternetExplorerMedium, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.ShellBrowserWindow_BeforeNavigate2_ArgNames,
handler: (this: SHDocVw.ShellBrowserWindow, parameter: SHDocVw.EventHelperTypes.ShellBrowserWindow_BeforeNavigate2_Parameter) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDispWindow: any }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { CX: number, CY: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly URL: any }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { ppDisp: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'],
handler: (this: SHDocVw.ShellBrowserWindow, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly FullScreen: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly MenuBar: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly StatusBar: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly TheaterMode: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly ToolBar: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Visible: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly bImpacted: boolean }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly szProperty: string }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'],
handler: (this: SHDocVw.ShellBrowserWindow, parameter: {
readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any,
readonly StatusCode: any
}) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly PhishingFilterStatus: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly SecureLockIcon: number }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Text: string }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly URL: any, readonly dwCount: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwUniqueID: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Height: number }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Left: number }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Resizable: boolean }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Top: number }) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.ShellBrowserWindow, parameter: { readonly Width: number }) => void): void;
on(
obj: SHDocVw.ShellBrowserWindow, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: (
this: SHDocVw.ShellBrowserWindow, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void;
on(
obj: SHDocVw.ShellNameSpace, event: 'FavoritesSelectionChange', argNames: SHDocVw.EventHelperTypes.ShellNameSpace_FavoritesSelectionChange_ArgNames,
handler: (this: SHDocVw.ShellNameSpace, parameter: SHDocVw.EventHelperTypes.ShellNameSpace_FavoritesSelectionChange_Parameter) => void): void;
on(obj: SHDocVw.ShellWindows, event: 'WindowRegistered' | 'WindowRevoked', argNames: ['lCookie'], handler: (this: SHDocVw.ShellWindows, parameter: { readonly lCookie: number }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'BeforeNavigate2', argNames: SHDocVw.EventHelperTypes.WebBrowser_BeforeNavigate2_ArgNames, handler: (
this: SHDocVw.WebBrowser, parameter: SHDocVw.EventHelperTypes.WebBrowser_BeforeNavigate2_Parameter) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'BeforeScriptExecute', argNames: ['pDispWindow'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly pDispWindow: any }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'ClientToHostWindow', argNames: ['CX', 'CY'], handler: (this: SHDocVw.WebBrowser, parameter: { CX: number, CY: number }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'DocumentComplete' | 'NavigateComplete2', argNames: ['pDisp', 'URL'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly URL: any }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'FileDownload', argNames: ['ActiveDocument', 'Cancel'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly ActiveDocument: boolean, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'NavigateError', argNames: ['pDisp', 'URL', 'Frame', 'StatusCode', 'Cancel'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly URL: any, readonly Frame: any, readonly StatusCode: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'NewProcess', argNames: ['lCauseFlag', 'pWB2', 'Cancel'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly lCauseFlag: number, readonly pWB2: any, Cancel: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'NewWindow2', argNames: ['ppDisp', 'Cancel'], handler: (this: SHDocVw.WebBrowser, parameter: { ppDisp: any, Cancel: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'NewWindow3', argNames: ['ppDisp', 'Cancel', 'dwFlags', 'bstrUrlContext', 'bstrUrl'], handler: (
this: SHDocVw.WebBrowser, parameter: { ppDisp: any, Cancel: boolean, readonly dwFlags: number, readonly bstrUrlContext: string, readonly bstrUrl: string }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnFullScreen', argNames: ['FullScreen'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly FullScreen: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnMenuBar', argNames: ['MenuBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly MenuBar: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnStatusBar', argNames: ['StatusBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly StatusBar: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnTheaterMode', argNames: ['TheaterMode'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly TheaterMode: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnToolBar', argNames: ['ToolBar'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly ToolBar: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'OnVisible', argNames: ['Visible'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Visible: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'PrintTemplateInstantiation' | 'PrintTemplateTeardown', argNames: ['pDisp'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'PrivacyImpactedStateChange', argNames: ['bImpacted'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly bImpacted: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'PropertyChange', argNames: ['szProperty'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly szProperty: string }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'RedirectXDomainBlocked', argNames: ['pDisp', 'StartURL', 'RedirectURL', 'Frame', 'StatusCode'],
handler: (this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly StartURL: any, readonly RedirectURL: any, readonly Frame: any, readonly StatusCode: any }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'SetPhishingFilterStatus', argNames: ['PhishingFilterStatus'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly PhishingFilterStatus: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'SetSecureLockIcon', argNames: ['SecureLockIcon'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly SecureLockIcon: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Text: string }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'ThirdPartyUrlBlocked', argNames: ['URL', 'dwCount'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly URL: any, readonly dwCount: number }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'UpdatePageStatus', argNames: ['pDisp', 'nPage', 'fDone'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly pDisp: any, readonly nPage: any, readonly fDone: any }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WebWorkerFinsihed', argNames: ['dwUniqueID'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly dwUniqueID: number }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'WebWorkerStarted', argNames: ['dwUniqueID', 'bstrWorkerLabel'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly dwUniqueID: number, readonly bstrWorkerLabel: string }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'WindowClosing', argNames: ['IsChildWindow', 'Cancel'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly IsChildWindow: boolean, Cancel: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WindowSetHeight', argNames: ['Height'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Height: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WindowSetLeft', argNames: ['Left'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Left: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WindowSetResizable', argNames: ['Resizable'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Resizable: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WindowSetTop', argNames: ['Top'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Top: number }) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'WindowSetWidth', argNames: ['Width'], handler: (this: SHDocVw.WebBrowser, parameter: { readonly Width: number }) => void): void;
on(
obj: SHDocVw.WebBrowser, event: 'WindowStateChanged', argNames: ['dwWindowStateFlags', 'dwValidFlagsMask'], handler: (
this: SHDocVw.WebBrowser, parameter: { readonly dwWindowStateFlags: number, readonly dwValidFlagsMask: number }) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'BeforeNavigate', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_BeforeNavigate_ArgNames,
handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_BeforeNavigate_Parameter) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'CommandStateChange', argNames: ['Command', 'Enable'], handler: (
this: SHDocVw.WebBrowser_V1, parameter: { readonly Command: number, readonly Enable: boolean }) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'FrameBeforeNavigate', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameBeforeNavigate_ArgNames,
handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameBeforeNavigate_Parameter) => void): void;
on(obj: SHDocVw.WebBrowser_V1, event: 'FrameNavigateComplete' | 'NavigateComplete', argNames: ['URL'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly URL: string }) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'FrameNewWindow', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameNewWindow_ArgNames,
handler: (this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_FrameNewWindow_Parameter) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'NewWindow', argNames: SHDocVw.EventHelperTypes.WebBrowser_V1_NewWindow_ArgNames, handler: (
this: SHDocVw.WebBrowser_V1, parameter: SHDocVw.EventHelperTypes.WebBrowser_V1_NewWindow_Parameter) => void): void;
on(
obj: SHDocVw.WebBrowser_V1, event: 'ProgressChange', argNames: ['Progress', 'ProgressMax'], handler: (
this: SHDocVw.WebBrowser_V1, parameter: { readonly Progress: number, readonly ProgressMax: number }) => void): void;
on(obj: SHDocVw.WebBrowser_V1, event: 'PropertyChange', argNames: ['Property'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly Property: string }) => void): void;
on(obj: SHDocVw.WebBrowser_V1, event: 'Quit', argNames: ['Cancel'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { Cancel: boolean }) => void): void;
on(obj: SHDocVw.WebBrowser_V1, event: 'StatusTextChange' | 'TitleChange', argNames: ['Text'], handler: (this: SHDocVw.WebBrowser_V1, parameter: { readonly Text: string }) => void): void;
on(obj: SHDocVw.InternetExplorer, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.InternetExplorer, parameter: {}) => void): void;
on(obj: SHDocVw.InternetExplorerMedium, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.InternetExplorerMedium, parameter: {}) => void): void;
on(obj: SHDocVw.ShellBrowserWindow, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.ShellBrowserWindow, parameter: {}) => void): void;
on(obj: SHDocVw.ShellNameSpace, event: 'DoubleClick' | 'Initialized' | 'SelectionChange', handler: (this: SHDocVw.ShellNameSpace, parameter: {}) => void): void;
on(obj: SHDocVw.WebBrowser, event: 'DownloadBegin' | 'DownloadComplete' | 'OnQuit', handler: (this: SHDocVw.WebBrowser, parameter: {}) => void): void;
on(obj: SHDocVw.WebBrowser_V1, event: 'DownloadBegin' | 'DownloadComplete' | 'WindowActivate' | 'WindowMove' | 'WindowResize', handler: (this: SHDocVw.WebBrowser_V1, parameter: {}) => void): void;
}
interface ActiveXObjectNameMap {
'InternetExplorer.Application': SHDocVw.InternetExplorer;
'Shell.Explorer': SHDocVw.WebBrowser;
'Shell.UIHelper': SHDocVw.ShellUIHelper;
'ShellNameSpace.ShellNameSpace': SHDocVw.ShellNameSpace;
} | the_stack |
interface JQuery {
progress: SemanticUI.Progress;
}
declare namespace SemanticUI {
interface Progress {
settings: ProgressSettings;
/**
* Sets current percent of progress to value. If using a total will convert from percent to estimated value.
*/
(behavior: 'set percent', percent: number): JQuery;
/**
* Sets progress to specified value. Will automatically calculate percent from total.
*/
(behavior: 'set progress', value: number): JQuery;
/**
* Increments progress by increment value, if not passed a value will use random amount specified in settings
*/
(behavior: 'increment', incrementValue?: number): JQuery;
/**
* Decrements progress by decrement value, if not passed a value will use random amount specified in settings
*/
(behavior: 'decrement', decrementValue?: number): JQuery;
/**
* Immediately updates progress to value, ignoring progress animation interval delays
*/
(behavior: 'update progress', value: number): JQuery;
/**
* Finishes progress and sets loaded to 100%
*/
(behavior: 'complete'): JQuery;
/**
* Resets progress to zero
*/
(behavior: 'reset'): JQuery;
/**
* Set total to a new value
*/
(behavior: 'set total', total: number): JQuery;
/**
* Replaces templated string with value, total, percent left and percent.
*/
(behavior: 'get text', text: string): string;
/**
* Returns normalized value inside acceptable range specified by total.
*/
(behavior: 'get normalized value', value: number): number;
/**
* Returns percent as last specified
*/
(behavior: 'get percent'): number;
/**
* Returns current progress value
*/
(behavior: 'get value'): number;
/**
* Returns total
*/
(behavior: 'get total'): number;
/**
* Returns whether progress is completed
*/
(behavior: 'is complete'): boolean;
/**
* Returns whether progress was a success
*/
(behavior: 'is success'): boolean;
/**
* Returns whether progress is in warning state
*/
(behavior: 'is warning'): boolean;
/**
* Returns whether progress is in error state
*/
(behavior: 'is error'): boolean;
/**
* Returns whether progress is in active state
*/
(behavior: 'is active'): boolean;
/**
* Sets progress to active state
*/
(behavior: 'set active'): JQuery;
/**
* Sets progress to warning state
*/
(behavior: 'set warning'): JQuery;
/**
* Sets progress to success state
*/
(behavior: 'set success'): JQuery;
/**
* Sets progress to error state
*/
(behavior: 'set error'): JQuery;
/**
* Changes progress animation speed
*/
(behavior: 'set duration', value: number): JQuery;
/**
* Sets progress exterior label to text
*/
(behavior: 'set label', text: string): JQuery;
/**
* Sets progress bar label to text
*/
(behavior: 'set bar label', text: string): JQuery;
/**
* Removes progress to active state
*/
(behavior: 'remove active'): JQuery;
/**
* Removes progress to warning state
*/
(behavior: 'remove warning'): JQuery;
/**
* Removes progress to success state
*/
(behavior: 'remove success'): JQuery;
/**
* Removes progress to error state
*/
(behavior: 'remove error'): JQuery;
(behavior: 'destroy'): JQuery;
<K extends keyof ProgressSettings>(behavior: 'setting', name: K, value?: undefined): ProgressSettings._Impl[K];
<K extends keyof ProgressSettings>(behavior: 'setting', name: K, value: ProgressSettings._Impl[K]): JQuery;
(behavior: 'setting', value: ProgressSettings): JQuery;
(settings?: ProgressSettings): JQuery;
}
/**
* @see {@link http://semantic-ui.com/modules/progress.html#/settings}
*/
type ProgressSettings = ProgressSettings.Param;
namespace ProgressSettings {
type Param = (Pick<_Impl, 'autoSuccess'> |
Pick<_Impl, 'showActivity'> |
Pick<_Impl, 'limitValues'> |
Pick<_Impl, 'label'> |
Pick<_Impl, 'random'> |
Pick<_Impl, 'precision'> |
Pick<_Impl, 'total'> |
Pick<_Impl, 'value'> |
Pick<_Impl, 'onChange'> |
Pick<_Impl, 'onSuccess'> |
Pick<_Impl, 'onActive'> |
Pick<_Impl, 'onError'> |
Pick<_Impl, 'onWarning'> |
Pick<_Impl, 'text'> |
Pick<_Impl, 'regExp'> |
Pick<_Impl, 'selector'> |
Pick<_Impl, 'metadata'> |
Pick<_Impl, 'className'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'namespace'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'silent'> |
Pick<_Impl, 'debug'> |
Pick<_Impl, 'performance'> |
Pick<_Impl, 'verbose'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
// region Progress Settings
/**
* Whether success state should automatically trigger when progress completes
*
* @default true
*/
autoSuccess: boolean;
/**
* Whether progress should automatically show activity when incremented
*
* @default true
*/
showActivity: boolean;
/**
* When set to true, values that calculate to above 100% or below 0% will be adjusted.
* When set to false, inappropriate values will produce an error.
*
* @default true
*/
limitValues: boolean;
/**
* Can be set to either to display progress as percent or ratio. Matches up to corresponding text template with the same name.
*
* @default 'percent'
*/
label: 'percent' | 'ratio';
/**
* When incrementing without value, sets range for random increment value
*/
random: Progress.RandomSettings;
/**
* Decimal point precision for calculated progress
*
* @default 1
*/
precision: number;
/**
* Setting a total value will make each call to increment get closer to this total (i.e. 1/20, 2/20 etc)
*
* @default false
*/
total: false | number;
/**
* Sets current value, when total is specified, this is used to calculate a ratio of the total, with percent this should be the overall percent
*
* @default false
*/
value: false | number;
// endregion
// region Callbacks
/**
* Callback on percentage change
*/
onChange(this: JQuery, percent: number, value: number, total: number): void;
/**
* Callback on success state
*/
onSuccess(this: JQuery, total: number): void;
/**
* Callback on active state
*/
onActive(this: JQuery, value: number, total: number): void;
/**
* Callback on error state
*/
onError(this: JQuery, value: number, total: number): void;
/**
* Callback on warning state
*/
onWarning(this: JQuery, value: number, total: number): void;
// endregion
// region DOM Settings
/**
* Text content for each state, uses simple templating with {percent}, {value}, {total}
*/
text: Progress.TextSettings;
/**
* Regular expressions used by module
*/
regExp: Progress.RegExpSettings;
/**
* Selectors used by module
*/
selector: Progress.SelectorSettings;
/**
* DOM metadata used by module
*/
metadata: Progress.MetadataSettings;
/**
* Class names used to attach style to state
*/
className: Progress.ClassNameSettings;
// endregion
// region Debug Settings
error: Progress.ErrorSettings;
// endregion
// region Component Settings
// region DOM Settings
/**
* Event namespace. Makes sure module teardown does not effect other events attached to an element.
*/
namespace: string;
// endregion
// region Debug Settings
/**
* Name used in log statements
*/
name: string;
/**
* Silences all console output including error messages, regardless of other debug settings.
*/
silent: boolean;
/**
* Debug output to console
*/
debug: boolean;
/**
* Show console.table output with performance metrics
*/
performance: boolean;
/**
* Debug output includes all internal behaviors
*/
verbose: boolean;
// endregion
// endregion
}
}
namespace Progress {
type RandomSettings = RandomSettings.Param;
namespace RandomSettings {
type Param = (Pick<_Impl, 'min'> |
Pick<_Impl, 'max'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 2
*/
min: number;
/**
* @default 5
*/
max: number;
}
}
type TextSettings = TextSettings.Param;
namespace TextSettings {
type Param = (Pick<_Impl, 'active'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'success'> |
Pick<_Impl, 'warning'> |
Pick<_Impl, 'percent'> |
Pick<_Impl, 'ratio'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default false
*/
active: false | string;
/**
* @default false
*/
error: false | string;
/**
* @default false
*/
success: false | string;
/**
* @default false
*/
warning: false | string;
/**
* @default '{percent}%'
*/
percent: false | string;
/**
* @default '{value} of {total}'
*/
ratio: false | string;
}
}
type RegExpSettings = RegExpSettings.Param;
namespace RegExpSettings {
type Param = (Pick<_Impl, 'variable'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default /\{\$*[A-z0-9]+\}/g
*/
variable: RegExp;
}
}
type SelectorSettings = SelectorSettings.Param;
namespace SelectorSettings {
type Param = (Pick<_Impl, 'bar'> |
Pick<_Impl, 'label'> |
Pick<_Impl, 'progress'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default '> .bar
*/
bar: string;
/**
* @default '> .label'
*/
label: string;
/**
* @default '.bar > .progress'
*/
progress: string;
}
}
type MetadataSettings = MetadataSettings.Param;
namespace MetadataSettings {
type Param = (Pick<_Impl, 'percent'> |
Pick<_Impl, 'total'> |
Pick<_Impl, 'value'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'percent'
*/
percent: string;
/**
* @default 'total'
*/
total: string;
/**
* @default 'value'
*/
value: string;
}
}
type ClassNameSettings = ClassNameSettings.Param;
namespace ClassNameSettings {
type Param = (Pick<_Impl, 'active'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'success'> |
Pick<_Impl, 'warning'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'active'
*/
active: string;
/**
* @default 'error'
*/
error: string;
/**
* @default 'success'
*/
success: string;
/**
* @default 'warning'
*/
warning: string;
}
}
type ErrorSettings = ErrorSettings.Param;
namespace ErrorSettings {
type Param = (Pick<_Impl, 'method'> |
Pick<_Impl, 'nonNumeric'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'The method you called is not defined.'
*/
method: string;
/**
* @default 'Progress value is non numeric'
*/
nonNumeric: string;
}
}
}
} | the_stack |
import * as ts from 'typescript';
import * as path from 'path';
export function formatUrl(url: string) {
return url.replace(/\\/g, '/');
}
// try find declaration in root
export function tryFindDeclarationByName(sourceFile: ts.SourceFile, name: ts.EntityName): ts.Declaration {
let decl;
if (ts.isIdentifier(name)) {
const declName = name.getText();
sourceFile.statements.forEach(statement => {
if (decl) return;
if (hasName(statement) && getText(statement.name) === declName) {
decl = statement;
} else if (ts.isVariableStatement(statement)) {
decl = statement.declarationList.declarations.find(decl => getText(decl.name) === declName);
}
});
}
return decl;
}
export function formatName(name: string, upper?: boolean) {
name = name
.replace(/[\/\\.\@_-][a-z]/gi, s => s.substring(1).toUpperCase())
.replace(/\/|\\|\./g, '');
return upper
? (name[0].toUpperCase() + name.substring(1))
: name;
}
export function getTypeArguments(node: ts.TypeNode) {
return (node as ts.NodeWithTypeArguments).typeArguments;
}
export function getSymbol(node: ts.Node): ts.Symbol | undefined {
return (node as any).symbol;
}
export function hasName(node: ts.Node): node is ts.NamedDeclaration {
return !!(node as ts.NamedDeclaration).name;
}
export function getDeclarationBySymbol(symbol: ts.Symbol) {
return symbol.valueDeclaration || (symbol.declarations && symbol.declarations[0]);
}
export function getJSDocProp(node: ts.Node): ts.JSDoc[] | undefined {
return (node as any).jsDoc;
}
export function getJSDoc(node: ts.Node): ts.JSDoc | undefined {
const jsDocs = getJSDocs(node);
return jsDocs ? jsDocs[jsDocs.length - 1] : undefined;
}
export function getDeclarationMayHasJSDoc(node: ts.Node): ts.Node {
if (!getJSDocProp(node)) {
const symbol = getSymbol(node);
const declaration = symbol && getDeclarationBySymbol(symbol);
if (declaration) {
if (ts.isPropertyAccessExpression(declaration)) {
return declaration.parent.parent;
}
return declaration;
}
}
return node;
}
export function getJSDocs(node: ts.Node): ts.JSDoc[] | undefined {
const decl = getDeclarationMayHasJSDoc(node);
if (!decl) return;
const jsDocs = getJSDocProp(decl);
if (!jsDocs) {
const tags = ts.getJSDocTags(decl);
const jsDocArray: ts.JSDoc[] = [];
tags.forEach(tag => {
if (ts.isJSDoc(tag.parent) && !jsDocArray.includes(tag.parent)) {
jsDocArray.push(tag.parent);
}
});
return jsDocArray;
}
return jsDocs;
}
export function hasQuestionToken(node: ts.Node) {
return (node as any).questionToken !== undefined;
}
export function isDeclareModule(node: ts.Node): node is ts.ModuleDeclaration {
return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
}
export function formatIdentifierName(name: string) {
return name.replace(/^("|')|("|')$/g, '');
}
export function getText(node?: ts.Node) {
if (node) {
if (ts.isIdentifier(node)) {
return formatIdentifierName(node.text);
} else if (ts.isStringLiteral(node)) {
return node.text;
} else if (ts.isQualifiedName(node)) {
return getText(node.right);
}
}
return '';
}
// find js doc tag
export function findJsDocTag(node: ts.Node, name: string) {
const jsDocTags = ts.isJSDoc(node)
? node.tags
: ts.getJSDocTags(getDeclarationMayHasJSDoc(node));
return jsDocTags && jsDocTags.find(tag => getText(tag.tagName) === name);
}
// normalize d.ts url
export function normalizeDtsUrl(file: string) {
const ext = path.extname(file);
file += ext ? '' : '.d.ts';
return file;
}
// resolve url
export function resolveUrl(url: string) {
try {
return require.resolve(url);
} catch (e) {
return;
}
}
// check kind in node.modifiers.
export function modifierHas(node: ts.Node, kind) {
return node.modifiers && node.modifiers.find(mod => kind === mod.kind);
}
// find assign result type
export interface AssignElement {
init?: boolean;
obj?: ts.Expression;
key: ts.Identifier;
value?: ts.Expression;
node: ts.Node;
}
export interface ExportObj {
node: ts.Node;
originalNode: ts.Node;
}
// find exports from sourcefile
export function findExports(source: ts.SourceFile) {
let exportEqual: ExportObj | undefined;
const exportList: Map<string, ExportObj> = new Map();
const checker = getAssignChecker([
'exports',
'module',
'module.exports',
]);
const addExportNode = (name: string, value: ts.Node, node: ts.Node) => {
exportList.set(name, {
node: value!,
originalNode: node,
});
};
source.statements.forEach(statement => {
const isExport = modifierHas(statement, ts.SyntaxKind.ExportKeyword);
if (ts.isExportAssignment(statement)) {
if (statement.isExportEquals) {
// export = {}
exportEqual = {
node: statement.expression,
originalNode: statement,
};
} else {
// export default {}
addExportNode('default', statement.expression, statement);
}
return;
} else if (isExport && (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement))) {
if (modifierHas(statement, ts.SyntaxKind.DefaultKeyword)) {
// export default function() {} | export default class xx {}
addExportNode('default', statement, statement);
} else {
// export function xxx() {} | export class xx {}
addExportNode(getText(statement.name), statement, statement);
}
return;
} else if (ts.isExportDeclaration(statement) && statement.exportClause) {
// export { xxxx };
statement.exportClause.elements.forEach(spec => {
addExportNode(getText(spec.name), spec.propertyName || spec.name, statement);
});
return;
}
getAssignResultFromStatement(statement).forEach(result => {
const newResult = checker.check(result);
if (isExport) {
// export const xxx = {};
addExportNode(getText(result.key), result.value!, result.node);
}
if (!newResult) return;
if (newResult.name === 'exports' || newResult.name === 'module.exports') {
// exports.xxx = {} | module.exports.xxx = {}
addExportNode(getText(newResult.key), newResult.value, newResult.node);
} else if (newResult.name === 'module' && getText(newResult.key) === 'exports') {
// module.exports = {}
exportEqual = {
node: newResult.value!,
originalNode: newResult.node,
};
}
});
});
return {
exportEqual,
exportList,
};
}
export function findAssign(statements: ts.NodeArray<ts.Statement>, cb: (result: AssignElement) => void) {
statements.forEach(statement => {
getAssignResultFromStatement(statement).forEach(cb);
});
}
export function findAssignByName(statements, name: FindAssignNameType | FindAssignNameType[], cb: (result: AssignNameElement) => void) {
const checker = getAssignChecker(name);
return findAssign(statements, result => {
const newResult = checker.check(result);
if (newResult) cb(newResult);
});
}
type FindAssignNameType = string | RegExp;
interface AssignNameElement extends AssignElement {
obj: ts.Expression;
name: string;
value: ts.Expression;
}
export function getAssignChecker(name: FindAssignNameType | FindAssignNameType[]) {
// cache the variable of name
const variableList = Array.isArray(name) ? name : [ name ];
const nameAlias = {};
const getRealName = name => {
const realName = nameAlias[name] || name;
const hitTarget = !!variableList.find(variable => {
return (typeof variable === 'string')
? variable === realName
: variable.test(realName);
});
return hitTarget ? realName : undefined;
};
return {
check(el: AssignElement): AssignNameElement | undefined {
const { obj, key, value, node } = el;
if (!obj || !value) {
// const xx = name
if (value) {
const realName = getRealName(value.getText().trim());
if (realName) {
nameAlias[getText(key)] = realName;
}
}
return;
}
const realName = getRealName(obj.getText().trim());
if (realName) {
return { name: realName, obj, key, value, node };
}
},
};
}
export function getAssignResultFromStatement(statement: ts.Statement, assignList: AssignElement[] = []) {
const checkValue = (node?: ts.Expression) => {
if (node && ts.isBinaryExpression(node)) {
checkBinary(node);
return checkValue(node.right);
} else {
return node;
}
};
// check binary expression
const checkBinary = (node: ts.BinaryExpression) => {
if (
ts.isPropertyAccessExpression(node.left) &&
ts.isIdentifier(node.left.name)
) {
// xxx.xxx = xx
assignList.push({
obj: node.left.expression,
key: node.left.name,
value: checkValue(node.right),
node: statement,
});
} else if (ts.isIdentifier(node.left)) {
// xxx = xx
assignList.push({
key: node.left,
value: checkValue(node.right),
node: statement,
});
} else if (
ts.isElementAccessExpression(node.left) &&
ts.isStringLiteral(node.left.argumentExpression)
) {
// xxx['sss'] = xxx
assignList.push({
obj: node.left.expression,
key: ts.createIdentifier(node.left.argumentExpression.text),
value: checkValue(node.right),
node: statement,
});
}
};
const eachStatement = (statements: ts.NodeArray<ts.Statement>) => {
statements.forEach(statement => getAssignResultFromStatement(statement, assignList));
};
const checkIfStatement = (el: ts.IfStatement) => {
if (ts.isBlock(el.thenStatement)) {
eachStatement(el.thenStatement.statements);
}
if (el.elseStatement) {
if (ts.isIfStatement(el.elseStatement)) {
checkIfStatement(el.elseStatement);
} else if (ts.isBlock(el.elseStatement)) {
eachStatement(el.elseStatement.statements);
}
}
};
if (ts.isExpressionStatement(statement) && ts.isBinaryExpression(statement.expression)) {
// xxx = xxx
checkBinary(statement.expression);
} else if (ts.isVariableStatement(statement)) {
// const xxx = xx
statement.declarationList.declarations.forEach(declare => {
if (ts.isIdentifier(declare.name)) {
assignList.push({
init: true,
key: declare.name,
value: checkValue(declare.initializer),
node: declare,
});
}
});
} else if (ts.isIfStatement(statement)) {
// if () { xxx = xxx }
checkIfStatement(statement);
}
return assignList;
} | the_stack |
import { Bridge } from "../bridge";
import { get as getLogger } from "./logging";
import PQueue from "p-queue";
import { Counter, Gauge } from "prom-client";
const log = getLogger("MembershipQueue");
export interface ThinRequest {
getId(): string;
}
interface QueueUserItem {
type: "join"|"leave";
kickUser?: string;
reason?: string;
attempts: number;
roomId: string;
userId: string;
retry: boolean;
req: ThinRequest;
ts: number;
ttl: number;
}
export interface MembershipQueueOpts {
/**
* The number of concurrent operations to perform.
*/
concurrentRoomLimit?: number;
/**
* The number of attempts to retry an operation before it is discarded.
*/
maxAttempts?: number;
/**
* @deprecated Use `actionDelayMs`
*/
joinDelayMs?: number;
/**
* How long to delay a request for in milliseconds, multiplied by the number of attempts made
* if a request failed.
*/
actionDelayMs?: number;
/**
* @deprecated Use `maxActionDelayMs`
*/
maxJoinDelayMs?: number;
/**
* The maximum number of milliseconds a request may be delayed for.
*/
maxActionDelayMs?: number;
/**
* How long a request can "live" for before it is discarded in
* milliseconds. This will override `maxAttempts`.
*/
defaultTtlMs?: number;
}
/**
* Default values used by the queue if not specified.
*/
export const DEFAULT_OPTS: MembershipQueueOptsWithDefaults = {
concurrentRoomLimit: 8,
maxAttempts: 10,
actionDelayMs: 500,
maxActionDelayMs: 30 * 60 * 1000, // 30 mins
defaultTtlMs: 2 * 60 * 1000, // 2 mins
};
interface MembershipQueueOptsWithDefaults extends MembershipQueueOpts {
maxActionDelayMs: number;
actionDelayMs: number;
concurrentRoomLimit: number;
defaultTtlMs: number;
maxAttempts: number;
}
/**
* This class sends membership changes for rooms in a linearized queue.
* The queue is lineaized based upon the hash value of the roomId, so that two
* operations for the same roomId may never happen concurrently.
*/
export class MembershipQueue {
private queues: Map<number, PQueue> = new Map();
private pendingGauge?: Gauge<"type"|"instance_id">;
private processedCounter?: Counter<"type"|"instance_id"|"outcome">;
private failureReasonCounter?: Counter<"errcode"|"http_status"|"type">;
private ageOfLastProcessedGauge?: Gauge<string>;
private opts: MembershipQueueOptsWithDefaults;
constructor(private bridge: Bridge, opts: MembershipQueueOpts) {
this.opts = { ...DEFAULT_OPTS, ...opts};
for (let i = 0; i < this.opts.concurrentRoomLimit; i++) {
this.queues.set(i, new PQueue({
autoStart: true,
concurrency: 1,
}));
}
if (opts.actionDelayMs === undefined && opts.joinDelayMs) {
log.warn("MembershipQueue configured with deprecated config option `joinDelayMs`. Use `actionDelayMs`");
this.opts.actionDelayMs = opts.joinDelayMs;
}
if (opts.maxActionDelayMs === undefined && opts.maxJoinDelayMs) {
log.warn(
"MembershipQueue configured with deprecated config option `maxJoinDelayMs`. Use `maxActionDelayMs`"
);
this.opts.maxActionDelayMs = opts.maxJoinDelayMs;
}
}
/**
* This should be called after starting the bridge in order
* to track metrics for the membership queue.
*/
public registerMetrics() {
const metrics = this.bridge.getPrometheusMetrics(false);
this.pendingGauge = metrics.addGauge({
name: "membershipqueue_pending",
help: "Count of membership actions in the queue by type",
labels: ["type"]
});
this.processedCounter = metrics.addCounter({
name: "membershipqueue_processed",
help: "Count of membership actions processed by type and outcome",
labels: ["type", "outcome"],
});
this.failureReasonCounter = metrics.addCounter({
name: "membershipqueue_reason",
help: "Count of failures to process membership by type, matrix errcode and http statuscode",
labels: ["type", "errcode", "http_status"],
});
this.ageOfLastProcessedGauge = metrics.addGauge({
name: "membershipqueue_lastage",
help: "Gauge to measure the age of the last processed event",
});
}
/**
* Join a user to a room
* @param roomId The roomId to join
* @param userId Leave empty to act as the bot user.
* @param req The request entry for logging context
* @param retry Should the request retry if it fails
* @param ttl How long should this request remain queued in milliseconds
* before it's discarded. Defaults to `opts.defaultTtlMs`
* @returns A promise that resolves when the membership has completed
*/
public async join(roomId: string, userId: string|undefined, req: ThinRequest, retry = true, ttl?: number) {
return this.queueMembership({
roomId,
userId: userId || this.bridge.botUserId,
retry,
req,
attempts: 0,
type: "join",
ts: Date.now(),
ttl: ttl || this.opts.defaultTtlMs,
});
}
/**
* Leave OR kick a user from a room
* @param roomId The roomId to leave
* @param userId Leave empty to act as the bot user.
* @param req The request entry for logging context
* @param retry Should the request retry if it fails
* @param reason Reason for leaving/kicking
* @param kickUser The user to be kicked. If left blank, this will be a leave.
* @param ttl How long should this request remain queued in milliseconds
* before it's discarded. Defaults to `opts.defaultTtlMs`
* @returns A promise that resolves when the membership has completed
*/
public async leave(roomId: string, userId: string, req: ThinRequest,
retry = true, reason?: string, kickUser?: string,
ttl?: number) {
return this.queueMembership({
roomId,
userId: userId || this.bridge.botUserId,
retry,
req,
attempts: 0,
reason,
kickUser,
type: "leave",
ts: Date.now(),
ttl: ttl || this.opts.defaultTtlMs,
})
}
public async queueMembership(item: QueueUserItem) {
try {
const queue = this.queues.get(this.hashRoomId(item.roomId));
if (!queue) {
throw Error("Could not find queue for hash");
}
this.pendingGauge?.inc({
type: item.kickUser ? "kick" : item.type
});
return queue.add(() => this.serviceQueue(item));
}
catch (ex) {
log.error(`Failed to handle membership: ${ex}`);
throw ex;
}
}
private hashRoomId(roomId: string) {
return Array.from(roomId).map((s) => s.charCodeAt(0)).reduce((a, b) => a + b, 0)
% this.opts.concurrentRoomLimit;
}
private async serviceQueue(item: QueueUserItem) {
const { req, roomId, userId, reason, kickUser, attempts, type, ttl, ts } = item;
const age = Date.now() - ts;
if (age > ttl) {
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "dead",
});
this.pendingGauge?.dec({
type: kickUser ? "kick" : type
});
throw Error('Request failed. TTL exceeded');
}
const reqIdStr = req.getId() ? `[${req.getId()}]`: "";
log.debug(`${reqIdStr} ${userId}@${roomId} -> ${type} (reason: ${reason || "none"}, kicker: ${kickUser})`);
const intent = this.bridge.getIntent(kickUser || userId);
this.ageOfLastProcessedGauge?.set(age);
try {
if (type === "join") {
await intent.join(roomId);
}
else if (kickUser) {
await intent.kick(roomId, userId, reason);
}
else {
await intent.leave(roomId, reason);
}
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "success",
});
}
catch (ex) {
if (ex.body.errcode || ex.statusCode) {
this.failureReasonCounter?.inc({
type: kickUser ? "kick" : type,
errcode: ex.body.errcode || "none",
http_status: ex.statusCode || "none"
});
}
if (!this.shouldRetry(ex, attempts)) {
this.processedCounter?.inc({
type: kickUser ? "kick" : type,
outcome: "fail",
});
throw ex;
}
const delay = Math.min(
(this.opts.actionDelayMs * attempts) + (Math.random() * 500),
this.opts.actionDelayMs
);
log.warn(`${reqIdStr} Failed to ${type} ${roomId}, delaying for ${delay}ms`);
log.debug(`${reqIdStr} Failed with: ${ex.body.errcode} ${ex.message}`);
await new Promise((r) => setTimeout(r, delay));
this.queueMembership({...item, attempts: attempts + 1}).catch((innerEx) => {
log.error(`Failed to handle membership change:`, innerEx);
});
}
finally {
this.pendingGauge?.dec({
type: kickUser ? "kick" : type
});
}
}
private shouldRetry(ex: {body: {code: string; errcode: string;}, statusCode: number}, attempts: number): boolean {
return !(
attempts === this.opts.maxAttempts ||
ex.body.errcode === "M_FORBIDDEN" ||
ex.statusCode === 403
);
}
} | the_stack |
import { PermissionStatus, PermissionResponse, PermissionHookOptions } from 'expo-modules-core';
import { LocationAccuracy, LocationCallback, LocationGeocodedAddress, LocationGeocodedLocation, LocationHeadingCallback, LocationHeadingObject, LocationLastKnownOptions, LocationObject, LocationOptions, LocationPermissionResponse, LocationProviderStatus, LocationRegion, LocationSubscription, LocationTaskOptions, LocationActivityType, LocationGeofencingEventType, LocationGeofencingRegionState, LocationGeocodingOptions } from './Location.types';
import { LocationEventEmitter } from './LocationEventEmitter';
import { setGoogleApiKey } from './LocationGoogleGeocoding';
import { _getCurrentWatchId } from './LocationSubscribers';
/**
* Check status of location providers.
* @return A promise which fulfills with an object of type [LocationProviderStatus](#locationproviderstatus).
*/
export declare function getProviderStatusAsync(): Promise<LocationProviderStatus>;
/**
* Asks the user to turn on high accuracy location mode which enables network provider that uses
* Google Play services to improve location accuracy and location-based services.
* @return A promise resolving as soon as the user accepts the dialog. Rejects if denied.
*/
export declare function enableNetworkProviderAsync(): Promise<void>;
/**
* Requests for one-time delivery of the user's current location.
* Depending on given `accuracy` option it may take some time to resolve,
* especially when you're inside a building.
* > __Note:__ Calling it causes the location manager to obtain a location fix which may take several
* > seconds. Consider using [`Location.getLastKnownPositionAsync`](#locationgetlastknownpositionasyncoptions)
* > if you expect to get a quick response and high accuracy is not required.
* @param options
* @return A promise which fulfills with an object of type [`LocationObject`](#locationobject).
*/
export declare function getCurrentPositionAsync(options?: LocationOptions): Promise<LocationObject>;
/**
* Gets the last known position of the device or `null` if it's not available or doesn't match given
* requirements such as maximum age or required accuracy.
* It's considered to be faster than `getCurrentPositionAsync` as it doesn't request for the current
* location, but keep in mind the returned location may not be up-to-date.
* @param options
* @return A promise which fulfills with an object of type [LocationObject](#locationobject) or
* `null` if it's not available or doesn't match given requirements such as maximum age or required
* accuracy.
*/
export declare function getLastKnownPositionAsync(options?: LocationLastKnownOptions): Promise<LocationObject | null>;
/**
* Subscribe to location updates from the device. Please note that updates will only occur while the
* application is in the foreground. To get location updates while in background you'll need to use
* [Location.startLocationUpdatesAsync](#locationstartlocationupdatesasynctaskname-options).
* @param options
* @param callback This function is called on each location update. It receives an object of type
* [`LocationObject`](#locationobject) as the first argument.
* @return A promise which fulfills with a [`LocationSubscription`](#locationsubscription) object.
*/
export declare function watchPositionAsync(options: LocationOptions, callback: LocationCallback): Promise<LocationSubscription>;
/**
* Gets the current heading information from the device. To simplify, it calls `watchHeadingAsync`
* and waits for a couple of updates, and then returns the one that is accurate enough.
* @return A promise which fulfills with an object of type [LocationHeadingObject](#locationheadingobject).
*/
export declare function getHeadingAsync(): Promise<LocationHeadingObject>;
/**
* Subscribe to compass updates from the device.
* @param callback This function is called on each compass update. It receives an object of type
* [LocationHeadingObject](#locationheadingobject) as the first argument.
* @return A promise which fulfills with a [`LocationSubscription`](#locationsubscription) object.
*/
export declare function watchHeadingAsync(callback: LocationHeadingCallback): Promise<LocationSubscription>;
/**
* Geocode an address string to latitude-longitude location.
* > **Note**: Geocoding is resource consuming and has to be used reasonably. Creating too many
* > requests at a time can result in an error, so they have to be managed properly.
* > It's also discouraged to use geocoding while the app is in the background and its results won't
* > be shown to the user immediately.
*
* > On Android, you must request a location permission (`Permissions.LOCATION`) from the user
* > before geocoding can be used.
* @param address A string representing address, eg. `"Baker Street London"`.
* @param options
* @return A promise which fulfills with an array (in most cases its size is 1) of [`LocationGeocodedLocation`](#locationgeocodedlocation) objects.
*/
export declare function geocodeAsync(address: string, options?: LocationGeocodingOptions): Promise<LocationGeocodedLocation[]>;
/**
* Reverse geocode a location to postal address.
* > **Note**: Geocoding is resource consuming and has to be used reasonably. Creating too many
* > requests at a time can result in an error, so they have to be managed properly.
* > It's also discouraged to use geocoding while the app is in the background and its results won't
* > be shown to the user immediately.
*
* > On Android, you must request a location permission (`Permissions.LOCATION`) from the user
* > before geocoding can be used.
* @param location An object representing a location.
* @param options
* @return A promise which fulfills with an array (in most cases its size is 1) of [`LocationGeocodedAddress`](#locationgeocodedaddress) objects.
*/
export declare function reverseGeocodeAsync(location: Pick<LocationGeocodedLocation, 'latitude' | 'longitude'>, options?: LocationGeocodingOptions): Promise<LocationGeocodedAddress[]>;
/**
* Checks user's permissions for accessing location.
* @return A promise that fulfills with an object of type [LocationPermissionResponse](#locationpermissionresponse).
* @deprecated __Deprecated.__ Use [`getForegroundPermissionsAsync`](#locationgetforegroundpermissionsasync) or [`getBackgroundPermissionsAsync`](#locationgetbackgroundpermissionsasync) instead.
*/
export declare function getPermissionsAsync(): Promise<LocationPermissionResponse>;
/**
* Asks the user to grant permissions for location.
* @return A promise that fulfills with an object of type [LocationPermissionResponse](#locationpermissionresponse).
* @deprecated __Deprecated.__ Use [`requestForegroundPermissionsAsync`](#locationrequestforegroundpermissionsasync) or [`requestBackgroundPermissionsAsync`](#locationrequestbackgroundpermissionsasync) instead.
*/
export declare function requestPermissionsAsync(): Promise<LocationPermissionResponse>;
/**
* Checks user's permissions for accessing location while the app is in the foreground.
* @return A promise that fulfills with an object of type [PermissionResponse](#permissionresponse).
*/
export declare function getForegroundPermissionsAsync(): Promise<LocationPermissionResponse>;
/**
* Asks the user to grant permissions for location while the app is in the foreground.
* @return A promise that fulfills with an object of type [PermissionResponse](#permissionresponse).
*/
export declare function requestForegroundPermissionsAsync(): Promise<LocationPermissionResponse>;
/**
* Check or request permissions for the foreground location.
* This uses both `requestForegroundPermissionsAsync` and `getForegroundPermissionsAsync` to interact with the permissions.
*
* @example
* ```ts
* const [status, requestPermission] = Location.useForegroundPermissions();
* ```
*/
export declare const useForegroundPermissions: (options?: PermissionHookOptions<object> | undefined) => [LocationPermissionResponse | null, () => Promise<LocationPermissionResponse>, () => Promise<LocationPermissionResponse>];
/**
* Checks user's permissions for accessing location while the app is in the background.
* @return A promise that fulfills with an object of type [PermissionResponse](#permissionresponse).
*/
export declare function getBackgroundPermissionsAsync(): Promise<PermissionResponse>;
/**
* Asks the user to grant permissions for location while the app is in the background.
* On __Android 11 or higher__: this method will open the system settings page - before that happens
* you should explain to the user why your application needs background location permission.
* For example, you can use `Modal` component from `react-native` to do that.
* > __Note__: Foreground permissions should be granted before asking for the background permissions
* (your app can't obtain background permission without foreground permission).
* @return A promise that fulfills with an object of type [PermissionResponse](#permissionresponse).
*/
export declare function requestBackgroundPermissionsAsync(): Promise<PermissionResponse>;
/**
* Check or request permissions for the foreground location.
* This uses both `requestBackgroundPermissionsAsync` and `getBackgroundPermissionsAsync` to
* interact with the permissions.
*
* @example
* ```ts
* const [status, requestPermission] = Location.useBackgroundPermissions();
* ```
*/
export declare const useBackgroundPermissions: (options?: PermissionHookOptions<object> | undefined) => [PermissionResponse | null, () => Promise<PermissionResponse>, () => Promise<PermissionResponse>];
/**
* Checks whether location services are enabled by the user.
* @return A promise which fulfills to `true` if location services are enabled on the device,
* or `false` if not.
*/
export declare function hasServicesEnabledAsync(): Promise<boolean>;
export declare function isBackgroundLocationAvailableAsync(): Promise<boolean>;
/**
* Registers for receiving location updates that can also come when the app is in the background.
* @param taskName Name of the task receiving location updates.
* @param options An object of options passed to the location manager.
* @return A promise resolving once the task with location updates is registered.
*
* # Task parameters
*
* Background location task will be receiving following data:
* - `locations` - An array of the new locations.
*
* ```ts
* import * as TaskManager from 'expo-task-manager';
*
* TaskManager.defineTask(YOUR_TASK_NAME, ({ data: { locations }, error }) => {
* if (error) {
* // check `error.message` for more details.
* return;
* }
* console.log('Received new locations', locations);
* });
* ```
*/
export declare function startLocationUpdatesAsync(taskName: string, options?: LocationTaskOptions): Promise<void>;
/**
* Stops geofencing for specified task.
* @param taskName Name of the background location task to stop.
* @return A promise resolving as soon as the task is unregistered.
*/
export declare function stopLocationUpdatesAsync(taskName: string): Promise<void>;
/**
* @param taskName Name of the location task to check.
* @return A promise which fulfills with boolean value indicating whether the location task is
* started or not.
*/
export declare function hasStartedLocationUpdatesAsync(taskName: string): Promise<boolean>;
/**
* Starts geofencing for given regions. When the new event comes, the task with specified name will
* be called with the region that the device enter to or exit from.
* If you want to add or remove regions from already running geofencing task, you can just call
* `startGeofencingAsync` again with the new array of regions.
* @param taskName Name of the task that will be called when the device enters or exits from specified regions.
* @param regions Array of region objects to be geofenced.
* @return A promise resolving as soon as the task is registered.
*
* # Task parameters
*
* Geofencing task will be receiving following data:
* - `eventType` - Indicates the reason for calling the task, which can be triggered by entering or exiting the region.
* See [GeofencingEventType](#geofencingeventtype).
* - `region` - Object containing details about updated region. See [LocationRegion](#locationregion) for more details.
*
* # Example
* ```ts
* import { GeofencingEventType } from 'expo-location';
* import * as TaskManager from 'expo-task-manager';
*
* TaskManager.defineTask(YOUR_TASK_NAME, ({ data: { eventType, region }, error }) => {
* if (error) {
* // check `error.message` for more details.
* return;
* }
* if (eventType === GeofencingEventType.Enter) {
* console.log("You've entered region:", region);
* } else if (eventType === GeofencingEventType.Exit) {
* console.log("You've left region:", region);
* }
* });
* ```
*/
export declare function startGeofencingAsync(taskName: string, regions?: LocationRegion[]): Promise<void>;
/**
* Stops geofencing for specified task. It unregisters the background task so the app will not be
* receiving any updates, especially in the background.
* @param taskName Name of the task to unregister.
* @return A promise resolving as soon as the task is unregistered.
*/
export declare function stopGeofencingAsync(taskName: string): Promise<void>;
/**
* @param taskName Name of the geofencing task to check.
* @return A promise which fulfills with boolean value indicating whether the geofencing task is
* started or not.
*/
export declare function hasStartedGeofencingAsync(taskName: string): Promise<boolean>;
export { LocationEventEmitter as EventEmitter, _getCurrentWatchId };
export { LocationAccuracy as Accuracy, LocationActivityType as ActivityType, LocationGeofencingEventType as GeofencingEventType, LocationGeofencingRegionState as GeofencingRegionState, PermissionStatus, PermissionHookOptions, setGoogleApiKey, };
export { installWebGeolocationPolyfill } from './GeolocationPolyfill';
export * from './Location.types'; | the_stack |
module TDev {
export class LayoutMgr {
static instance: LayoutMgr = new LayoutMgr();
// Set in initAsync(), default.str
public onBoxSelected: () => void = () => { };
public onRendered: () => void = () => { };
public numBoxes: number = 0;
public changedtext: string;
boxes: BoxBase[];
rootBox: BoxBase;
//relayoutingBoxes: WallBox[];
rootElement: HTMLElement;
scrollspeculation = true;
pcTable: any;
currentAstNodeId = "";
selectedBox: BoxBase = null;
boxMenu: HTMLElement = null;
//originalX: number;
//originalY: number;
minimumScale: number;
maximumScale: number;
scale: number; // TODO: should be reset after loading the script.
scrollTop: number = undefined;
scrollLeft: number = undefined;
// zoomfactor: number = undefined;
public editMode: boolean;
public sideview = false;
public updateEditMode(rt: Runtime) {
// Set edit mode to true,
// if the script is stopped or is running in live mode.
this.editMode = rt.liveViewSupported() && (rt.isStopped() || rt.liveMode());
// Dive into the edit mode!
if (this.editMode) {
} else {
// Get out of the edit mode...
if (this.currentAstNodeId) {
this.clearRelatedBoxes();
}
if (this.selectedBox !== null) {
this.unselectBox();
}
this.adjustForNormalView();
}
if (!!this.rootBox)
this.updateRootElement();
//if (!!this.rootBox) {
// this.boxes.forEach((box: WallBox) =>
// { box.setEditMode(editMode); });
// }
}
private static renderexecutionmode = false;
public static RenderExecutionMode(): boolean { return LayoutMgr.renderexecutionmode; }
public static SetRenderExecutionMode(val: boolean) { LayoutMgr.renderexecutionmode = val; }
private static needrelayout = false;
public static QueueReLayout() {
// keep it simple... do it immediately.
//if (!LayoutMgr.renderexecutionmode && LayoutMgr.instance.rootBox) {
// LayoutMgr.instance.CoreLayout();
//}
var check = () => {
if (LayoutMgr.needrelayout) {
if (!LayoutMgr.renderexecutionmode && LayoutMgr.instance.rootBox) {
LayoutMgr.instance.CoreLayout();
LayoutMgr.needrelayout = false;
} else
TDev.Util.setTimeout(100, check);
}
};
if (!LayoutMgr.needrelayout) {
LayoutMgr.needrelayout = true;
TDev.Util.setTimeout(50, check);
}
}
// functions for altering scroll behavior of top elements (switching between live view and actual view)
public adjustForSideView() {
// DUAL-TODO: remove?
if (!this.sideview) {
this.rootElement.style.overflow = "auto";
this.rootElement.style.msContentZooming = "zoom";
if (this.rootBox instanceof WallBox)
(<WallBox>this.rootBox).setRenderedSideView(true);
this.updateRootElement();
this.sideview = true;
}
}
public adjustForNormalView() {
// DUAL-TODO: remove?
if (this.sideview) {
var rootelt = this.rootElement;
rootelt.style.overflow = "";
rootelt.style.msContentZooming = "";
rootelt.scrollTop = 0;
rootelt.scrollLeft = 0;
rootelt.msContentZoomFactor = 1;
if (this.rootBox instanceof WallBox)
(<WallBox>this.rootBox).setRenderedSideView(false);
this.updateRootElement();
this.sideview = false;
}
}
//private static TestAndClear(): boolean {
// var n = needrelayout;
// needrelayout = false;
// return n;
//}
// typing activity - we use this to catch race behavior on keystrokes
public lastbox_edited: string;
public FlagTypingActivity(id: string) { this.lastbox_edited = id; }
public ClearTypingActivity(id: string) { if (this.lastbox_edited === id) this.lastbox_edited = undefined; }
public CheckTypingActivity(id: string) { return this.lastbox_edited === id; }
static lazyInitCurrentRanderBox = () => {};
static htmlTagName:string;
static createOrRecycleContainerBoxDelayed(rt: Runtime, cur: BoxBase) {
var pc = rt.getTopScriptPc();
LayoutMgr.lazyInitCurrentRanderBox = () => {
LayoutMgr.lazyInitCurrentRanderBox = () => {};
var tag = LayoutMgr.htmlTagName || "div";
LayoutMgr.htmlTagName = undefined;
var w = WallBox.CreateOrRecycleContainerBox(rt, cur, pc, tag)
LayoutMgr.currentbox = w;
}
LayoutMgr.currentbox = null;
}
static setHtmlTagName(name:string) {
if (LayoutMgr.currentbox)
Util.userError(lf("you cannot set the HTML tag name here"))
LayoutMgr.htmlTagName = name;
}
static currentbox: BoxBase;
static getCurrentRenderBox(): BoxBase {
LayoutMgr.lazyInitCurrentRanderBox()
return LayoutMgr.currentbox;
}
static setCurrentRenderBox(box: BoxBase) {
LayoutMgr.lazyInitCurrentRanderBox()
LayoutMgr.currentbox = box;
}
public findFirstBoxByNodeId(astNodeId: string): WallBox {
if (!this.pcTable) return null;
var box = this.pcTable[astNodeId];
return box === undefined ? null : box;
}
public findAllBoxesByNodeId(astNodeId: string): WallBox[] {
var boxes = [];
if (this.boxes) this.boxes.forEach((box: WallBox) => {
if (box.getAstNodeId() === astNodeId) boxes.push(box);
});
return boxes;
}
public findAllBoxesByPropertyNodeId(astNodeId: string): WallBox[] {
var boxes = [];
if (this.boxes) this.boxes.forEach((box: WallBox) => {
var pcTable = box.pcTable;
for (var propName in pcTable) {
if (pcTable[propName] === astNodeId) {
boxes.push(box);
break;
}
}
});
return boxes;
}
public getSelectedBox(): BoxBase {
return this.selectedBox;
}
public setCurrentId(astNodeId: string) {
this.currentAstNodeId = astNodeId;
}
public getCurrentId(): string {
return this.currentAstNodeId;
}
// GUI selection
public selectBox(box: BoxBase): boolean {
if (this.selectedBox !== null) {
// Skip this box? (propagate to the parent box.)
var parent: BoxBase = box;
while (parent !== null) {
if (parent === this.selectedBox)
return false;
parent = <WallBox> parent.parent;
}
// Cancel previous selection.
this.unselectBox();
}
// Clear other highlights
if (this.currentAstNodeId)
this.clearRelatedBoxes();
// If the selected box is the root or a single child in a non-root box, cancel selection.
if (!box || box.depth <= 0
|| (box.isSingleChild && box.isLeaf() && box.depth > 1))
return false;
this.selectedBox = box;
this.highlightSelectedBox();
//Util.log("box is selected" + box);
// Show the menu.
if (this.onBoxSelected)
this.onBoxSelected();
return true;
}
public showBoxMenu(cb: () =>void ) {
var editButton = HTML.mkRoundButton("svg:edit,currentColor", lf("edit"), Ticks.wallEdit, () => {
if (cb) cb();
});
this.boxMenu = div("wall-selected", [editButton]);
this.refreshBoxMenu();
}
public refreshBoxMenu() {
if (this.boxMenu !== null) {
this.updateBoxMenuPosition();
this.rootElement.appendChild(this.boxMenu);
this.checkBoxMenuPosition();
}
}
public hideBoxMenu() {
if (this.boxMenu !== null) {
Animation.fadeOut(this.boxMenu).begin();
this.boxMenu = null;
}
}
private updateBoxMenuPosition() {
if (this.selectedBox === null || this.boxMenu === null)
return;
var box = this.selectedBox;
var offset = Util.offsetIn(box.element, this.rootElement);
var renderedScale = 1; // This is not 1 when the wall is scaled by transformation matrix.
var viewWidth = this.rootElement.clientWidth, viewHeight = this.rootElement.clientHeight;
var boxWidth = box.getRenderedWidth() * renderedScale, boxHeight = box.getRenderedHeight() * renderedScale;
var viewLeft = offset.x * renderedScale, viewTop = offset.y * renderedScale;
var margin = SizeMgr.topFontSize * 0.2;
// Show it on the right side.
if (viewLeft + boxWidth / 2 < viewWidth / 2) {
this.boxMenu.style.right = "auto";
this.boxMenu.style.left = (viewLeft + boxWidth + margin) + "px";
// Show it on the left side.
} else {
this.boxMenu.style.left = "auto";
this.boxMenu.style.right = (viewWidth - (viewLeft - margin)) + "px";
}
// Show it on the lower side.
if (viewTop + boxHeight / 2 < viewHeight / 2) {
this.boxMenu.style.bottom = "auto";
this.boxMenu.style.top = viewTop + "px";
// Show it on the upper side.
} else {
this.boxMenu.style.top = "auto";
this.boxMenu.style.bottom = (viewHeight - (viewTop + boxHeight)) + "px";
}
}
private checkBoxMenuPosition() {
if (this.boxMenu === null)
return;
var box = this.selectedBox;
var offset = Util.offsetIn(this.boxMenu, this.rootElement);
var renderedScale = 1; // This is not 1 when the wall is scaled by transformation matrix.
var viewWidth = this.rootElement.clientWidth, viewHeight = this.rootElement.clientHeight;
var menuWidth = this.boxMenu.clientWidth * renderedScale, menuHeight = this.boxMenu.clientHeight * renderedScale;
var viewLeft = offset.x * renderedScale - this.rootElement.scrollLeft, viewTop = offset.y * renderedScale - this.rootElement.scrollTop;
var viewRight = viewLeft + menuWidth, viewBottom = viewTop + menuHeight;
// Stick to the left edge.
if (viewLeft < 0) {
this.boxMenu.style.left = "0px";
this.boxMenu.style.right = "auto";
// Stick to the right edge.
} else if (viewRight > viewWidth) {
this.boxMenu.style.right = "0px";
this.boxMenu.style.left = "auto";
}
// Stick to the top edge.
if (viewTop < 0) {
this.boxMenu.style.top = "0px";
this.boxMenu.style.bottom = "auto";
// Stick to the bottom edge.
} else if (viewBottom > viewHeight) {
this.boxMenu.style.bottom = "0px";
this.boxMenu.style.top = "auto";
}
}
public unselectBox() {
if (this.selectedBox !== null) {
this.findAllBoxesByNodeId(this.selectedBox.getAstNodeId())
.forEach((box: BoxBase) => {
box.clearHighlight();
});
this.selectedBox = null;
this.hideBoxMenu();
}
}
public highlightSelectedBox() {
if (this.selectedBox !== null) {
this.selectedBox.setHighlight();
this.scrollToShow(this.selectedBox);
this.findAllBoxesByNodeId(this.selectedBox.getAstNodeId())
.forEach((box: WallBox) => {
if (this.selectedBox !== box)
box.setHighlight(false);
});
}
}
public highlightRelatedBoxes() {
if (this.selectedBox !== null)
this.unselectBox();
if (this.currentAstNodeId) {
var firstBox = this.findFirstBoxByNodeId(this.currentAstNodeId);
if (firstBox !== null) {
firstBox.setHighlight();
this.selectedBox = firstBox;
}
this.findAllBoxesByPropertyNodeId(this.currentAstNodeId)
.forEach((box: WallBox) => {
if (firstBox !== box)
box.setHighlight(false);
});
}
}
private clearRelatedBoxes() {
if (this.currentAstNodeId) {
this.findAllBoxesByPropertyNodeId(this.currentAstNodeId)
.forEach((box: WallBox) => {
box.clearHighlight();
});
}
this.currentAstNodeId = "";
}
public updateslider: (zoom: number, adjustscroll: boolean) => void;
public createZoomingUI(): HTMLElement {
var scaleSpan = span(null, "");
var scaleSliderCursor = div("cursor");
var scaleSlider = div("slider", [scaleSliderCursor]);
this.updateslider = (zoom: number, adjustscroll:boolean) => {
var oldScale = this.scale;
this.scale = Math.max(this.minimumScale, Math.min(zoom, this.maximumScale));
scaleSliderCursor.style.top = "0";
scaleSliderCursor.style.left = (scaleSlider.clientWidth - scaleSliderCursor.clientWidth)
* this.fromZoomToSliderValue(this.scale) + "px";
scaleSpan.setChildren([Math.round(this.scale * 100).toString() + "%"]);
if (adjustscroll) {
this.updateScaling(this.scale);
if (this.scrollTop !== undefined) {
// Zoom in the center part of the live view.
this.scrollTop = this.scrollTop * this.scale / oldScale + this.rootElement.offsetHeight / 2 * (this.scale / oldScale - 1);
this.scrollLeft = this.scrollLeft * this.scale / oldScale + this.rootElement.offsetWidth / 2 * (this.scale / oldScale - 1);
this.recoverScroll();
}
}
};
new DragHandler(scaleSliderCursor, (e, dx, dy) => {
var pos = Util.offsetIn(scaleSliderCursor, scaleSlider);
var max = scaleSlider.clientWidth - scaleSliderCursor.clientWidth;
this.updateslider(this.fromSliderValueToZoom(pos.x / max), true);
});
var zoomOutButton = HTML.mkButtonElt("wall-zoom-out", "-");
zoomOutButton.withClick(() => {
this.updateslider(this.scale * 0.9, true);
});
var zoomInButton = HTML.mkButtonElt("wall-zoom-in", "+");
zoomInButton.withClick(() => {
this.updateslider(this.scale * 1.1, true);
});
var ui = div("wall-zoom", scaleSpan, zoomOutButton, scaleSlider, zoomInButton);
return ui
}
private fromSliderValueToZoom(value: number): number {
return this.minimumScale * Math.exp(Math.log(this.maximumScale / this.minimumScale) * value);
}
private fromZoomToSliderValue(zoom: number): number {
return this.minimumScale >= this.maximumScale ? 1 : Math.log(zoom / this.minimumScale) / Math.log(this.maximumScale / this.minimumScale);
}
public getRootElement() {
return this.rootElement;
}
public getRootBox() {
return this.rootBox;
}
public updateRootElement() {
this.rootElement.setAttribute("livemode", this.editMode ? "true" : "false");
}
private calcDefaultScaling() {
if (this.sideview) {
if (this.scale === undefined || isNaN(this.scale)) {
var horizontalScale =
this.rootElement.offsetWidth / this.rootBox.element.offsetWidth;
var verticalScale =
this.rootElement.offsetHeight / this.rootBox.element.offsetHeight;
this.minimumScale = Math.min(horizontalScale, verticalScale) * 0.5;
this.maximumScale = this.minimumScale * 100;
var defaultScale = Math.max(horizontalScale, verticalScale);
this.scale = defaultScale;
this.updateScaling(this.scale);
}
}
else {
this.updateScaling(1);
}
}
private updateScaling(scale: number) {
if (this.sideview && this.rootElement.msContentZoomFactor) {
Util.setTransform(this.rootBox.element, "scale(" + this.minimumScale*10 + ", " + this.minimumScale*10 + ")", "0% 0%");
this.rootElement.msContentZoomFactor = scale / (this.minimumScale*10);
this.rootElement.style.msContentZoomLimit = "10% 1000%";
}
else {
Util.setTransform(this.rootBox.element, "scale(" + scale + ", " + scale + ")", "0% 0%");
}
}
public scrollbarWidth: number = undefined;
public scrollbarHeight: number = undefined;
private FindScrollbarSizes(elt: HTMLElement) {
if (this.scrollbarWidth === undefined) {
var saved = elt.style.overflow || "";
this.scrollbarWidth = elt.clientWidth;
this.scrollbarHeight = elt.clientHeight;
elt.style.overflow = "scroll";
this.scrollbarWidth -= elt.clientWidth;
this.scrollbarHeight -= elt.clientHeight;
elt.style.overflow = saved;
}
}
private recoverScroll() {
if (this.sideview) {
if (this.scrollTop !== undefined) {
this.rootElement.scrollTop = this.scrollTop;
this.rootElement.scrollLeft = this.scrollLeft;
}
//if (this.zoomfactor !== undefined)
// this.rootElement.msContentZoomFactor = this.zoomfactor;
}
}
public onScroll() {
this.scrollTop = this.rootElement.scrollTop;
this.scrollLeft = this.rootElement.scrollLeft;
var zoomfactor = this.rootElement.msContentZoomFactor;
if (zoomfactor)
this.updateslider(zoomfactor * this.minimumScale * 10, false);
}
// public onZoom() {
//
// }
private scrollToShow(box: BoxBase) {
// TODO: Implement this.
}
public render(box: BoxBase, e: HTMLElement) {
// "box" should be the root box.
if (box === null
|| (box.parent !== null && box.parent !== undefined)) {
return;
}
this.rootElement = e; // div wall-page box-page
this.rootBox = box;
box.isRoot = true;
// Prevent flickering.
var el = box.element;
// el.style.visibility = "hidden";
// fix element structure if necessary
if (this.rootElement.firstChild != el || ! this.rootBox.structuring_done) {
this.CreateOrFixElementStructure();
}
// the core layout algorithm
this.CoreLayout();
//el.style.visibility = "visible";
}
public isOnScreen(node: HTMLElement):boolean {
var top = document.documentElement;
while (node) {
if (node === top)
return true;
if (node.style.display === "none")
return false;
node = <HTMLElement>node.parentNode;
}
return false;
}
// the idempotent layout algorithm. Call this to recompute layout on non-structural changes.
public CoreLayout(): void {
if (this.rootBox instanceof HtmlBox) {
// we are doing almost nothing, just set attributes
this.rootBox.doLayout();
return;
}
if (!this.isOnScreen(this.rootElement))
return; // breaks if we are not on screen, because we need browser to tell us size of things
Util.time("CoreLayout", () =>
{
//Util.log("start layout");
// make sure we know the size of scroll bars
this.FindScrollbarSizes(this.rootElement);
// if this view is scaled (e.g. because of pinch-zoom), ensure scale is in place
if (this.sideview && this.scale !== undefined && this.scale != 1)
this.updateScaling(this.scale);
// the layout algorithm
this.rootBox.doLayout();
// redo layout if we misspeculated on vertical scrollbars
if (this.rootBox instanceof WallBox && !(<WallBox> this.rootBox).speculationwascorrect(this.scrollspeculation)) {
this.scrollspeculation = !this.scrollspeculation;
this.rootBox.doLayout();
}
// Calculate default scaling
this.calcDefaultScaling();
if (this.sideview) {
this.recoverScroll();
this.updateslider(this.scale, true);
}
if (this.onRendered)
this.onRendered();
// Util.log("end layout");
},
false); // set to true to stop measuring
}
private CreateOrFixElementStructure() {
this.boxes = [];
this.pcTable = {};
// Remove previous content unless recycled
var e = this.rootElement;
var el = this.rootBox.element;
while (e.hasChildNodes()) {
var b = e.firstChild;
if (b == el)
break;
e.removeChild(b);
}
while (e.hasChildNodes()) {
var b = e.lastChild;
if (b == el)
break;
e.removeChild(b);
}
// recurse
this.passS(this.rootBox);
// don't do it again
this.rootBox.structuring_done = true;
}
private passS(box: BoxBase) {
if (box.doLiveNavigation()) {
this.boxes.push(box);
this.recordmapping(box);
}
box.visitS();
for (var i = 0; i < box.children.length; i++)
this.passS(box.children[i]);
}
/*
private doLayout(rootBox: WallBox) {
// Horizontal layout
// 1. make box groups
// 2. compute widths of leaf nodes without wrapping
// 3. set widths if specified explicitly
var bottomUpQueue = this.prepareHorizontalLayout(rootBox);
// 4. make box lines
// 5. for each line, distribute the rest horizontal space among springs
this.calcHorizontalSprings(bottomUpQueue);
// Vertical layout
// 6. set heights if specified explicitly
this.prepareVerticalLayout(rootBox);
// 7. distribute the rest vertical space among springs
this.calcVerticalSprings(bottomUpQueue);
}
*/
// Put this box in the database.
public recordmapping(box: BoxBase) {
if (this.pcTable[box.getAstNodeId()] === undefined)
this.pcTable[box.getAstNodeId()] = box;
for (var propName in box.pcTable)
if (this.pcTable[box.pcTable[propName]] === undefined)
this.pcTable[box.pcTable[propName]] = box;
}
}
export class WallPage {
libName: string;
pageName: string;
drawFn: any;
drawArgs: any[];
topDown: boolean = false;
buttons: IPageButton[];
crashed = false;
id = Random.uniqueId();
csslayout: boolean = false;
model:any; // the compile sticks stuff in here
private element: HTMLElement;
private rootBox: BoxBase;
private currentBox: BoxBase;
public lastChildCount = -1;
private runtime: Runtime;
private _rtPage: TDev.RT.Page;
private auto: boolean;
public title = "";
public subtitle = "";
public chromeVisible = true;
public backButtonVisible = true;
public fgColor = "#000000";
public bgColor = "#ffffff";
public bgPictureUrl: string;
public bgPicture: HTMLElement;
public bgPictureWidth:number;
public bgPictureHeight:number;
public bgVideo: HTMLVideoElement;
public fullScreenElement: HTMLElement;
public renderCount = 0;
public onNavigatedFrom: RT.Event_ = new RT.Event_();
constructor (rt: Runtime, auto:boolean) {
this.runtime = rt;
this.element = div("wall-page");
this.buttons = [];
this.auto = auto;
this.onNavigatedFrom.isPageEvent = true;
this.clear();
}
activate(): void {
this.getElement().style.display = "block";
}
deactivate(): void {
this.getElement().style.display = "none";
}
getElement(): HTMLElement { return this.element; }
isAuto() { return this.auto; }
public isReversed(): boolean { return this.topDown; }
public setReversed(reversed: boolean) {
if (this.topDown != reversed) {
this.lastChildCount = -1;
this.topDown = reversed;
}
}
public rtPage() : TDev.RT.Page
{
if (!this._rtPage)
this._rtPage = TDev.RT.Page.mk(this);
return this._rtPage;
}
static applySizeUpdate(e: HTMLElement) {
var walkHtml = (e: any) => {
if (!e) return;
if (e.updateSizes)
e.updateSizes();
Util.childNodes(e).forEach(walkHtml)
}
walkHtml(e);
}
getFrame(prev: IStackFrame, ret: IContinuationFunction) {
var rt = prev.rt;
if (!this.isAuto()) {
var frame: IStackFrame = <any>{};
frame.previous = prev;
frame.rt = prev.rt;
frame.returnAddr = ret;
frame.entryAddr = (s) => { return s.rt.leave() };
return frame;
}
if (!this.drawFn) {
var f = prev.rt.compiled.lookupLibPage(this.libName, this.pageName);
this.drawFn = (prev, ret) => {
var newFrame = f(prev);
return newFrame.invoke.apply(null, (<any[]>[newFrame, ret]).concat(this.drawArgs));
};
}
return this.drawFn(prev, ret);
}
refreshForNewScript() {
this.drawFn = null;
//this.element = div("wall-page"); NOOOO dont do this... it breaks incremental layout
}
getCurrentBox(): BoxBase {
// Util.log("get current box" + this.currentBox.id);
return this.currentBox;
}
setCurrentBox(box: BoxBase) {
this.currentBox = box;
//Util.log("set current box" + box.id);
}
setFullScreenElement(host: RuntimeHost, elt: HTMLElement) {
this.fullScreenElement = elt;
host.setFullScreenElement(elt);
}
clear() {
this.rootBox = WallBox.CreateOrRecycleRoot(this.runtime, null); // null forces creation
this.setCurrentBox(this.rootBox);
this.lastChildCount = -1;
}
startrender() {
this.renderCount++;
this.rootBox = WallBox.CreateOrRecycleRoot(this.runtime, this.rootBox);
this.setCurrentBox(this.rootBox);
this.lastChildCount = -1;
}
render(host: RuntimeHost, popCount: number = 0) {
Util.assertCode(popCount >= 0);
var rootElt = this.getElement();
var getElt = (b: WallBox) =>
{
return div("legacy-wall-box", b.getContent());
}
// always apply wall background, foreground colors,
// ignoring picture/video background for now.
rootElt.style.background = "none"; // see through to the real background as set in applyPageAttributes
rootElt.style.color = this.fgColor;
if (this.isAuto()) { //if (this.rootBox.isGeneric()) {
rootElt.className = "wall-page " + (this.csslayout ? " html-page" : "box-page");
this.setFullScreenElement(host, null);
LayoutMgr.instance.render(this.rootBox, rootElt)
} else {
Util.assert(this.rootBox instanceof WallBox);
var i = 0;
var sz = (<WallBox>this.rootBox).size()
var newElts = []
if (sz > 0) {
var last = (<WallBox>this.rootBox).get(sz - 1);
if ((<WallBox>last).fullScreen) {
this.setFullScreenElement(host,div("wall-fullscreen", last.getContent()));
this.lastChildCount = -1;
return;
}
}
this.setFullScreenElement(host,null);
rootElt.className = "wall-page classic-page";
// push front boxes
if (this.lastChildCount < 0) {
var children: WallBox[] = []
for (i = 0; i < sz; ++i)
children.push(<WallBox> (<WallBox>this.rootBox).get(this.isReversed() ? i : sz - i - 1))
rootElt.setChildren(children.map(getElt))
newElts = [rootElt]
} else {
for (i = this.lastChildCount - popCount; i < sz; ++i) {
var ch = getElt(<WallBox> (<WallBox>this.rootBox).get(i))
newElts.push(ch)
if (this.isReversed()) {
rootElt.appendChild(ch)
} else {
var first = rootElt.firstChild;
if (!first)
rootElt.appendChild(ch)
else
rootElt.insertBefore(ch, first)
}
}
// incremental pop back boxes
for (var i = 0; i < popCount; ++i) {
if (this.isReversed()) {
var firstChild = rootElt.firstChild;
if (firstChild)
rootElt.removeChild(firstChild);
}
else {
var lastChild = rootElt.lastChild;
if (lastChild)
rootElt.removeChild(lastChild);
}
}
}
this.lastChildCount = sz;
newElts.forEach(WallPage.applySizeUpdate)
}
}
}
export interface BoxBackgroundImage {
url: string;
size?: string;
repeat?: string;
attachment?:string;
position?: string;
origin?: string;
}
export class BoxAttributes {
public tappedEvent: RT.Event_;
//public editEvent: RT.Event_;
public textEditingEvent: RT.Event_;
constructor() {
this.tappedEvent = this.mkEv();
this.textEditingEvent = this.mkEv();
}
// abstract methods
public applyToStyle(b: BoxBase) { Util.oops("must override"); }
public mkEv() {
var r = new RT.Event_();
r.isPageEvent = true;
return r;
}
}
export class HtmlAttributes extends BoxAttributes {
public classnames: string[];
public styles: StringMap<string>;
public attributes: StringMap<string>;
public applyToStyle(b: BoxBase) {
Util.assert(b instanceof HtmlBox);
var bb = <HtmlBox> b;
if (bb.element.nodeType == Node.ELEMENT_NODE) {
bb.setRenderedClassnames(this.classnames);
bb.setRenderedStyles(this.styles);
bb.setRenderedAttributes(this.attributes);
}
}
}
export class LayoutAttributes extends BoxAttributes {
public flow:number; // FLOW_HORIZONTAL, FLOW_VERTICAL, FLOW_OVERLAY
public textalign: number; // TEXT_LEFT, TEXT_CENTER, TEXT_RIGHT, TEXT_JUSTIFY
public fontSize: number;
public fontWeight: string;
public fontFamily: string;
public background: string;
public backgroundImages: BoxBackgroundImage[];
public foreground: string;
public border: string;
public width: number[]; // width[MIN], width[MAX]
public height: number[]; // height[MIN], height[MAX]
public margin: number[]; // margin[T], margin[R], margin[B], margin[L]
public padding: number[]; // padding[T], padding[R], padding[B], padding[L]
public borderwidth: number[];
public stretchwidth: number; // -1 (auto) 0 (no stretching) >0 (stretch weight)
public stretchheight: number; // -1 (auto) 0 (no stretching) >0 (stretch weight)
public stretchmargin: number[]; // [T,R,B,L] each being 0 (no stretching) or >0 (stretch weight)
public scroll: boolean[]; // [H,V]
public arrangement: number[]; // [H,V]
public wrap: boolean;
public wraplimit: number;
// for compatibility with old API
public legacystretch: boolean[];
public legacybaseline: boolean;
public textEditedEvent: RT.Event_;
constructor(isroot: boolean) {
super();
// Set to the default values
this.flow = WallBox.FLOW_VERTICAL;
//this.textalign = undefined;
this.fontSize = 0;
//this.fontWeight = undefined;
this.fontFamily = "";
this.background = "transparent";
//this.foreground = undefined;
//this.border = undefined;
this.width = [0, Infinity];
this.height = [0, Infinity];
this.margin = [0, 0, 0, 0];
this.padding = [0, 0, 0, 0];
this.stretchwidth = -1;
this.stretchheight = -1;
this.stretchmargin = [0, 0, 0, 0];
this.borderwidth = [0, 0, 0, 0];
this.arrangement = [undefined, WallBox.ARRANGE_BASELINE];
this.scroll = [isroot, isroot];
this.legacystretch = [false, false];
this.legacybaseline = true;
this.wrap = undefined;
this.wraplimit = 15;
this.textEditedEvent = this.mkEv();
}
public applyToStyle(b: WallBox) {
b.setRenderedPositionMode("absolute");
b.setRenderedTextAlign(this.textalign);
b.setRenderedBackgroundColor(this.background);
b.setRenderedBackgroundImages(this.backgroundImages);
b.setRenderedColor(this.foreground);
b.setRenderedFontWeight(this.fontWeight);
b.setRenderedFontFamily(this.fontFamily);
b.setRenderedFontSize(this.fontSize);
b.setRenderedWrap(this.wrap, this.wraplimit);
b.setRenderedBorder(this.border, this.borderwidth);
}
}
export class BoxBase {
// structural info
public id: number;
public depth: number;
private astNodeId: string;
public isRoot: boolean;
public parent: BoxBase;
public obsolete = false;
// attributes and children
public attributes: BoxAttributes;
public children: BoxBase[];
// reuse of boxes
public recycled = false;
private prevchildren: BoxBase[];
private reuseindex = 0;
private reusekey: any;
private reuseversion: number;
private replaces: BoxBase;
// content
private fresh = true;
public element: HTMLElement;
// other
public runtime: Runtime;
public pcTable: any;
public structuring_done = false;
public isSingleChild = false;
layoutcompletehandler: (width: number, height: number) => void;
public delayedlayout = false;
constructor(rt: Runtime, parent: BoxBase, nodeId: string) {
this.runtime = rt;
this.id = LayoutMgr.instance.numBoxes++;
this.astNodeId = nodeId;
this.isRoot = false;
this.parent = parent;
if (this.parent) {
this.parent.children.push(this);
this.depth = this.parent.depth + 1;
} else {
this.depth = 0;
}
this.children = [];
this.pcTable = { "": this.astNodeId };
}
// for leaf boxes - overridden
public getContent(): HTMLElement { return undefined; }
public setContent(e: any) { }
public RefreshOnScreen(): void { }
public SwapImageContent(newcontent: HTMLElement): void { }
public hookContent(): void { }
public mayReplaceWith(tagname?: string): boolean { return false; } // overridden
public isLeaf(): boolean { return false } // overridden
// for live navigation
public doLiveNavigation(): boolean { return true; }
public getRenderedWidth(): number { return 0; } // overridden
public getRenderedHeight(): number { return 0; } // overridden
public setHighlight(strong: boolean = true) { }// overridden
public clearHighlight() { }// overridden
public Obsolete() {
this.obsolete = true;
this.children.forEach(c => c.Obsolete());
}
public getAstNodeId(): string { return this.astNodeId; }
// We don't use this since it fails when the default value for a method parameter is set.
// (Strada compiler hides the callee name.)
private onFunctionCall(f: (any) => any, pc: string) {
var functionNames = f.toString().match(/function ([^\(]+)/);
if (functionNames !== null) {
var functionName = functionNames[1];
this.onCall(functionName, pc);
}
}
public onCall(fName: string, pc: string) {
if (!pc) return;
this.pcTable[fName] = pc;
}
// --------------- tap events
tapped() {
var done = false;
if (LayoutMgr.instance.editMode) { // live navigation
if (LayoutMgr.instance.selectBox(this))
done = true;
} else {
if (this.obsolete || (this.runtime.eventQ && !this.runtime.eventQ.viewIsCurrent()))
return; // box may have been deleted or not reflect proper action
if (this.attributes.tappedEvent.handlers) {
done = true;
this.setRenderedTappable(true, true);
this.runtime.queueLocalEvent(this.attributes.tappedEvent);
this.runtime.forcePageRefresh();
}
else if (this.contenttapapplies()) {
this.contenttaphandler();
done = true;
}
}
if (LayoutMgr.instance.editMode || this instanceof WallBox) // bubble up tap events
if (!done && this.parent)
this.parent.tapped();
}
// click handlers that are installed by posted content
private contenttaphandler: () => void;
public withClick(h: () => void): void {
this.contenttaphandler = h;
}
public contenttapapplies(): boolean {
return this.contenttaphandler && !this.attributes.tappedEvent.handlers && !(this.isSingleChild && this.parent.attributes.tappedEvent.handlers);
}
// overridden by WallBox - creates grey shadow
setRenderedTappable(tappable: boolean, tapped: boolean) { }
// ---------- editable text binding
private inputversions = new Array<string>();
private lastqueuededit: RT.Event_;
static debuginput: boolean = false;
public bindEditableText(s: string, handler: any /* RT.TextAction or Ref<string> */, pc: string)
{
this.addTextEditHandler(handler);
this.setInputText(s);
this.onCall("binding", pc);
}
private addTextEditHandler(handler: any /* RT.TextAction or Ref<string> */) {
if (handler instanceof RT.Ref) {
this.attributes.textEditingEvent.addHandler(new RT.PseudoAction((rt: Runtime, args: any[]) => {
(<RT.Ref<string>> handler)._set(args[0], rt.current);
rt.forcePageRefresh();
}));
}
else // RT.TextAction
this.attributes.textEditingEvent.addHandler(handler);
}
// virtual methods (these are specific to HtmlBox bs. LayoutBox)
public getEditableContent(): string { Util.oops("virtual"); return undefined; }
public setEditableContent(s: string) { Util.oops("virtual"); }
public invalidateCachedLayout(triggerdelayedrelayout: boolean) { }
onInputTextChange() {
if (LayoutMgr.instance.editMode)
return; // don't do anything in edit mode
var text = this.getEditableContent();
if (this.obsolete)
return; // box may be already gone from screen
if (this.inputversions.length === 3)
this.inputversions.pop(); // never keep more than 3 versions
if (this.inputversions[this.inputversions.length - 1] === text) {
if (WallBox.debuginput) Util.log("&&&" + this.id + " flag \"" + this.inputversions + "\"");
LayoutMgr.instance.FlagTypingActivity("i" + this.id); // for catching race
return; // already being processed
}
this.inputversions.push(text);
if (WallBox.debuginput) Util.log("&&&" + this.id + " push \"" + this.inputversions + "\"");
var parent = this.parent;
if (this.attributes.textEditingEvent.handlers) {
this.invalidateCachedLayout(false);
if (this.inputversions.length >= 2) {
this.runtime.queueLocalEvent(this.lastqueuededit = this.attributes.textEditingEvent, [this.inputversions[1]]);
this.runtime.forcePageRefresh();
}
}
else {
// no need for full refresh... just do a delayed relayout
this.invalidateCachedLayout(true);
}
}
setInputText(text: string) {
var cur = this.getEditableContent();
var requeue = false;
if (text === this.inputversions[1]) {
this.inputversions.shift(); // prune history
if (WallBox.debuginput) Util.log("&&&" + this.id + " prune \"" + this.inputversions + "\"");
// record additional changes
if (text !== cur) {
this.inputversions[1] = cur;
requeue = true;
}
} else if (this.inputversions.length === 1 && text != cur && LayoutMgr.instance.CheckTypingActivity("i" + this.id)) {
this.inputversions = [text, cur]; // skip the version by changing the event argument
LayoutMgr.instance.ClearTypingActivity("i" + this.id);
if (WallBox.debuginput) Util.log("&&&" + this.id + " skip \"" + this.inputversions + "\"");
requeue = true;
}
//else if (text === this.inputversions[0] && this.lastqueuededit && this.lastqueuededit.inQueue) {
// an update event is pending
//Util.oops("should not refresh screen while page events are pending");
//if (WallBox.debuginput) Util.log("&&&" + this.id + " wait \"" + this.inputversions + "\"");
//}
else {
this.inputversions = [text]; // start new history, discard intermediate versions
this.lastqueuededit = undefined;
if (WallBox.debuginput) Util.log("&&&" + this.id + " set \"" + this.inputversions + "\"");
}
if (this.inputversions.length == 1) {
// the current version is final - write it back
if (text !== cur) {
this.setEditableContent(text);
this.invalidateCachedLayout(false);
}
LayoutMgr.instance.ClearTypingActivity("i" + this.id);
}
else if (this.inputversions.length == 2 && requeue) {
// there were more edits since the last edit event -- requeue
if (this.attributes.textEditingEvent.handlers) {
if (WallBox.debuginput) Util.log("&&&" + this.id + " requeue \"" + this.inputversions + "\"");
this.runtime.queueLocalEvent(this.lastqueuededit = this.attributes.textEditingEvent, [this.inputversions[1]]);
//this.runtime.forcePageRefresh();
}
}
}
// ----------- online tree diffing
public static CreateOrRecycleRoot(rt: Runtime, p: BoxBase): BoxBase {
var cssmode = rt.onCssPage();
if (LayoutMgr.RenderExecutionMode()
&& p && (cssmode == p instanceof HtmlBox)) {
return p.recycle(rt, null, "", rt.onCssPage());
}
else {
return cssmode ? (<BoxBase> new HtmlBox(rt, null, "", "div")) : (<BoxBase> new WallBox(rt, null, ""));
}
}
public static CreateOrRecycleContainerBox(rt: Runtime, cur: BoxBase, pc, tagName?:string):BoxBase {
var candidate = null;
if (LayoutMgr.RenderExecutionMode()
&& cur.recycled
&& cur.reuseindex < cur.prevchildren.length) {
candidate = cur.prevchildren[cur.reuseindex];
cur.reuseindex = cur.reuseindex + 1;
if (candidate.mayReplaceWith(tagName))
return candidate.recycle(rt, cur, pc, rt.onCssPage());
}
var box = rt.onCssPage() ? <BoxBase>new HtmlBox(rt, cur, pc, tagName) : <BoxBase>new WallBox(rt, cur, pc);
box.replaces = candidate;
return box;
}
public static CreateOrRecycleLeafBox(rt: Runtime, val: any): BoxBase {
var cur = rt.getCurrentBoxBase(true);
var candidate = null;
var pc = rt.getTopScriptPc();
if (LayoutMgr.RenderExecutionMode()
&& cur.recycled
&& cur.reuseindex < cur.prevchildren.length) {
candidate = cur.prevchildren[cur.reuseindex];
cur.reuseindex = cur.reuseindex + 1;
if (val !== null && candidate.content && candidate.reusekey === val
&& (!candidate.reuseversion || (candidate.reuseversion === (<RT.RTValue>val).versioncounter))) {
return candidate.recycle(rt, cur, pc, rt.onCssPage());
}
}
var cssmode = rt.onCssPage()
var box = rt.onCssPage() ? <BoxBase>new HtmlBox(rt, cur, pc) : <BoxBase>new WallBox(rt, cur, pc);
box.reusekey = val;
box.reuseversion = val && val.versioncounter;
box.replaces = candidate;
return box;
}
public recycle(rt: Runtime, parent: BoxBase, nodeId: string, cssmode: boolean): BoxBase {
Util.assert(!!cssmode === (this instanceof HtmlBox), "mixed up boxes");
this.runtime = rt;
this.parent = parent;
this.astNodeId = nodeId;
if (this.parent) {
this.parent.children.push(this);
Util.assert(this.depth === this.parent.depth + 1);
} else {
Util.assert(this.depth === 0);
}
this.recycled = true;
this.structuring_done = false;
this.prevchildren = this.children;
this.reuseindex = 0;
this.children = [];
this.attributes = cssmode ? new HtmlAttributes() : new LayoutAttributes(this.depth == 0);
this.pcTable = { "": this.astNodeId };
return this;
}
// ----------- tree traversals
public doLayout() { /*overridden*/ }
public visitS() {
// remove deleted children
if (this.recycled) {
for (var i = this.children.length; i < this.prevchildren.length; i++) {
var b = this.prevchildren[i];
b.Obsolete();
this.element.removeChild(b.element);
}
}
// add to parent if fresh, or replace
var p = this.parent;
if (this.fresh || (p && !p.recycled)) {
// add into parent container
if (p) {
if (this.replaces) {
this.replaces.Obsolete();
p.element.replaceChild(this.element, this.replaces.element);
this.replaces = null;
}
else {
p.element.appendChild(this.element);
}
}
else {
Util.assert(this.isRoot);
LayoutMgr.instance.rootElement.appendChild(this.element);
LayoutMgr.instance.rootElement.onscroll = (e: Event) => { LayoutMgr.instance.onScroll(); };
//LayoutMgr.instance.rootElement.onzoom = (e: Event) => { LayoutMgr.instance.onZoom(); };
}
// set content, if fresh
if (this.fresh) {
this.hookContent();
this.fresh = false;
}
}
}
public visitI() {
this.attributes.applyToStyle(this);
}
}
export class HtmlBox extends BoxBase {
// specialize types
public attributes: HtmlAttributes;
public tagName: string;
public isLeaf(): boolean {
return !this.tagName;
}
constructor(rt: Runtime, parent: BoxBase, nodeId: string, tagName?: string) {
super(rt, parent, nodeId);
if (parent)
Util.assert(parent instanceof HtmlBox);
this.attributes = new HtmlAttributes();
if (tagName !== undefined) {
this.tagName = tagName;
if (tagName && !HTML.allowedTagName(tagName))
Util.userError(lf("tag name {0} is not allowed", tagName))
this.element = document.createElement(tagName);
this.element.id = this.id.toString();
this.attributes.applyToStyle(this);
}
}
public mayReplaceWith(tagName?: string): boolean {
return (this.tagName === tagName);
}
public doLiveNavigation(): boolean { return !!this.tagName; }
public setContent(e: any) {
Util.check(this.isLeaf());
Util.check(e != null);
this.element = e;
this.attributes.applyToStyle(this);
}
public getContent() {
return this.element;
}
public RefreshOnScreen(): void {
// no action needed.. html layout is always on
}
public invalidateCachedLayout(triggerdelayedrelayout: boolean) {
// no action needed... html layout is always on
}
public withClick(h: () => void): void {
//todo
}
public getRenderedWidth(): number { return this.element.clientWidth; }
public getRenderedHeight(): number { return this.element.clientHeight; }
public getEditableContent(): string {
return (<any>this.element).value;
// return this.textarea ? (<HTMLTextAreaElement>this.content).value : (<HTMLInputElement>this.content).value
}
public setEditableContent(text: string) {
(<any>this.element).value = text;
// if (this.textarea)
// (<HTMLTextAreaElement>this.content).value = text;
// else
// (<HTMLInputElement>this.content).value = text;
}
public hookContent() {
var tag = this.element && this.element.tagName;
if (tag) {
this.element.withClick(() => { this.tapped() });
if (/input|textarea/i.test(tag))
this.element.oninput = (e: Event) => { this.onInputTextChange(); };
}
}
public SwapImageContent(newcontent: HTMLElement): void {
var p = this.element.parentNode;
if (p)
p.replaceChild(newcontent, this.element);
this.element = newcontent;
}
public setHighlight(strong: boolean = true) {
if (this.element && this.element.style) {
this.element.style.border = strong ? "5px dotted #C00" : "5px dotted #rgba(204, 0, 0, 0.6)";
if (!strong)
this.element.style.background = "rgba(204, 0, 0, 0.4)";
}
}
public clearHighlight() {
this.element.style.cssText = this.rendered_styles;
}
public doLayout() {
this.passA();
}
private passA() {
this.visitI();
for (var i = 0; i < this.children.length; i++) {
(<HtmlBox>this.children[i]).passA();
}
}
public addClassName(s: string, pc = "") {
if (!this.attributes.classnames) this.attributes.classnames = [];
this.attributes.classnames.push(s);
this.onCall("class name", pc);
}
public setAttribute(name: string, value: string, pc = "") {
if (!this.attributes.attributes) this.attributes.attributes = {};
this.attributes.attributes[name] = value;
this.onCall("attr:" + name, pc);
}
public setStyle(property: string, value:string, pc = "") {
if (!this.attributes.styles) this.attributes.styles = {};
this.attributes.styles[property] = value;
this.onCall("style:" + property, pc);
}
private rendered_classnames: string;
private rendered_styles: string;
private rendered_attributes: string;
setRenderedClassnames(names: string[]) {
var cmp = (names && names.length > 0) ? names.join(' ') : '';
if (cmp !== this.rendered_classnames) {
if (cmp) this.element.className = cmp;
else this.element.removeAttribute("class");
this.rendered_classnames = cmp;
}
}
setRenderedStyles(styles: StringMap<string>) {
var s = styles ? Object.keys(styles).map(k => k + ": " + styles[k]).join("; ") : "";
if (s !== this.rendered_styles) {
this.element.style.cssText = s;
this.rendered_styles = s;
}
}
setRenderedAttributes(attributes: StringMap<string>) {
var s = JSON.stringify(attributes);
if (s !== this.rendered_attributes) {
var prev = JSON.parse(this.rendered_attributes || "{}");
// set new keys
Object.keys(attributes).forEach(k => {
this.element.setAttribute(k, attributes[k]);
delete prev[k];
});
// remove keys that weren't overrideen
Object.keys(prev).forEach(k => this.element.removeAttribute(k));
// store new set of attributes
this.rendered_attributes = s;
}
}
}
export class WallBox extends BoxBase {
// specialize types
public attributes: LayoutAttributes;
// Constants
static FLOW_HORIZONTAL: number = 0;
static FLOW_VERTICAL: number = 1;
static FLOW_OVERLAY: number = 2;
static STRETCH_AUTO: number = -1;
static ARRANGE_LEFT: number = 1;
static ARRANGE_RIGHT: number = 2;
static ARRANGE_CENTER: number = 3;
static ARRANGE_JUSTIFY: number = 4;
static ARRANGE_BASELINE: number = 5;
static ARRANGE_TOP: number = 6;
static ARRANGE_BOTTOM: number = 7;
static ARRANGE_SPREAD: number = 8;
static MIN: number = 0;
static MAX: number = 1;
static T: number = 0;
static R: number = 1;
static B: number = 2;
static L: number = 3;
static H: number = 0;
static V: number = 1;
static CONTENT_NONE: number = -1;
static CONTENT_TEXT: number = 0;
static CONTENT_IMAGE: number = 1;
static CONTENT_INPUT: number = 2;
// cached size info
private cached_width = -1; // the natural (full) width of the element
private cached_height = -1; // the natural height of the element, for the given cached_width
private cached_baseline = -1; // the baseline of this element
private cached_aspectratio = 0; // width / height, or zero if this element does not use a ratio
// New layout algorithm
private A_m: number; // requested minwidth
private A_as: number;// requested alt width
private A_s: number; // requested width
private A_sl: number;// requested left margin
private A_sr: number;// requested right margin
private A_mc: number;// computed minwidth
private A_asc: number;// computed alt width
private A_sc: number;// computed width
private A_scc: number;// computed width for content
private A_fcc: number;// computed fill count for content
private A_fcs: number;// computed fill count for spaces
private A_f: number; // requested fill width for content
private A_fl: number;// requested left margin fill
private A_fr: number;// requested right margin fill
private A_fp: number; // requested fill propagation
private A_scr: number; // space needed for scrollbar
private B_s: number; // granted width
private B_x: number; // computed x coordinate of box
private B_scr: boolean; // scrolling
private C_m: number; // requested minheight
private C_s: number; // requested height
private C_st: number;// requested top margin
private C_sb: number;// requested bottom margin
private C_sc: number;// computed height
private C_scc: number;// computed height for content
private C_fcc: number;// computed fill count for content
private C_fcs: number; // computed fill count for spaces
private C_mc: number; // requested minheight
private C_f: number; // requested fill height
private C_ft: number;// requested top margin fill
private C_fb: number;// requested bottom margin fill
private C_fp: number;// requested fill propagation
private C_scr: number; // space needed for scrollbar
private C_zc: number; // number of z positions needed
private C_bc: number; // computed baseline
private C_b: number; // reported baseline
private D_s: number; // granted height
private D_y: number; // computed y coordinate of box
private D_scr: boolean; // scrolling
private D_z: number; // zrange
private D_zmax: number; // zrange
private D_b: number; // baseline
// Fields that are computed and set during the layouting.
private rendered_x: number;
private rendered_y: number;
private rendered_width: number;
private rendered_height: number;
private rendered_hmode: string;
private rendered_vmode: string;
private rendered_b: number;
private rendered_fontfamily: string;
private rendered_fontweight: string;
private rendered_fontsize: number;
private rendered_textalign: number;
private rendered_foregroundcolor: string;
private rendered_backgroundcolor: string;
private rendered_background: string;
private rendered_wrap: boolean;
private rendered_wraplimit: number;
private rendered_zindex: number;
private rendered_border: string;
private rendered_borderwidth: number[];
private rendered_sideview: boolean;
private rendered_tappable: string;
private rendered_positionmode: string;
// content
private contentType: number;
private content: HTMLElement;
private auxcontent: HTMLElement;
private baselineprobe: HTMLElement;
public textarea: boolean;
//other
public fullScreen: boolean;
constructor (rt: Runtime, parent: BoxBase, nodeId: string) {
super(rt, parent, nodeId);
if (parent)
Util.assert(parent instanceof WallBox);
this.attributes = new LayoutAttributes(this.depth == 0);
this.contentType = WallBox.CONTENT_NONE;
this.content = null;
this.element = document.createElement("div");
this.element.id = this.id.toString();
this.element.withClick(() => { this.tapped() });
this.attributes.applyToStyle(this);
}
public mayReplaceWith(tagname?: string): boolean {
return (tagname === "div" && this.content === null && this.contentType === WallBox.CONTENT_NONE);
}
public isLeaf(): boolean {
return this.contentType != WallBox.CONTENT_NONE;
}
public RefreshOnScreen(): void {
if (this.contentType == WallBox.CONTENT_NONE)
return; // too early... content not set yet
Util.assert(this.contentType == WallBox.CONTENT_IMAGE);
this.cached_height = -1;
this.cached_width = -1;
LayoutMgr.QueueReLayout();
}
public SwapImageContent(newcontent: HTMLElement):void {
Util.assert(this.contentType == WallBox.CONTENT_IMAGE);
this.element.removeAllChildren();
this.element.appendChild(newcontent);
this.content = newcontent;
this.cached_height = -1;
this.cached_width = -1;
LayoutMgr.QueueReLayout();
}
public hookContent(): void {
if (this.content && this.content !== this.element) {
var e = this.element;
if (this.contentType === WallBox.CONTENT_TEXT) {
} else if (this.contentType === WallBox.CONTENT_INPUT) {
//this.content.onkeyup = (e: Event) => {
// this.onInputTextChange();
//};
this.content.oninput = (e: Event) => {
this.onInputTextChange();
};
this.content.onchange = (e: Event) => {
this.onInputTextChangeDone();
};
this.content.onclick = (e: Event) => {
if (LayoutMgr.instance.editMode) {
this.tapped();
} else {
if (this.attributes.tappedEvent.handlers) {
this.runtime.queueLocalEvent(this.attributes.tappedEvent);
}
}
};
}
if (this.auxcontent)
e.appendChild(this.auxcontent);
e.appendChild(this.content);
}
}
public setHighlight(strong: boolean = true) {
this.element.style.zIndex = strong ? "2" : "1";
this.element.setAttribute("sel", strong ? "strong" : "weak");
}
public clearHighlight() {
this.element.setAttribute("sel", "");
this.element.style.zIndex = "auto";
}
public visitI() {
if (!this.isRoot) {
//this.rendered_x = undefined;
//this.rendered_y = undefined;
//this.rendered_width = undefined;
// this.rendered_height = undefined;
//this.rendered_hscrollbar = false;
//this.rendered_vscrollbar = false;
// set fontfamily and fontsize if they were not specified
if (this.getFontFamily() === "")
this.setFontFamily((<WallBox> this.parent).getFontFamily());
if (this.getFontSize() <= 0)
this.setFontSize((<WallBox> this.parent).getFontSize());
// set wrapping if this a multiline input and it was not specified
} else {
// Calculate size of the wall
var width = this.runtime.host.fullWallWidth();
var height = this.runtime.host.userWallHeight();
// restore full element size (not sure if needed)
this.setRenderedWidth(width);
this.setRenderedHeight(height);
// overrides any user-specified sizes... they are meaningless for root box
//this.setWidth(width);
// this.setHeight(height);
// set fontfamily and fontsize if they were not specified
if (this.getFontFamily() === "")
this.setFontFamily('"Segoe UI", "Segoe WP", "Helvetica Neue", Sans-Serif')
if (this.getFontSize() <= 0)
this.setFontSize(SizeMgr.topFontSize);
}
// determine if this is a single child
var parent = this.parent;
if (parent && parent.children.length === 1)
this.isSingleChild = true;
// leaf boxes get some attributes from parent
if (this.contentType == WallBox.CONTENT_TEXT) {
var parentattributes = <LayoutAttributes> (parent.attributes);
(<LayoutAttributes>this.attributes).textalign = parentattributes.textalign;
this.attributes.wrap = parentattributes.wrap;
this.attributes.wraplimit = parentattributes.wraplimit;
}
if (this.contentType == WallBox.CONTENT_INPUT) {
var parentattributes = <LayoutAttributes> (parent.attributes);
this.attributes.textalign = WallBox.ARRANGE_LEFT; // this is the only thing that works on input boxes
this.attributes.wrap = this.textarea ? (parentattributes.wrap === undefined ? true : parentattributes.wrap) : false;
this.attributes.wraplimit = parentattributes.wraplimit;
}
if (this.contentType == WallBox.CONTENT_IMAGE) {
var parentattributes = <LayoutAttributes> (parent.attributes);
this.attributes.textalign = parentattributes.textalign;
this.attributes.width = parentattributes.width;
this.attributes.height = parentattributes.height;
if (parentattributes.stretchwidth !== -1) this.attributes.stretchwidth = parentattributes.stretchwidth; // influences min width
if (parentattributes.stretchheight !== -1) this.attributes.stretchheight = parentattributes.stretchheight;
this.attributes.wrap = parentattributes.wrap;
this.attributes.wraplimit = parentattributes.wraplimit;
}
var numchildren = this.children.length;
// arrangement sets stretch margins
var harr = this.attributes.arrangement[WallBox.H];
if (harr !== undefined) {
if (this.attributes.flow !== WallBox.FLOW_HORIZONTAL) {
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.attributes.stretchmargin[WallBox.L] = (harr == WallBox.ARRANGE_RIGHT || harr == WallBox.ARRANGE_CENTER || harr == WallBox.ARRANGE_SPREAD) ? 1 : 0;
child.attributes.stretchmargin[WallBox.R] = (harr == WallBox.ARRANGE_LEFT || harr == WallBox.ARRANGE_CENTER || harr == WallBox.ARRANGE_SPREAD) ? 1 : 0;
}
}
else {
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.attributes.stretchmargin[WallBox.L] = (harr == WallBox.ARRANGE_SPREAD ||
(i == 0 ? (harr == WallBox.ARRANGE_RIGHT || harr == WallBox.ARRANGE_CENTER) : (harr == WallBox.ARRANGE_JUSTIFY))) ? 1 : 0;
child.attributes.stretchmargin[WallBox.R] = (harr == WallBox.ARRANGE_SPREAD ||
(i == (numchildren - 1) ? (harr == WallBox.ARRANGE_LEFT || harr == WallBox.ARRANGE_CENTER) : (harr == WallBox.ARRANGE_JUSTIFY || harr == WallBox.ARRANGE_CENTER))) ? 1 : 0;
}
//if (this.attributes.stretchwidth === -1 && (harr == WallBox.ARRANGE_LEFT || harr === WallBox.ARRANGE_RIGHT || harr === WallBox.ARRANGE_CENTER))
// this.attributes.stretchwidth = 1;
}
}
var varr = this.attributes.arrangement[WallBox.V];
if (varr !== WallBox.ARRANGE_BASELINE) {
if (this.attributes.flow !== WallBox.FLOW_VERTICAL) {
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.attributes.stretchmargin[WallBox.T] = (varr == WallBox.ARRANGE_BOTTOM || varr == WallBox.ARRANGE_CENTER || varr == WallBox.ARRANGE_SPREAD) ? 1 : 0;
child.attributes.stretchmargin[WallBox.B] = (varr == WallBox.ARRANGE_TOP || varr == WallBox.ARRANGE_CENTER || varr == WallBox.ARRANGE_SPREAD) ? 1 : 0;
}
}
else {
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.attributes.stretchmargin[WallBox.T] = (varr == WallBox.ARRANGE_SPREAD ||
(i == 0 ? (varr == WallBox.ARRANGE_BOTTOM || varr == WallBox.ARRANGE_CENTER) : (varr == WallBox.ARRANGE_JUSTIFY))) ? 1 : 0;
child.attributes.stretchmargin[WallBox.B] = (varr == WallBox.ARRANGE_SPREAD ||
(i == (numchildren - 1) ? (varr == WallBox.ARRANGE_TOP || varr == WallBox.ARRANGE_CENTER) : (varr == WallBox.ARRANGE_JUSTIFY))) ? 1 : 0;
}
// if (this.attributes.stretchheight === -1 && (varr == WallBox.ARRANGE_TOP || varr === WallBox.ARRANGE_BOTTOM || varr === WallBox.ARRANGE_CENTER))
// this.attributes.stretchheight = 1;
}
}
// disable baseline probe if not needed
if (!this.attributes.legacybaseline &&
(this.attributes.flow !== WallBox.FLOW_HORIZONTAL || varr !== WallBox.ARRANGE_BASELINE || numchildren < 2))
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.attributes.legacybaseline = false;
}
super.visitI();
// tappability visualization
this.setRenderedTappable((this.attributes.tappedEvent.handlers || this.contenttapapplies()) ? true : false, false);
}
//isGeneric() {
// return !this.wallLike;
//}
//makeGeneric() {
// if (this.wallLike) {
// this.wallLike = false;
// if (this.parent) this.parent.makeGeneric();
// }
//}
public speculationwascorrect(scroll: boolean): boolean {
return scroll === this.D_scr;
}
private bound(min: number, val: number, max: number): number {
if (min > val)
return min;
if (max < val)
return max;
return val;
}
private tryPreserveAspectRatio(): boolean {
return /img|canvas|video|audio|boardContainer|viewPicture/i.test(this.content.tagName)
|| /boardContainer|viewPicture/i.test(this.content.className);
}
private fillh(f: number): boolean {
if (f <= 0) return false;
if (Math.abs(1-f) < 0.0001 || this.isRoot) return true;
var a = this.attributes.arrangement[WallBox.H];
return (a === WallBox.ARRANGE_LEFT || a === WallBox.ARRANGE_CENTER || a === WallBox.ARRANGE_SPREAD || a === WallBox.ARRANGE_RIGHT);
}
private fillv(f: number): boolean {
if (f <= 0) return false;
if (f == 1 || this.isRoot) return true;
var a = this.attributes.arrangement[WallBox.V];
return (a === WallBox.ARRANGE_TOP || a === WallBox.ARRANGE_BOTTOM || a === WallBox.ARRANGE_CENTER || a === WallBox.ARRANGE_SPREAD );
}
// new layout algorithm
public doLayout() {
this.passA();
this.passBC();
this.passD();
}
private passA() {
this.visitI();
for (var i = 0; i < this.children.length; i++) {
(<WallBox>this.children[i]).passA();
}
this.visitA();
}
private passBC() {
this.visitB();
for (var i = 0; i < this.children.length; i++)
(<WallBox>this.children[i]).passBC();
this.visitC();
}
private passD() {
this.visitD();
for (var i = 0; i < this.children.length; i++)
(<WallBox>this.children[i]).passD();
if (this.layoutcompletehandler)
this.layoutcompletehandler(this.getRenderedWidth(), this.getRenderedHeight());
}
private visitA() {
var numchildren = this.children.length;
if (numchildren === 0) {
// determine width
if (this.contentType != WallBox.CONTENT_NONE && this.cached_width === -1) {
// remove all size settings
this.setRenderedWidth(-1);
this.setRenderedHeight(-1);
if ((this.contentType === WallBox.CONTENT_TEXT || this.contentType === WallBox.CONTENT_INPUT)) {
// update the auxiliary span we use to take measurements
if (this.contentType === WallBox.CONTENT_INPUT) {
var text = this.textarea ? (<HTMLTextAreaElement>this.content).value : (<HTMLInputElement>this.content).value;
text = text + " abc"; // guarantee some free space for typing ahead
this.auxcontent.textContent = text;
}
this.setRenderedWrap(false, this.attributes.wraplimit);
// compute the width it wants to be
var newwidth = (this.contentType === WallBox.CONTENT_INPUT) ?
this.auxcontent.scrollWidth + (this.textarea ? (LayoutMgr.instance.scrollbarWidth + 50) : 50) :
this.element.scrollWidth;
//if (newwidth > this.width[WallBox.MAX]) {
// newwidth = this.attributes.wrap * SizeMgr.topFontSize;
// this.setRenderedWrap(this.attributes.wrap);
// this.setRenderedWidth(newwidth);
// newwidth = (this.contentType === WallBox.CONTENT_INPUT) ? this.auxcontent.scrollWidth : this.element.scrollWidth;
this.setRenderedWrap(this.attributes.wrap, this.attributes.wraplimit);
this.cached_width = newwidth;
this.cached_aspectratio = 0;
// determine baseline if asked for
if (this.attributes.legacybaseline && this.cached_baseline === -1) {
if (!this.baselineprobe) {
this.baselineprobe = span(null, "s");
this.baselineprobe.style.fontSize = "0";
var c = div(null,
span(null, "L"),
this.baselineprobe);
c.style.visibility = "hidden";
c.style.position = "absolute";
this.element.appendChild(c);
}
var yPosition = 0;
this.cached_baseline = this.baselineprobe.offsetTop - this.baselineprobe.scrollTop + this.baselineprobe.clientTop;
this.element.removeChild(this.baselineprobe.parentElement);
this.baselineprobe = null;
}
}
else {
// use attributes if present, or use browser-reported size otherwise
var targetelt = (this.content.className === "viewPicture") ? (<HTMLElement>this.content.firstChild) : this.content;
var ha = targetelt ? Number(targetelt.getAttribute("height")) : 0;
var wa = targetelt ? Number(targetelt.getAttribute("width")) : 0;
// look for attributes on elt
if (targetelt && (targetelt.tagName == "IMG" || targetelt.tagName == "VIDEO" || targetelt.tagName == "AUDIO")) {
ha = ha || (<any>targetelt).height;
wa = wa || (<any>targetelt).width;
}
this.cached_width = wa || this.element.scrollWidth;
this.cached_aspectratio = (this.tryPreserveAspectRatio() && this.cached_width) ?
((ha || this.element.scrollHeight) / this.cached_width) : 0;
// if this is video or audio and we couldn't get any width reported, use default
if ((this.cached_width == 0) && targetelt && (targetelt.tagName == "VIDEO" || targetelt.tagName == "AUDIO")) {
this.cached_width = 300;
}
// if this is an image and we couldn't get any width reported, use default
if ((this.cached_width == 0) && targetelt && (targetelt.tagName == "IMG")) {
this.cached_width = 100;
}
}
}
// determine requested widths
if (this.contentType === WallBox.CONTENT_IMAGE) {
if (this.cached_aspectratio > 0) {
var scmin = this.attributes.height[WallBox.MIN] / this.cached_aspectratio;
var scmax = this.attributes.height[WallBox.MAX] / this.cached_aspectratio;
if ((this.attributes.width[WallBox.MIN] <= scmax) && (this.attributes.width[WallBox.MAX] >= scmin))
// constraints are satisfiable, take them into account
this.A_sc = this.bound(scmin, this.cached_width, scmax);
else
// constraints are not satisfiable, do not take them into account
this.A_sc = this.cached_width;
}
else {
this.A_sc = this.cached_width;
}
this.A_asc = this.A_sc;
var flex = (this.attributes.stretchwidth == 1 || !this.tryPreserveAspectRatio() || (this.attributes.stretchwidth == -1 && this.content && this.content.tagName == "IMG")) ? 1 : 0;
this.A_mc = flex ? 0 : this.A_asc;
this.A_fcc = flex;
} else if (this.contentType === WallBox.CONTENT_TEXT) {
var statedwidth = this.cached_width;
var safetywidth = statedwidth + 1; // need safety margin pixel ... browser are not good at this
this.A_sc = safetywidth;
this.A_asc = (this.attributes.wrap) ? Math.min(this.A_sc, this.attributes.wraplimit * SizeMgr.topFontSize) : this.A_sc;
this.A_mc = this.A_asc;
this.A_fcc = 1;
} else if (this.contentType === WallBox.CONTENT_INPUT) {
this.A_sc = this.cached_width;
this.A_asc = (this.attributes.wrap) ? Math.min(this.A_sc, this.attributes.wraplimit * SizeMgr.topFontSize) : this.A_sc;
this.A_mc = this.A_asc;
this.A_fcc = 1;
} else {
this.A_sc = 0;
this.A_mc = 0;
this.A_asc = 0;
this.A_fcc = 0;
}
}
else {
// composite node
if (this.attributes.flow === WallBox.FLOW_HORIZONTAL) {
var lm_s = this.attributes.padding[WallBox.L];
var lm_f = 0;
this.A_mc = lm_s;
this.A_sc = lm_s;
this.A_scc = 0;
this.A_asc = lm_s;
this.A_fcc = 0;
this.A_fcs = 0;
this.A_fp = 0;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
var ws = Math.max(0, child.A_sl - lm_s) + child.A_sr;
lm_s = child.A_sr;
if (i == numchildren - 1)
ws += Math.max(0, this.attributes.padding[WallBox.R] - lm_s);
this.A_mc += child.A_m + ws;
this.A_sc += child.A_s + ws;
this.A_scc += child.A_s;
this.A_asc += child.A_as + ws;
this.A_fcc += child.A_f;
this.A_fcs += Math.max(0, child.A_fl - lm_f) + child.A_fr;
this.A_fp = this.A_fp || child.A_fp;
lm_f = child.A_fr;
}
} else if (this.attributes.flow === WallBox.FLOW_VERTICAL || this.attributes.flow === WallBox.FLOW_OVERLAY) {
this.A_mc = 0;
this.A_sc = 0;
this.A_asc = 0;
this.A_fcc = 0;
this.A_fp = 0;
for (var i = 0; i < this.children.length; i++) {
var child = <WallBox> this.children[i];
var ws = Math.max(child.A_sl, this.attributes.padding[WallBox.L]) + Math.max(child.A_sr, this.attributes.padding[WallBox.R]);
this.A_mc = Math.max(this.A_mc, child.A_m + ws);
this.A_asc = Math.max(this.A_asc, child.A_as + ws);
this.A_sc = Math.max(this.A_sc, child.A_s + ws);
this.A_fcc = Math.max(this.A_fcc, child.A_f);
this.A_fp = this.A_fp || child.A_fp;
}
}
}
var min = this.attributes.width[WallBox.MIN];
var max = this.attributes.width[WallBox.MAX];
var borderwidth = this.attributes.borderwidth[WallBox.L] + this.attributes.borderwidth[WallBox.R];
this.A_scr = (this.attributes.scroll[WallBox.V] && (!this.isRoot || LayoutMgr.instance.scrollspeculation)) ? LayoutMgr.instance.scrollbarWidth : 0;
this.A_m = this.bound(min, (this.attributes.scroll[WallBox.H] ? Math.min(this.A_mc, SizeMgr.topFontSize*6) : this.A_mc) + this.A_scr, max) + borderwidth;
this.A_as = this.bound(min, (this.attributes.scroll[WallBox.H] ? Math.min(this.A_mc, SizeMgr.topFontSize * 10) : this.A_asc) + this.A_scr, max) + borderwidth;
this.A_s = this.bound(min, this.A_sc + this.A_scr, max) + borderwidth;
this.A_sl = this.attributes.margin[WallBox.L];
this.A_sr = this.attributes.margin[WallBox.R];
this.A_f = (this.attributes.stretchwidth == -1) ? ((this.A_fp || (numchildren == 0)) ? (this.fillh(this.A_fcc) ? 1 : this.A_fcc) : 0) : this.attributes.stretchwidth;
this.A_fp = (this.attributes.stretchwidth == -1) ? ((numchildren > 0) && (max > min) && this.A_fp) : (this.attributes.legacystretch[WallBox.H] ? 0 : this.attributes.stretchwidth);
this.A_fl = this.attributes.stretchmargin[WallBox.L];
this.A_fr = this.attributes.stretchmargin[WallBox.R];
}
private visitB() {
if (this.isRoot) {
// get algorithm inputs from window constraints
this.B_x = 0;
//this.B_s = window.innerWidth;
this.B_s = this.runtime.host.fullWallWidth();
}
var borderwidth = (this.attributes.borderwidth[WallBox.L] + this.attributes.borderwidth[WallBox.R]);
var allowance = this.B_s - this.A_scr - borderwidth;
var numchildren = this.children.length;
var overflow = false;
if (numchildren == 0) {
// leaf node
this.B_scr = false;
} else {
// composite node
overflow = allowance < this.A_mc;
this.B_scr = (overflow && this.attributes.scroll[WallBox.H]);
if (this.attributes.flow === WallBox.FLOW_VERTICAL || this.attributes.flow === WallBox.FLOW_OVERLAY) {
var pl = this.attributes.padding[WallBox.L];
var pr = this.attributes.padding[WallBox.R];
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
var ws = Math.max(Math.max(pl, child.A_sl) + Math.max(pr, child.A_sr));
if (allowance > child.A_s + ws) {
// we have enough for requested width
var extra_c = 0;
if (child.A_f) {
var proportion = (child.A_f < 1 && this.fillh(child.A_f)) ? child.A_f : 1;
extra_c = Math.max(0, Math.min(proportion*allowance - ws, child.attributes.width[WallBox.MAX]) - child.A_s);
}
child.B_s = child.A_s + extra_c;
var extra_s = (child.A_fl + child.A_fr) ? ((allowance - child.B_s - ws) / (child.A_fl + child.A_fr)) : 0;
child.B_x = Math.max(pl,child.A_sl) + extra_s * child.A_fl;
}
else if (allowance > child.A_as + ws) {
// we have enough for alt width
child.B_x = Math.max(pl,child.A_sl);
child.B_s = allowance - ws;
}
else if (this.B_scr) {
// we are scrolling, use alt width
child.B_x = Math.max(pl,child.A_sl);
child.B_s = child.A_as;
}
else {
// take what we can
child.B_x = Math.max(pl,child.A_sl);
child.B_s = Math.max(child.A_m, allowance - ws);
}
}
}
else if (this.attributes.flow === WallBox.FLOW_HORIZONTAL) {
if (allowance >= this.A_sc) {
// we have enough for requested width
var apply_fractional_stretches = this.fillh(this.A_fcc);
var space_for_content = allowance - (this.A_sc - this.A_scc);
// first, give extra space to content that wants it
var remainder = space_for_content;
var wsum = this.A_fcc;
var csum = this.A_scc;
if (remainder === 0 || wsum === 0)
this.children.forEach((c:WallBox) => remainder -= (c.B_s = c.A_s));
else {
var limit = (c:WallBox) => {
if (!apply_fractional_stretches || c.A_f >= 1)
return c.attributes.width[WallBox.MAX];
else
return Math.max(c.A_s, Math.min(c.attributes.width[WallBox.MAX], space_for_content * c.A_f));
};
var sortedlist = this.children.slice(0).sort((wb1: WallBox, wb2: WallBox) => limit(wb1) - limit(wb2));
for (var i = 0; i < sortedlist.length; i++) {
var c = <WallBox> sortedlist[i];
c.B_s = (c.A_f == 0) ? c.A_s : ((!apply_fractional_stretches || c.A_f >= 1) ?
Math.min(c.attributes.width[WallBox.MAX], c.A_s + ((remainder - csum) / wsum) * c.A_f)
: Math.max(c.A_s, Math.min(c.attributes.width[WallBox.MAX], space_for_content * c.A_f)));
remainder -= c.B_s;
csum -= c.A_s;
wsum -= c.A_f;
}
}
// then, give extra space wo white space
var extra_s = this.A_fcs ? (remainder / this.A_fcs) : 0;
var ls = this.attributes.padding[WallBox.L];
var lf = 0;
var x = ls;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
x = x + Math.max(0, child.A_sl - ls) + Math.max(0, extra_s * child.A_fl - lf);
child.B_x = x;
ls = child.A_sr;
lf = extra_s * child.A_fr;
x = x + child.B_s + ls + lf;
}
}
else {
if (allowance > this.A_asc) {
// we have enough for requested alternate width
this.distribute(allowance - this.A_asc,
(child: WallBox) => child.A_s - child.A_as,
(child: WallBox, give: number) => { child.B_s = child.A_as + give });
}
else if (this.B_scr) {
// scrolling - everybody gets alt width
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
child.B_s = child.A_as;
}
}
else {
// minimum width
overflow = true;
this.distribute(this.A_asc - allowance,
(child: WallBox) => child.A_as - child.A_m,
(child: WallBox, take: number) => { child.B_s = child.A_as - take });
}
// assign position
var x = 0;
var lastmargin = this.attributes.padding[WallBox.L];
for (var i = 0; i < numchildren; i++) {
var child = <WallBox> this.children[i];
x = x + Math.max(lastmargin, child.A_sl);
child.B_x = x;
x = x + child.B_s;
lastmargin = child.A_sr;
}
}
}
}
// output to rendering
if (!this.delayedlayout)
this.setRenderedWidth(this.B_s - borderwidth);
this.setRenderedHorizontalOverflow(this.B_scr ? "scroll" : (overflow ? "hidden" : ""));
this.setRenderedX(this.B_x);
}
private distribute(
amount: number,
limit: (wb: WallBox) => number,
apply: (wb: WallBox, amount: number) => void )
{
if (amount === 0) {
for (var i = 0; i < this.children.length; i++)
apply(<WallBox>this.children[i], 0);
}
else {
var takers = this.children.length;
var sortedlist = this.children.slice(0).sort((wb1: WallBox, wb2: WallBox) => limit(wb1) - limit(wb2));
for (var i = 0; i < this.children.length; i++) {
var child = <WallBox>sortedlist[i];
var take = Math.min(limit(child), amount / takers);
amount -= take;
apply(child, take);
takers--;
}
}
}
private visitC() {
var numchildren = this.children.length;
if (numchildren === 0) {
// we are on leaf
// determine height
if (this.contentType != WallBox.CONTENT_NONE && this.cached_height === -1) {
if (this.contentType == WallBox.CONTENT_IMAGE) {
var targetelt = (this.content.className === "viewPicture") ? (<HTMLElement>this.content.firstChild) : this.content;
this.cached_height = targetelt ? Number(targetelt.getAttribute("height")) : 0;
if (!this.cached_height && this.content && this.content.tagName == "IMG") {
this.cached_height = (<HTMLImageElement> targetelt).height;
}
if (!this.cached_height) {
this.setRenderedHeight(-1);
this.cached_height = this.element.clientHeight;
}
}
else if (this.contentType == WallBox.CONTENT_INPUT) {
this.setRenderedHeight(-1);
this.cached_height = this.auxcontent.scrollHeight + (this.textarea ? 5 : 0);
} else {
this.setRenderedHeight(-1);
this.cached_height = this.element.clientHeight;
}
}
// initialize algorithm inputs
if (this.contentType === WallBox.CONTENT_IMAGE) {
if (this.cached_aspectratio > 0) // try to preserve aspect ratio
this.C_sc = ((this.delayedlayout ? this.cached_width : this.getRenderedWidth()) * this.cached_aspectratio);
else // cannot preserve aspect ratio
this.C_sc = this.cached_height;
this.C_mc = this.attributes.stretchheight == 1 ? 0 : this.C_sc;
this.C_bc = 0;
this.C_fcc = this.attributes.stretchheight == 1 ? 1 : 0;
}
else if (this.contentType === WallBox.CONTENT_TEXT) {
this.C_sc = this.cached_height + 1; // add 1 for browser inaccuracy
this.C_mc = this.C_sc; // want all of it
this.C_bc = this.cached_baseline;
this.C_fcc = 0;
}
else if (this.contentType === WallBox.CONTENT_INPUT) {
this.C_sc = this.cached_height + (this.textarea ? 1 : 6);
this.C_mc = this.C_sc; // want all of it
this.C_bc = this.cached_baseline;
this.C_fcc = 0;
} else {
this.C_sc = 0;
this.C_mc = 0;
this.C_bc = 0;
this.C_fcc = 0;
}
this.C_zc = 1;
}
else {
this.C_bc = 0;
var dobaseline = (this.attributes.arrangement[WallBox.V] === WallBox.ARRANGE_BASELINE);
if (this.attributes.flow === WallBox.FLOW_VERTICAL) {
// find baseline adjustment
var firstchild = <WallBox>this.children[0];
if (dobaseline && firstchild.C_b) {
this.C_bc = firstchild.C_b + Math.max(this.attributes.padding[WallBox.T], firstchild.C_st);
}
var bm_s = this.attributes.padding[WallBox.T];
var bm_f = 0;
this.C_sc = bm_s;
this.C_scc = 0;
this.C_mc = bm_s;
this.C_fcc = 0;
this.C_fcs = 0;
this.C_fp = 0;
this.C_zc = 1;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
var ws = Math.max(0, child.C_st - bm_s) + child.C_sb;
bm_s = child.C_sb;
if (i == numchildren-1)
ws += Math.max(0, this.attributes.padding[WallBox.B] - bm_s);
this.C_sc += child.C_s + ws;
this.C_scc += child.C_s;
this.C_mc += child.C_m + ws;
this.C_fcc += child.C_f;
this.C_fcs += Math.max(0, child.C_ft - bm_f) + child.C_fb;
this.C_fp = this.C_fp || child.C_fp;
bm_f = child.C_fb;
this.C_zc = Math.max(this.C_zc, 1 + child.C_zc);
}
} else if (this.attributes.flow === WallBox.FLOW_HORIZONTAL || this.attributes.flow === WallBox.FLOW_OVERLAY) {
// var pos = 0;
//for (var line = 0; pos < this.children.length; line++) {
//var lsa = 0;
//var lst = 0;
//var lsb = 0;
//var lft = true;
//var lf = true;
//var lfb = true;
//for (var col = 0; pos < this.children.length && this.children[pos].B_g == line; col++) {
// var child = this.children[pos];
// if (child.B_g > line) break;
// lsa = Math.max(lsa, child.C_st + child.C_s + child.C_sb);
// lst = Math.max(lsa, child.C_st + child.C_s + child.C_sb);
// lsb = Math.max(lsa, child.C_st + child.C_s + child.C_sb);
// lft = lft && child.C_ft;
if (dobaseline)
for (var i = 0; i < this.children.length; i++) {
var child = <WallBox>this.children[i];
if (child.C_b)
this.C_bc = Math.max(this.C_bc, child.C_b + Math.max(this.attributes.padding[WallBox.T], child.C_st));
}
this.C_sc = 0;
this.C_mc = 0;
this.C_fcc = 0;
this.C_fp = 0;
this.C_zc = 1;
for (var i = 0; i < this.children.length; i++) {
var child = <WallBox>this.children[i];
var wst = Math.max(this.attributes.padding[WallBox.T], child.C_st);
var bsa = child.C_b ? Math.max(0, this.C_bc - (child.C_b + wst)) : 0;
var ws = wst + bsa + Math.max(this.attributes.padding[WallBox.B], child.C_sb);
this.C_sc = Math.max(this.C_sc, child.C_s + ws);
this.C_mc = Math.max(this.C_mc, child.C_m + ws);
this.C_fcc = Math.max(this.C_fcc, child.C_f);
this.C_fp = this.C_fp || child.C_fp;
if (this.attributes.flow === WallBox.FLOW_OVERLAY)
this.C_zc = this.C_zc + child.C_zc;
else
this.C_zc = Math.max(this.C_zc, 1 + child.C_zc);
}
}
}
var min = this.attributes.height[WallBox.MIN];
var max = this.attributes.height[WallBox.MAX];
var borderwidth = this.attributes.borderwidth[WallBox.T] + this.attributes.borderwidth[WallBox.B];
this.C_scr = this.B_scr ? LayoutMgr.instance.scrollbarHeight : 0;
this.C_m = this.bound(min, (this.attributes.scroll[WallBox.V] ? Math.min(this.C_mc, SizeMgr.topFontSize * 6) : this.C_mc) + this.C_scr, max) + borderwidth;
this.C_s = this.bound(min, this.C_sc + this.C_scr, max) + borderwidth;
this.C_st = this.attributes.margin[WallBox.T];
this.C_sb = this.attributes.margin[WallBox.B];
this.C_f = (this.attributes.stretchheight == -1) ? ((this.C_fp || (numchildren == 0)) ? (this.fillv(this.C_fcc) ? 1 : this.C_fcc) : 0) : this.attributes.stretchheight;
this.C_fp = (this.attributes.stretchheight == -1) ? ((numchildren > 0) && (max > min) && this.C_fp) : (this.attributes.legacystretch[WallBox.V] ? 0 : this.attributes.stretchheight);
this.C_ft = this.attributes.stretchmargin[WallBox.T];
this.C_fb = this.attributes.stretchmargin[WallBox.B];
this.C_b = (this.attributes.legacybaseline && this.C_bc) ? (this.C_bc + this.attributes.borderwidth[WallBox.T]) : 0;
}
private visitD() {
// input from the top element
if (this.isRoot) {
this.D_y = 0;
//this.D_s = window.innerHeight - SizeMgr.topFontSize * 4;
this.D_s = this.runtime.host.userWallHeight();
this.D_z = 1;
this.D_b = this.C_b;
}
var overflow = false;
var borderwidth = (this.attributes.borderwidth[WallBox.T] + this.attributes.borderwidth[WallBox.B]);
var allowance = this.D_s - this.C_scr - borderwidth;
var baseline = this.attributes.legacybaseline ? ((this.attributes.arrangement[WallBox.V]===WallBox.ARRANGE_BASELINE) ? Math.max(this.C_bc,this.D_b - this.attributes.borderwidth[WallBox.T]) : 0) : this.C_bc;
var numchildren = this.children.length;
if (numchildren === 0) {
// leaf node
this.D_scr = false;
} else {
// composite node
overflow = allowance < this.C_mc + this.C_scr;
this.D_scr = (overflow && this.attributes.scroll[WallBox.V]);
var nextz = this.D_z + 1;
if (this.attributes.flow === WallBox.FLOW_HORIZONTAL || this.attributes.flow === WallBox.FLOW_OVERLAY) {
var pt = this.attributes.padding[WallBox.T];
var pb = this.attributes.padding[WallBox.B];
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
var wst = Math.max(pt, child.C_st, child.C_b ? Math.max(0, baseline - child.C_b) : 0);
var ws = wst + Math.max(pb, child.C_sb);
if (allowance > child.C_s + ws) {
// we have enough for requested width
var extra_c = 0;
if (child.C_f)
{
var proportion = (child.C_f < 1 && this.fillv(child.C_f)) ? child.C_f : 1;
extra_c = Math.max(0, Math.min(allowance*proportion - ws, child.attributes.height[WallBox.MAX]) - child.C_s);
}
child.D_s = child.C_s + extra_c;
var extra_s = (child.C_ft + child.C_fb) ? ((allowance - child.D_s - ws) / (child.C_ft + child.C_fb)) : 0;
child.D_y = wst + extra_s * child.C_ft;
}
else if (this.D_scr) {
// we are scrolling - give full requested size
child.D_y = wst;
child.D_s = child.C_s;
} else {
// shrink as much as possible
child.D_y = wst;
child.D_s = Math.max(child.C_m, allowance - ws);
}
child.D_b = Math.max(0, baseline - child.D_y);
child.D_z = nextz;
if (this.attributes.flow === WallBox.FLOW_OVERLAY)
nextz = nextz + child.C_zc;
}
}
else if (this.attributes.flow === WallBox.FLOW_VERTICAL) {
var firstchild = <WallBox>this.children[0];
var bsa = firstchild.C_b ? Math.max(0, baseline - firstchild.C_b) : 0;
var pt = Math.max(this.attributes.padding[WallBox.T], bsa);
if (allowance >= this.C_sc) {
// we have enough for requested width
var apply_fractional_stretches = this.fillv(this.C_fcc);
var space_for_content = allowance - (this.C_sc - this.C_scc);
// first, give extra space to content that wants it
var remainder = space_for_content;
var wsum = this.C_fcc;
var csum = this.C_scc;
if (remainder === 0 || wsum === 0)
this.children.forEach((c:WallBox) => remainder -= (c.D_s = c.C_s));
else {
var limit = c => {
if (!apply_fractional_stretches || c.C_f >= 1)
return c.attributes.height[WallBox.MAX];
else
return Math.max(c.C_s, Math.min(c.attributes.height[WallBox.MAX], space_for_content * c.C_f));
};
var sortedlist = this.children.slice(0).sort((wb1: WallBox, wb2: WallBox) => limit(wb1) - limit(wb2));
for (var i = 0; i < sortedlist.length; i++) {
var c = <WallBox> sortedlist[i];
c.D_s = (c.C_f == 0) ? c.C_s : ((!apply_fractional_stretches || c.C_f >= 1) ?
Math.min(c.attributes.height[WallBox.MAX], c.C_s + ((remainder - csum) / wsum) * c.C_f)
: Math.max(c.C_s, Math.min(c.attributes.height[WallBox.MAX], space_for_content * c.C_f)));
remainder -= c.D_s;
csum -= c.C_s;
wsum -= c.C_f;
}
}
// then, give extra space to white space that wants it
var extra_s = this.C_fcs ? (remainder / this.C_fcs) : 0;
var y = pt;
var ls = pt;
var lf = 0;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
y = y + Math.max(0, child.C_st - ls) + Math.max(0, extra_s * child.C_ft - lf);
child.D_y = y;
ls = child.C_sb;
lf = extra_s * child.C_fb;
y = y + child.D_s + ls + lf;
child.D_z = nextz;
child.D_b = Math.max(0, baseline - child.D_y);
}
}
else {
if (this.D_scr) {
// we are scrolling - give full requested size
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
child.D_s = child.C_s;
}
}
else if (allowance > this.C_mc) {
this.distribute(allowance - this.C_mc,
(child: WallBox) => child.C_s - child.C_m,
(child: WallBox, give: number) => { child.D_s = child.C_m + give });
} else {
// give minimum width
overflow = allowance < this.C_mc;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
child.D_s = child.C_m;
}
}
// assign position
var y = 0;
var lastmargin = pt;
for (var i = 0; i < numchildren; i++) {
var child = <WallBox>this.children[i];
y = y + Math.max(lastmargin, child.C_st);
child.D_y = y;
child.D_b = Math.max(0, baseline - child.D_y);
y = y + child.D_s;
lastmargin = child.C_sb;
child.D_z = nextz;
child.D_b = Math.max(0, baseline - child.D_y);
}
}
}
}
// output to the HTML element
if (!this.delayedlayout)
this.setRenderedHeight(this.D_s - borderwidth);
this.setRenderedVerticalOverflow(this.D_scr ? "scroll" : (overflow ? "hidden" : ""));
this.setRenderedY(this.D_y);
this.setRenderedZIndex(this.D_z);
}
public getEditableContent(): string {
Util.assert(this.contentType == WallBox.CONTENT_INPUT);
return this.textarea ? (<HTMLTextAreaElement>this.content).value : (<HTMLInputElement>this.content).value
}
public setEditableContent(text: string) {
Util.assert(this.contentType == WallBox.CONTENT_INPUT);
if (this.textarea)
(<HTMLTextAreaElement>this.content).value = text;
else
(<HTMLInputElement>this.content).value = text;
}
public invalidateCachedLayout(triggerdelayedrelayout: boolean) {
this.cached_width = -1;
this.cached_height = -1;
if (triggerdelayedrelayout)
TDev.Util.setTimeout(100, () => {
if (this.cached_width === -1)
LayoutMgr.QueueReLayout();
});
}
onInputTextChangeDone() {
if (this.obsolete)
return; // box may be already gone from screen
if (LayoutMgr.instance.editMode) {
// don't do anything in edit mode
} else {
this.cached_width = -1;
this.cached_height = -1;
var parent = this.parent;
var text = this.textarea ? (<HTMLTextAreaElement>this.content).value : (<HTMLInputElement>this.content).value;
if (parent && (<LayoutAttributes>parent.attributes).textEditedEvent.handlers) {
this.runtime.queueLocalEvent((<LayoutAttributes>parent.attributes).textEditedEvent, [text]);
}
this.runtime.forcePageRefresh(); // we need to ensure display is updated.
}
}
// Getters
public size(): number { return this.children.length; }
public get(index: number): BoxBase { return this.children[index]; }
public shift(): void {
if (this.children.length > 0)
this.children.shift();
}
public forEachChild(f: (WallBox) =>any) { this.children.forEach(f); }
public getDepth(): number { return this.depth; }
public getId(): number { return this.id; }
public getElement(): HTMLElement { return this.element; }
public getFlow(): number { return this.attributes.flow; }
public getAlign(): number { return this.attributes.textalign; }
public getBackground(): string { return this.attributes.background; }
public getForeground(): string { return this.attributes.foreground; }
public getFontSize(): number { return this.attributes.fontSize; }
public getFontWeight(): string { return this.attributes.fontWeight; }
public getFontFamily(): string { return this.attributes.fontFamily; }
/*
public getMinWidth(): number { return this.width[WallBox.MIN]; }
public getMaxWidth(): number { return this.width[WallBox.MAX]; }
public getMinHeight(): number { return this.height[WallBox.MIN]; }
public getMaxHeight(): number { return this.height[WallBox.MAX]; }
public getMargin(direction: number): number { return this.margin[direction]; }
public getTopMargin(): number { return this.margin[WallBox.T]; }
public getRightMargin(): number { return this.margin[WallBox.R]; }
public getBottomMargin(): number { return this.margin[WallBox.B]; }
public getLeftMargin(): number { return this.margin[WallBox.L]; }
*/
// public getX(): number { return this.rendered_x; }
// public getY(): number { return this.rendered_y; }
public getRenderedWidth(): number { return this.rendered_width; }
public getRenderedHeight(): number { return this.rendered_height; }
//public getRenderedMargin(direction: number): number { return this.rendered_margin[direction]; }
//public getRenderedTopMargin(): number { return this.rendered_margin[WallBox.T]; }
//public getRenderedRightMargin(): number { return this.rendered_margin[WallBox.R]; }
//public getRenderedBottomMargin(): number { return this.rendered_margin[WallBox.B]; }
//public getRenderedLeftMargin(): number { return this.rendered_margin[WallBox.L]; }
//public getHorizontalScrollbar(): boolean { return this.rendered_hscrollbar; }
// public getVerticalScrollbar(): boolean { return this.rendered_vscrollbar; }
//public getContentType(): number { return this.contentType; }
public getContent(): HTMLElement { return this.content; }
// Functions for setting box attributes. Called from user code.
public setFlow(flow: number, pc = "") { this.attributes.flow = flow; this.onCall("flow", pc); }
public setBackground(background: string, pc = "") { this.attributes.background = background; this.onCall("background", pc); }
public addBackgroundImage(img: BoxBackgroundImage, pc = "") {
if (!this.attributes.backgroundImages) this.attributes.backgroundImages = [];
this.attributes.backgroundImages.splice(0, 0, img); this.onCall("background image", pc);
}
public setForeground(foreground: string, pc = "") { this.attributes.foreground = foreground; this.onCall("foreground", pc); }
public setFontSize(fontSize: number, pc = "") { this.attributes.fontSize = fontSize; this.onCall("font size", pc); }
public setFontWeight(fontWeight: string, pc = "") { this.attributes.fontWeight = fontWeight; this.onCall("font weight", pc); }
public setFontFamily(fontFamily: string, pc = "") { this.attributes.fontFamily = fontFamily; this.onCall("font family", pc); }
public setScrolling(h: boolean, v: boolean, pc = "") {
this.attributes.scroll = [h, v];
this.onCall("scrolling", pc);
}
public setEmBorder(color: string, width: number, pc = "") {
this.attributes.border = color;
var bw = SizeMgr.topFontSize * width;
this.attributes.borderwidth = [bw, bw, bw, bw];
this.onCall("border", pc);
}
public setBorderWidth(top: number, right: number, bottom: number, left: number, pc = "") {
this.attributes.borderwidth = [top, right, bottom, left];
this.onCall("border widths", pc);
}
public setAllMargins(top: number, right: number, bottom: number, left: number, pc = "") {
this.attributes.margin = [top, right, bottom, left];
this.onCall("margins", pc);
}
public setPadding(top: number, right: number, bottom: number, left: number, pc = "") {
this.attributes.padding = [top, right, bottom, left];
this.onCall("margins", pc);
}
public setWrap(wrap: boolean, width: number, pc = "") { this.attributes.wrap = wrap; this.attributes.wraplimit = Math.max(width,1); this.onCall("text wrap", pc); }
public setWidth(width: number, pc = "") { this.attributes.width = [width, width]; this.onCall("width", pc); }
public setWidthRange(minWidth: number, maxWidth: number, pc = "") { this.attributes.width[WallBox.MIN] = minWidth; this.attributes.width[WallBox.MAX] = maxWidth; this.onCall("width range", pc); }
public setHorizontalStretch(n: number, pc = "") {
this.attributes.stretchwidth = n;
this.onCall("horizontal stretch", pc);
}
public setVerticalStretch(n: number, pc = "") {
this.attributes.stretchheight = n;
this.onCall("vertical stretch", pc);
}
public setHorizontalAlignment(left: number, right: number, pc = "") {
left = Math.max(0, Math.min(1,left));
right = Math.max(0, Math.min(1,right));
if (left < 1) this.attributes.stretchmargin[WallBox.L] = (1 - left);
if (right < 1) this.attributes.stretchmargin[WallBox.R] = (1 - left);
if (left > 0 && right > 0)
this.attributes.stretchwidth = 1;
if (right == 0 && left != 0)
this.attributes.textalign = WallBox.ARRANGE_LEFT;
else if (right != 0 && left == 0)
this.attributes.textalign = WallBox.ARRANGE_RIGHT;
else if (right == 0 && left == 0)
this.attributes.textalign = WallBox.ARRANGE_CENTER;
else
this.attributes.textalign = WallBox.ARRANGE_JUSTIFY;
this.attributes.legacystretch[WallBox.H] = true;
this.onCall("horizontal alignment", pc);
}
public setVerticalAlignment(top: number, bottom: number, pc = "") {
top = Math.max(0, Math.min(1,top));
bottom = Math.max(0, Math.min(1,bottom));
if (top < 1) this.attributes.stretchmargin[WallBox.T] = (1 - top);
if (bottom < 1) this.attributes.stretchmargin[WallBox.B] = (1 - bottom);
if (top > 0 && bottom > 0) this.attributes.stretchheight = 1;
this.attributes.legacybaseline = false;
this.attributes.legacystretch[WallBox.V] = true;
this.onCall("vertical alignment", pc);
}
public setHorizontalArrangement(what: number, pc = "") {
this.attributes.arrangement[WallBox.H] = what;
this.attributes.textalign = what;
this.onCall("horizontal arrangement", pc);
}
public setVerticalArrangement(what: number, pc = "") {
this.attributes.arrangement[WallBox.V] = what;
if (what != WallBox.ARRANGE_BASELINE)
this.attributes.legacybaseline = false;
this.onCall("vertical arrangement", pc);
}
// public stretchAllMargins(top: number, right: number, bottom: number, left: number, pc = "") {
// this.attributes.stretchmargin = [top, right, bottom, left];
// this.onCall("stretch margins", pc);
//}
//public setWidthStretch(weight: number, pc = "") { this.attributes.stretchwidth = ((weight < 0) ? WallBox.STRETCH_AUTO : weight); this.onCall("stretch width", pc); }
//public setHeightStretch(weight: number, pc = "") { this.attributes.stretchheight = ((weight < 0) ? WallBox.STRETCH_AUTO : weight); this.onCall("stretch height", pc); }
public setHeight(height: number, pc = "") { this.attributes.height = [height, height]; this.onCall("height", pc); }
public setHeightRange(minHeight: number, maxHeight: number, pc = "") { this.attributes.height[WallBox.MIN] = minHeight; this.attributes.height[WallBox.MAX] = maxHeight; this.onCall("height range", pc); }
public setEmFontSize(fontSize: number, pc = "") { this.setFontSize(SizeMgr.topFontSize * fontSize, pc); }
public setEmBorderWidth(top: number, right: number, bottom: number, left: number, pc = "") {
this.setBorderWidth(SizeMgr.topFontSize * top, SizeMgr.topFontSize * right, SizeMgr.topFontSize * bottom, SizeMgr.topFontSize * left, pc);
}
public setAllEmMargins(top: number, right: number, bottom: number, left: number, pc = "") {
this.setAllMargins(SizeMgr.topFontSize * top, SizeMgr.topFontSize * right, SizeMgr.topFontSize * bottom, SizeMgr.topFontSize * left, pc);
}
public setEmPadding(top: number, right: number, bottom: number, left: number, pc = "") {
this.setPadding(SizeMgr.topFontSize * top, SizeMgr.topFontSize * right, SizeMgr.topFontSize * bottom, SizeMgr.topFontSize * left, pc);
}
public setEmWidth(width: number, pc = "") { this.setWidth(SizeMgr.topFontSize * width, pc); }
public setEmWidthRange(minWidth: number, maxWidth: number, pc = "") { this.setWidthRange(SizeMgr.topFontSize * minWidth, SizeMgr.topFontSize * maxWidth, pc); }
public setEmHeight(height: number, pc = "") { this.setHeight(SizeMgr.topFontSize * height, pc); }
public setEmHeightRange(minHeight: number, maxHeight: number, pc = "") { this.setHeightRange(SizeMgr.topFontSize * minHeight, SizeMgr.topFontSize * maxHeight, pc); }
public setContent(e: any) {
Util.check(e != null);
if (e instanceof HTMLTextAreaElement || e instanceof HTMLInputElement) {
this.contentType = WallBox.CONTENT_INPUT;
this.content = e;
this.auxcontent = span("wall-text", "");
this.auxcontent.style.visibility = "hidden"; // make this visible for debugging
this.auxcontent.style.position = "absolute";
this.auxcontent.style.left = "0px";
this.auxcontent.style.top = "0px";
this.auxcontent.style.padding = "1px";
this.auxcontent.style.color = "red";
this.auxcontent.style.zIndex = "-1";
}
else if (e instanceof HTMLElement) {
this.contentType = WallBox.CONTENT_IMAGE;
this.content = e;
} else {
this.contentType = WallBox.CONTENT_TEXT;
var str = (e || "").toString();
this.content = span("wall-text", str);
}
}
// functions for manipulating the appearance of the HTML element. Called by layout algorithm.
setRenderedX(x: number) {
if (x !== this.rendered_x) {
if (typeof (this.rendered_x) === "invalid" && !this.isRoot) {
this.element.style.position = "absolute";
}
this.element.style.left = x + "px";
this.rendered_x = x;
}
}
setRenderedY(y: number) {
if (y !== this.rendered_y) {
this.element.style.top = y + "px";
this.rendered_y = y;
}
}
setRenderedWidth(width: number) {
if (width !== this.rendered_width) {
this.element.style.width = (width >= 0) ? (width + "px") : "";
if (this.contentType != WallBox.CONTENT_NONE && this.contentType != WallBox.CONTENT_TEXT) {
var extra = (this.contentType == WallBox.CONTENT_INPUT && !this.textarea) ? 6 : 0;
var targetelt = (this.content.className === "viewPicture") ? (<HTMLElement>this.content.firstChild) : this.content;
if (targetelt)
targetelt.style.width = (width > 0) ? ((width - extra) + "px") : "";
if (this.contentType === WallBox.CONTENT_INPUT && this.textarea)
this.auxcontent.style.width = (width >= 0) ? ((width - 10) + "px") : "";
}
this.rendered_width = width;
this.cached_height = -1;
}
}
setRenderedHeight(height: number) {
if (height !== this.rendered_height) {
this.element.style.height = (height > 0) ? (height + "px") : "";
if (this.contentType != WallBox.CONTENT_NONE && this.contentType != WallBox.CONTENT_TEXT) {
var extra = (this.contentType == WallBox.CONTENT_INPUT && !this.textarea) ? 6 : 0;
var targetelt = (this.content.className === "viewPicture") ? (<HTMLElement>this.content.firstChild) : this.content;
if (targetelt)
targetelt.style.height = (height > 0) ? ((height - extra) + "px") : "";
if (this.contentType == WallBox.CONTENT_INPUT && this.textarea && height >= this.cached_height) {
this.content.style.overflow = "hidden"; // make sure IE does not display gray scroll bars
}
}
this.rendered_height = height;
}
}
setRenderedFontFamily(family: string) {
if (family !== this.rendered_fontfamily) {
this.element.style.fontFamily = (family === "Default" ? '"Segoe UI", "Segoe WP", "Helvetica Neue", Sans-Serif' : family);
this.rendered_fontfamily = family;
this.cached_height = -1;
this.cached_baseline = -1;
this.cached_width = -1;
}
}
setRenderedFontWeight(fw: string) {
var fontweight = fw || "inherit";
if (fontweight !== this.rendered_fontweight) {
this.element.style.fontWeight = fontweight;
this.rendered_fontweight = fontweight;
this.cached_height = -1;
this.cached_baseline = -1;
this.cached_width = -1;
}
}
setRenderedFontSize(size: number) {
if (size !== this.rendered_fontsize) {
this.element.style.fontSize = (size > 0) ? (size + "px") :"inherit";
this.rendered_fontsize = size;
this.cached_height = -1;
this.cached_baseline = -1;
this.cached_width = -1;
}
}
setRenderedColor(clr: string) {
var color = clr || "inherit";
if (color !== this.rendered_foregroundcolor) {
this.element.style.color = color;
this.rendered_foregroundcolor = color;
}
}
setRenderedBackgroundColor(color: string) {
if (color !== this.rendered_backgroundcolor) {
this.element.style.backgroundColor = color;
this.rendered_backgroundcolor = color;
}
}
setRenderedBackgroundImages(images: BoxBackgroundImage[]) {
var css = images ? images.map(img => HTML.cssImage(img.url) + ' '
+ (img.position || 'center')
+ ' / ' + (img.size || 'cover')
+ ' ' + (img.repeat || 'no-repeat')
+ ' ' + (img.attachment || 'scroll')
).join(', ') : '';
if(css !== this.rendered_background) {
this.element.style.background = css;
this.rendered_background = css;
}
}
//setRenderedTagname(name: string) {
// if (this.element.tagName !== name) {
// var original = this.element;
// var copy = document.createElement(name);
// if (original.attributes)
// for (var i = 0; i < original.attributes.length; i++) {
// var a = original.attributes.item(i);
// copy.setAttribute(a.nodeName, a.nodeValue);
// }
// while (original.firstChild) {
// copy.appendChild(original.firstChild);
//}
// if (original.parentNode)
// original.parentNode.replaceChild(copy, original);
// this.element = copy;
// }
//}
setRenderedTappable(tappable: boolean, tapped: boolean) {
var x = "wall-box" + (tappable ? " tappable " : "") + (tapped ? " tapped" : "");
if (x !== this.rendered_tappable) {
this.element.className = x;
this.rendered_tappable = x;
}
}
setRenderedPositionMode(positionmode: string) {
if (positionmode !== this.rendered_positionmode) {
this.element.style.position = positionmode;
this.rendered_positionmode = positionmode;
}
}
//clearCss()
//{
// if (this.element.style.cssText)
// this.element.style.cssText = ""
//}
min1pixel(x: number) {
return ((x > 0 && x < 1) ? "1" : x.toString()) + "px";
}
setRenderedBorder(clr: string, width: number[]) {
var color = clr || "black";
if (color !== this.rendered_border) {
this.element.style.borderColor = color;
this.rendered_border = color;
}
if (!this.rendered_borderwidth
|| width[0] !== this.rendered_borderwidth[0]
|| width[1] !== this.rendered_borderwidth[1]
|| width[2] !== this.rendered_borderwidth[2]
|| width[3] !== this.rendered_borderwidth[3]) {
var visible = (width[0] || width[1] || width[2] || width[3]);
this.element.style.borderStyle = visible ? "solid" : "none";
this.element.style.borderTopWidth = visible ? this.min1pixel(width[WallBox.T]) : "";
this.element.style.borderRightWidth = visible ? this.min1pixel(width[WallBox.R]) : "";
this.element.style.borderBottomWidth = visible ? this.min1pixel(width[WallBox.B]) : "";
this.element.style.borderLeftWidth = visible ? this.min1pixel(width[WallBox.L]) : "";
this.rendered_borderwidth = width.slice(0);
}
}
setRenderedTextAlign(alignment: number) {
if (alignment !== this.rendered_textalign) {
switch (alignment) {
case WallBox.ARRANGE_RIGHT:
this.element.style.textAlign = "right";
break;
case WallBox.ARRANGE_CENTER:
this.element.style.textAlign = "center";
break;
case WallBox.ARRANGE_JUSTIFY:
this.element.style.textAlign = "justify";
break;
default:
this.element.style.textAlign = "left";
break;
}
this.cached_height = -1;
this.cached_width = -1;
this.rendered_textalign = alignment;
}
}
setRenderedHorizontalOverflow(mode: string) {
if (mode != this.rendered_hmode) {
this.element.style.overflowX = (this.rendered_sideview || (mode == "scroll" && (this.contentType == WallBox.CONTENT_INPUT))) ? "" : mode;
this.rendered_hmode = mode;
}
}
setRenderedVerticalOverflow(mode: string) {
if (mode != this.rendered_vmode) {
this.element.style.overflowY = (this.rendered_sideview || (mode == "scroll" && (this.contentType == WallBox.CONTENT_INPUT))) ? "" : mode;
this.rendered_vmode = mode;
}
}
setRenderedSideView(sideview: boolean) {
// called on root box to adjust side view
if (this.rendered_sideview != sideview) {
this.element.style.overflowX = (sideview || (this.rendered_hmode == "scroll" && (this.contentType == WallBox.CONTENT_INPUT))) ? "" : this.rendered_hmode;
this.element.style.overflowY = (sideview || (this.rendered_vmode == "scroll" && (this.contentType == WallBox.CONTENT_INPUT))) ? "" : this.rendered_vmode;
this.rendered_sideview = sideview;
}
}
setRenderedWrap(wrap: boolean, wraplimit: number) {
wrap = wrap || false;
if (wrap != this.rendered_wrap || wraplimit != this.rendered_wraplimit) {
this.element.style.whiteSpace = wrap ? (this.element.style.textAlign === "justify" ? "pre-line" : "pre-wrap") : "pre";
this.element.style.wordWrap = wrap ? "break-word" : "";
this.rendered_wrap = wrap;
this.rendered_wraplimit = wraplimit;
this.cached_height = -1;
this.cached_width = -1;
}
}
setRenderedZIndex(zi: number) {
if (zi != this.rendered_zindex) {
this.element.style.zIndex = zi ? zi.toString() : "";
this.rendered_zindex = zi;
}
}
//setRenderedTopMargin(margin: number) { this.rendered_margin[WallBox.T] = Math.max(0, margin); }
//setRenderedRightMargin(margin: number) { this.rendered_margin[WallBox.R] = Math.max(0, margin); }
//setRenderedBottomMargin(margin: number) { this.rendered_margin[WallBox.B] = Math.max(0, margin); }
//setRenderedLeftMargin(margin: number) { this.rendered_margin[WallBox.L] = Math.max(0, margin); }
}
} | the_stack |
'use strict';
import { join } from 'path';
import { exec } from 'child_process';
import encoding = require('vs/base/node/encoding');
import * as fs from 'fs';
import pfs = require('vs/base/node/pfs');
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IRosService, TaskName } from 'vs/platform/ros/common/ros';
import { templates as taskTemplates } from 'vs/workbench/parts/tasks/common/taskTemplates';
export const rosLaunchJson: string = [
'{',
'\t"version": "0.2.0",',
'\t"configurations": [',
'\t\t{',
'\t\t\t"name": "C++",',
'\t\t\t"type": "gdb",',
'\t\t\t"request": "launch",',
'\t\t\t"target": "${file}",',
'\t\t\t"cwd": "${workspaceRoot}"',
'\t\t},',
'\t\t{',
'\t\t\t"name": "C++ (remote)",',
'\t\t\t"type": "gdb",',
'\t\t\t"request": "launch",',
'\t\t\t"target": "dev${relativeFile}",',
'\t\t\t"cwd": "${workspaceRoot}",',
'\t\t\t"ssh": {',
'\t\t\t\t"host": "remotehost",',
'\t\t\t\t"user": "remoteuser",',
'\t\t\t\t"keyfile": "/home/user/.ssh/id_rsa",',
'\t\t\t\t"cwd": "/home/remote/ws"',
'\t\t\t}',
'\t\t},',
'\t\t{',
'\t\t\t"name": "Python",',
'\t\t\t"type": "python",',
'\t\t\t"request": "launch",',
'\t\t\t"stopOnEntry": true,',
'\t\t\t"pythonPath": "${config:python.pythonPath}",',
'\t\t\t"program": "${file}",',
'\t\t\t"debugOptions": [',
'\t\t\t\t"WaitOnAbnormalExit",',
'\t\t\t\t"WaitOnNormalExit",',
'\t\t\t\t"RedirectOutput"',
'\t\t\t]',
'\t\t}',
'\t]',
'}'
].join('\n');
export const rosTemplateCppPubNode: string = [
'#include "ros/ros.h"',
'#include "std_msgs/String.h"',
'',
'#include <sstream>',
'',
'/**',
' * This tutorial demonstrates simple sending of messages over the ROS system.',
' */',
'int main(int argc, char *argv[])',
'{',
'\t/**',
'\t * The ros::init() function needs to see argc and argv so that it can perform',
'\t * any ROS arguments and name remapping that were provided at the command line.',
'\t * For programmatic remappings you can use a different version of init() which takes',
'\t * remappings directly, but for most command-line programs, passing argc and argv is',
'\t * the easiest way to do it. The third argument to init() is the name of the node.',
'\t *',
'\t * You must call one of the versions of ros::init() before using any other',
'\t * part of the ROS system.',
'\t */',
'\tros::init(argc, argv, "${node_name}");',
'',
'\t/**',
'\t * NodeHandle is the main access point to communications with the ROS system.',
'\t * The first NodeHandle constructed will fully initialize this node, and the last',
'\t * NodeHandle destructed will close down the node.',
'\t */',
'\tros::NodeHandle n;',
'',
'\t/**',
'\t * The advertise() function is how you tell ROS that you want to',
'\t * publish on a given topic name. This invokes a call to the ROS',
'\t * master node, which keeps a registry of who is publishing and who',
'\t * is subscribing. After this advertise() call is made, the master',
'\t * node will notify anyone who is trying to subscribe to this topic name,',
'\t * and they will in turn negotiate a peer-to-peer connection with this',
'\t * node. advertise() returns a Publisher object which allows you to',
'\t * publish messages on that topic through a call to publish(). Once',
'\t * all copies of the returned Publisher object are destroyed, the topic',
'\t * will be automatically unadvertised.',
'\t *',
'\t * The second parameter to advertise() is the size of the message queue',
'\t * used for publishing messages. If messages are published more quickly',
'\t * than we can send them, the number here specifies how many messages to',
'\t * buffer up before throwing some away.',
'\t */',
'\tros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);',
'',
'\tros::Rate loop_rate(10);',
'',
'\t/**',
'\t * A count of how many messages we have sent. This is used to create',
'\t * a unique string for each message.',
'\t */',
'\tint count = 0;',
'\twhile (ros::ok())',
'\t{',
'\t\t/**',
'\t\t * This is a message object. You stuff it with data, and then publish it.',
'\t\t */',
'\t\tstd_msgs::String msg;',
'',
'\t\tstd::stringstream ss;',
'\t\tss << "hello world " << count;',
'\t\tmsg.data = ss.str();',
'',
'\t\tROS_INFO("%s", msg.data.c_str());',
'',
'\t\t/**',
'\t\t * The publish() function is how you send messages. The parameter',
'\t\t * is the message object. The type of this object must agree with the type',
'\t\t * given as a template parameter to the advertise<>() call, as was done',
'\t\t * in the constructor above.',
'\t\t */',
'\t\tchatter_pub.publish(msg);',
'',
'\t\tros::spinOnce();',
'',
'\t\tloop_rate.sleep();',
'\t\t++count;',
'\t}',
'',
'\treturn 0;',
'}'
].join('\n');
export const rosTemplateCppSubNode: string = [
'#include "ros/ros.h"',
'#include "std_msgs/String.h"',
'',
'/**',
' * This tutorial demonstrates simple receipt of messages over the ROS system.',
' */',
'void chatterCallback(const std_msgs::String::ConstPtr& msg)',
'{',
'\tROS_INFO("I heard: [%s]", msg->data.c_str());',
'}',
'',
'int main(int argc, char *argv[])',
'{',
'\t/**',
'\t * The ros::init() function needs to see argc and argv so that it can perform',
'\t * any ROS arguments and name remapping that were provided at the command line.',
'\t * For programmatic remappings you can use a different version of init() which takes',
'\t * remappings directly, but for most command-line programs, passing argc and argv is',
'\t * the easiest way to do it. The third argument to init() is the name of the node.',
'\t *',
'\t * You must call one of the versions of ros::init() before using any other',
'\t * part of the ROS system.',
'\t */',
'\tros::init(argc, argv, "${node_name}");',
'',
'\t/**',
'\t * NodeHandle is the main access point to communications with the ROS system.',
'\t * The first NodeHandle constructed will fully initialize this node, and the last',
'\t * NodeHandle destructed will close down the node.',
'\t */',
'\tros::NodeHandle n;',
'',
'\t/**',
'\t * The subscribe() call is how you tell ROS that you want to receive messages',
'\t * on a given topic. This invokes a call to the ROS',
'\t * master node, which keeps a registry of who is publishing and who',
'\t * is subscribing. Messages are passed to a callback function, here',
'\t * called chatterCallback. subscribe() returns a Subscriber object that you',
'\t * must hold on to until you want to unsubscribe. When all copies of the Subscriber',
'\t * object go out of scope, this callback will automatically be unsubscribed from',
'\t * this topic.',
'\t *',
'\t * The second parameter to the subscribe() function is the size of the message',
'\t * queue. If messages are arriving faster than they are being processed, this',
'\t * is the number of messages that will be buffered up before beginning to throw',
'\t * away the oldest ones.',
'\t */',
'\tros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);',
'',
'\t/**',
'\t * ros::spin() will enter a loop, pumping callbacks. With this version, all',
'\t * callbacks will be called from within this thread (the main one). ros::spin()',
'\t * will exit when Ctrl-C is pressed, or the node is shutdown by the master.',
'\t */',
'\tros::spin();',
'',
'\treturn 0;',
'}'
].join('\n');
export const rosTemplatePythonPubNode: string = [
'#!/usr/bin/env python',
'\'\'\'${node_name} ROS Node\'\'\'',
'# license removed for brevity',
'import rospy',
'from std_msgs.msg import String',
'',
'def talker():',
' \'\'\'${node_name} Publisher\'\'\'',
' pub = rospy.Publisher(\'chatter\', String, queue_size=10)',
' rospy.init_node(\'${node_name}\', anonymous=True)',
' rate = rospy.Rate(10) # 10hz',
' while not rospy.is_shutdown():',
' hello_str = "hello world %s" % rospy.get_time()',
' rospy.loginfo(hello_str)',
' pub.publish(hello_str)',
' rate.sleep()',
'',
'if __name__ == \'__main__\':',
' try:',
' talker()',
' except rospy.ROSInterruptException:',
' pass',
''
].join('\n');
export const rosTemplatePythonSubNode: string = [
'#!/usr/bin/env python',
'\'\'\'${node_name} ROS Node\'\'\'',
'import rospy',
'from std_msgs.msg import String',
'',
'def callback(data):',
' \'\'\'${node_name} Callback Function\'\'\'',
' rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)',
'',
'def listener():',
' \'\'\'${node_name} Subscriber\'\'\'',
' # In ROS, nodes are uniquely named. If two nodes with the same',
' # node are launched, the previous one is kicked off. The',
' # anonymous=True flag means that rospy will choose a unique',
' # name for our \'listener\' node so that multiple listeners can',
' # run simultaneously.',
' rospy.init_node(\'${node_name}\', anonymous=True)',
'',
' rospy.Subscriber("chatter", String, callback)',
'',
' # spin() simply keeps python from exiting until this node is stopped',
' rospy.spin()',
'',
'if __name__ == \'__main__\':',
' listener()',
''
].join('\n');
export const rosTemplateCppClassDefine: string = [
'class ${class_name}',
'{',
'public:',
'\t${class_name}();',
'\tvirtual ~${class_name}();',
'};'
].join('\n');
export const rosTemplateCppClassImplement: string = [
'#include "${class_name}.h"',
'',
'${class_name}::${class_name}()',
'{',
'}',
'',
'${class_name}::~${class_name}()',
'{',
'}'
].join('\n');
export const rosTemplateYcmConf: string = [
'#!/usr/bin/env python',
'',
'import os',
'import ycm_core',
'',
'flags = [',
'\'-Wall\',',
'\'-Wextra\',',
'\'-Werror\',',
'\'-fexceptions\',',
'\'-DNDEBUG\',',
'\'-std=c++11\',',
'\'-x\',',
'\'c++\',',
'\'-isystem\',',
'\'/usr/include\',',
'\'-isystem\',',
'\'/usr/local/include\',',
'\'-isystem\',',
'\'/opt/ros/\' + os.getenv(\'ROS_DISTRO\') + \'/include\',',
'${ws_incs}',
']',
'',
'compilation_database_folder = \'\'',
'',
'if os.path.exists( compilation_database_folder ):',
' database = ycm_core.CompilationDatabase( compilation_database_folder )',
'else:',
' database = None',
'',
'SOURCE_EXTENSIONS = [ \'.cpp\', \'.cxx\', \'.cc\', \'.c\' ]',
'',
'def DirectoryOfThisScript():',
' return os.path.dirname( os.path.abspath( __file__ ) )',
'',
'',
'def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):',
' if not working_directory:',
' return list( flags )',
' new_flags = []',
' make_next_absolute = False',
' path_flags = [ \'-isystem\', \'-I\', \'-iquote\', \'--sysroot=\' ]',
' for flag in flags:',
' new_flag = flag',
'',
' if make_next_absolute:',
' make_next_absolute = False',
' if not flag.startswith( \'/\' ):',
' new_flag = os.path.join( working_directory, flag )',
'',
' for path_flag in path_flags:',
' if flag == path_flag:',
' make_next_absolute = True',
' break',
'',
' if flag.startswith( path_flag ):',
' path = flag[ len( path_flag ): ]',
' new_flag = path_flag + os.path.join( working_directory, path )',
' break',
'',
' if new_flag:',
' new_flags.append( new_flag )',
' return new_flags',
'',
'',
'def IsHeaderFile( filename ):',
' extension = os.path.splitext( filename )[ 1 ]',
' return extension in [ \'.h\', \'.hxx\', \'.hpp\', \'.hh\' ]',
'',
'',
'def GetCompilationInfoForFile( filename ):',
' if IsHeaderFile( filename ):',
' basename = os.path.splitext( filename )[ 0 ]',
' for extension in SOURCE_EXTENSIONS:',
' replacement_file = basename + extension',
' if os.path.exists( replacement_file ):',
' compilation_info = database.GetCompilationInfoForFile(',
' replacement_file )',
' if compilation_info.compiler_flags_:',
' return compilation_info',
' return None',
' return database.GetCompilationInfoForFile( filename )',
'',
'',
'def FlagsForFile( filename, **kwargs ):',
' if database:',
' compilation_info = GetCompilationInfoForFile( filename )',
' if not compilation_info:',
' return None',
'',
' final_flags = MakeRelativePathsInFlagsAbsolute(',
' compilation_info.compiler_flags_,',
' compilation_info.compiler_working_dir_ )',
' else:',
' relative_to = DirectoryOfThisScript()',
' final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )',
'',
' return {',
' \'flags\': final_flags,',
' \'do_cache\': True',
' }',
''
].join('\n');
export class RosService implements IRosService {
public _serviceBrand: any;
public static ARGS_CACHE_SIZE = 32;
constructor(
@IWorkspaceContextService private contextService: IWorkspaceContextService
) {
}
// init ROS workspace
public initRosWs(path: string): TPromise<void> {
const srcPath = join(path, 'src'); // create src folder
return pfs.mkdirp(srcPath).then(() => {
return new TPromise<void>((c, e) => {
const execProc = exec('catkin_init_workspace', { cwd: srcPath }, (err, stdout, stderr) => { // catkin_init_workspace
if (err) {
return e(err);
}
});
execProc.on('exit', c);
execProc.on('error', e);
});
}).then(() => {
const libPath = join(path, 'devel', 'lib'); // create devel/lib folder
pfs.mkdirp(libPath);
}).then(() => {
const isolatedPath = join(path, 'devel_isolated'); // create devel_isolated folder
pfs.mkdirp(isolatedPath);
}).then(() => {
const libPath = join(path, 'el', 'lib'); // create el/lib folder
pfs.mkdirp(libPath);
}).then(() => {
const isolatedPath = join(path, 'el_isolated'); // create el_isolated folder
pfs.mkdirp(isolatedPath);
}).then(() => {
this.initConfiguration(path);
}).then(() => {
this.initRosWsYcmConf();
});
}
// init the configuration of ROS workspace
public initConfiguration(path: string): TPromise<void> {
return pfs.mkdirp(join(path, '.vscode')).then(() => {
pfs.writeFile(join(path, '.vscode', 'tasks.json'), taskTemplates[0].content, encoding.UTF8);
pfs.writeFile(join(path, '.vscode', 'launch.json'), rosLaunchJson, encoding.UTF8);
});
}
// init the YCM configuration of ROS workspace
public initRosWsYcmConf(): TPromise<void> {
const workspace = this.contextService.getWorkspace();
if (!workspace) {
return null;
}
const wsdevinc = `'-isystem',\n'${join(workspace.resource.fsPath, 'devel', 'include')}',\n`;
const srcDir = join(workspace.resource.fsPath, 'src');
return pfs.readDirsInDir(srcDir).then(children => {
const wspkginc = children.map(val => `'-isystem',\n'${join(srcDir, val, 'include')}'`).join(',\n');
pfs.writeFile(join(workspace.resource.fsPath, '.ycm_extra_conf.py'), rosTemplateYcmConf.replace('${ws_incs}', wsdevinc + wspkginc), encoding.UTF8);
});
}
// create ROS package
public addRosPkg(pkgName: string): TPromise<void> {
const workspace = this.contextService.getWorkspace();
if (!workspace || !pkgName) {
return null;
}
return new TPromise<void>((c, e) => {
const execProc = exec(`catkin_create_pkg ${pkgName}`, { cwd: join(workspace.resource.fsPath, 'src') }, (err, stdout, stderr) => {
if (err) {
return e(err);
}
});
execProc.on('exit', c);
execProc.on('error', e);
});
}
// get the debug argument
public getDebugArgs(name: string): TPromise<string> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
for (let i = 0; i < jsonObject.configurations.length; i++) {
if (jsonObject.configurations[i].name && jsonObject.configurations[i].name === name) {
return jsonObject.configurations[i].arguments;
}
}
} catch (error) { }
return null;
});
}
// set the debug argument
public setDebugArgs(name: string, args: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch.json');
return pfs.readFile(jsonPath).then(buffer => {
let jsonString = buffer.toString();
try {
const jsonObject = JSON.parse(jsonString);
for (let i = 0; i < jsonObject.configurations.length; i++) {
if (jsonObject.configurations[i].name && jsonObject.configurations[i].name === name) {
jsonObject.configurations[i].arguments = args;
}
}
jsonString = JSON.stringify(jsonObject, null, '\t');
} catch (error) { }
pfs.writeFile(jsonPath, jsonString);
});
}
// get the argument from cache
public getArgsCache(): TPromise<string[]> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.args) {
return jsonObject.args;
}
} catch (error) { }
return null;
}, () => null);
}
// add argument to cache
public addArgsToCache(args: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.args.indexOf(args) < 0) {
jsonObject.args.unshift(args); // new args at the beginning of cache
jsonObject.args.splice(RosService.ARGS_CACHE_SIZE, jsonObject.args.length - RosService.ARGS_CACHE_SIZE); // delete old args
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
}, () => {
const jsonString = JSON.stringify({ args: [args] }, null, '\t');
pfs.writeFile(jsonPath, jsonString);
});
}
// get the active package name from cache, It's synchronous
public getActivePkgNameCacheSync(): string[] {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
try {
const buffer = fs.readFileSync(jsonPath);
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.activePkgName && jsonObject.activePkgName.length > 0) {
return jsonObject.activePkgName;
}
} catch (error) {
return null;
}
return null;
}
// get the active package name from cache
public getActivePkgNameCache(): TPromise<string[]> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.activePkgName && jsonObject.activePkgName.length > 0) {
return jsonObject.activePkgName;
}
} catch (error) { }
return null;
}, () => null);
}
// add the active package name to cache
public addActivePkgNameToCache(pkgName: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (!jsonObject.activePkgName) {
jsonObject.activePkgName = [];
}
if (jsonObject.activePkgName.indexOf(pkgName) < 0) {
jsonObject.activePkgName.push(pkgName);
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
}, () => {
const jsonString = JSON.stringify({ activePkgName: [pkgName] }, null, '\t');
pfs.writeFile(jsonPath, jsonString);
});
}
// delete the active package name from cache
public delActivePkgNameFromCache(pkgName: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (!jsonObject.activePkgName) {
return;
}
const idx = jsonObject.activePkgName.indexOf(pkgName);
if (idx >= 0) {
jsonObject.activePkgName.splice(idx, 1);
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
});
}
// clean all active package name from cache
public cleanActivePkgNameFromCache(): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.activePkgName) {
delete jsonObject.activePkgName;
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
});
}
// get the remote argument from cache
public getRemoteArgsCache(): TPromise<any> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
if (jsonObject.remoteArgs) {
return jsonObject.remoteArgs;
}
} catch (error) { }
return null;
}, () => null);
}
// set the remote argument to cache
public setRemoteArgsToCache(host: string, user: string, keyfile: string, cwd: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch_args.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
let isChanged: boolean = false;
if (!jsonObject.remoteArgs) {
jsonObject.remoteArgs = {};
}
if (!jsonObject.remoteArgs.host || jsonObject.remoteArgs.host !== host) {
jsonObject.remoteArgs.host = host;
isChanged = true;
}
if (!jsonObject.remoteArgs.user || jsonObject.remoteArgs.user !== user) {
jsonObject.remoteArgs.user = user;
isChanged = true;
}
if (!jsonObject.remoteArgs.keyfile || jsonObject.remoteArgs.keyfile !== keyfile) {
jsonObject.remoteArgs.keyfile = keyfile;
isChanged = true;
}
if (!jsonObject.remoteArgs.cwd || jsonObject.remoteArgs.cwd !== cwd) {
jsonObject.remoteArgs.cwd = cwd;
isChanged = true;
}
if (isChanged) {
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
}, () => {
const jsonString = JSON.stringify({ remoteArgs: { host: host, user: user, keyfile: keyfile, cwd: cwd } }, null, '\t');
pfs.writeFile(jsonPath, jsonString);
});
}
// get Build Task Name list
public getBuildTaskNames(isCatkinBuild: boolean): TPromise<TaskName[]> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'tasks.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonTasks = JSON.parse(buffer.toString()).tasks;
let names: TaskName[] = [];
for (let i = 0; i < jsonTasks.length; i++) {
if ((jsonTasks[i].taskName.indexOf('Deploy') > 0 || jsonTasks[i].taskName.indexOf('catkin') > 0 === isCatkinBuild) &&
(!jsonTasks[i].isTestCommand || jsonTasks[i].isBuildCommand)) {
names.push({ name: jsonTasks[i].taskName, isBuildCommand: jsonTasks[i].isBuildCommand });
}
}
return names;
} catch (error) { }
return null;
});
}
// set the default Build Task
public setBuildTask(taskName: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'tasks.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
const jsonTasks = jsonObject.tasks;
let isChanged: boolean = false;
for (let i = 0; i < jsonTasks.length; i++) {
if (jsonTasks[i].taskName === taskName) {
if (!jsonTasks[i].isBuildCommand) {
jsonTasks[i].isBuildCommand = true;
isChanged = true;
}
} else if (jsonTasks[i].isBuildCommand) {
delete jsonTasks[i].isBuildCommand;
isChanged = true;
}
}
if (isChanged) {
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
});
}
// set tasks arguments
private setTasksArgs(activePkgName: string[], host: string, user: string, cwd: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'tasks.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
const jsonTasks = jsonObject.tasks;
let isChanged: boolean = false;
for (let i = 0; i < jsonTasks.length; i++) {
let args;
switch (jsonTasks[i].taskName) {
case 'Debug':
args = `catkin_make${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C \${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug`;
break;
case 'Release':
args = `catkin_make${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C \${workspaceRoot}`;
break;
case 'Debug (isolated)':
args = `catkin_make_isolated${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C \${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug`;
break;
case 'Release (isolated)':
args = `catkin_make_isolated${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C \${workspaceRoot}`;
break;
case 'Debug (remote)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin_make${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C ${cwd} -DCMAKE_BUILD_TYPE=Debug\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avz --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel/lib/${val}`).join(' ') : `${user}@${host}:${cwd}/devel/lib/\\*`} \${workspaceRoot}/el/lib`;
break;
case 'Release (remote)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin_make${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C ${cwd}\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avz --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel/lib/${val}`).join(' ') : `${user}@${host}:${cwd}/devel/lib/\\*`} \${workspaceRoot}/el/lib`;
break;
case 'Debug (remote isolated)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin_make_isolated${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C ${cwd} -DCMAKE_BUILD_TYPE=Debug\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avz --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel_isolated/${val}`).join(' ') : `${user}@${host}:${cwd}/devel_isolated/\\*`} \${workspaceRoot}/el_isolated`;
break;
case 'Release (remote isolated)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin_make_isolated${activePkgName ? ' --pkg ' + activePkgName.join(' ') : ''} -C ${cwd}\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avz --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel_isolated/${val}`).join(' ') : `${user}@${host}:${cwd}/devel_isolated/\\*`} \${workspaceRoot}/el_isolated`;
break;
case 'Debug (catkin)':
args = `catkin build${activePkgName ? ' ' + activePkgName.join(' ') : ''} -w \${workspaceRoot} -DCMAKE_BUILD_TYPE=Debug`;
break;
case 'Release (catkin)':
args = `catkin build${activePkgName ? ' ' + activePkgName.join(' ') : ''} -w \${workspaceRoot}`;
break;
case 'Debug (remote catkin)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin build${activePkgName ? ' ' + activePkgName.join(' ') : ''} -w ${cwd} -DCMAKE_BUILD_TYPE=Debug\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avzL --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel/lib/${val}`).join(' ') : `${user}@${host}:${cwd}/devel/lib/\\*`} \${workspaceRoot}/el/lib`;
break;
case 'Release (remote catkin)':
if (!host || !user || !cwd) {
continue;
}
args = `ssh ${user}@${host} 'echo -e \"#!/bin/bash --login\\ncatkin build${activePkgName ? ' ' + activePkgName.join(' ') : ''} -w ${cwd}\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; rsync -avzL --delete --exclude=\"*.swp\" ${activePkgName ? activePkgName.map(val => `${user}@${host}:${cwd}/devel/lib/${val}`).join(' ') : `${user}@${host}:${cwd}/devel/lib/\\*`} \${workspaceRoot}/el/lib`;
break;
case 'Remote Deploy':
if (!host || !user || !cwd) {
continue;
}
args = activePkgName ? `rsync -avz --delete --exclude=\"*.swp\" ${activePkgName.map(val => `\${workspaceRoot}/src/${val}`).join(' ')} ${user}@${host}:${cwd}/src; echo \"Deploy Finished!\"` : `rsync -avz --delete --exclude=\"*.swp\" \${workspaceRoot}/src ${user}@${host}:${cwd}; ssh ${user}@${host} 'rm ${cwd}/src/CMakeLists.txt; echo -e \"#!/bin/bash --login\\ncatkin_init_workspace ${cwd}/src\" > /tmp/roswstmp.sh; chmod 755 /tmp/roswstmp.sh; /tmp/roswstmp.sh'; echo \"Deploy Finished!\"`;
break;
default:
continue;
}
if (!jsonTasks[i].args[0] || jsonTasks[i].args[0] !== args) {
jsonTasks[i].args[0] = args;
isChanged = true;
}
}
if (isChanged) {
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
});
}
// set the active package name
public setActivePkgNameArgs(activePkgName: string[]): TPromise<void> {
return this.getRemoteArgsCache().then(remoteArgs => {
if (remoteArgs) {
this.setTasksArgs(activePkgName, remoteArgs.host, remoteArgs.user, remoteArgs.cwd);
} else {
this.setTasksArgs(activePkgName, null, null, null);
}
});
}
// set remote tasks argument
public setRemoteTasksArgs(host: string, user: string, keyfile: string, cwd: string): TPromise<void> {
return this.getActivePkgNameCache().then(activePkgName => this.setTasksArgs(activePkgName, host, user, cwd));
}
// set remote launch argument
public setRemoteLaunchArgs(host: string, user: string, keyfile: string, cwd: string): TPromise<void> {
const jsonPath = join(this.contextService.getWorkspace().resource.fsPath, '.vscode', 'launch.json');
return pfs.readFile(jsonPath).then(buffer => {
try {
const jsonObject = JSON.parse(buffer.toString());
const jsonConfig = jsonObject.configurations;
let isChanged: boolean = false;
for (let i = 0; i < jsonConfig.length; i++) {
if (jsonConfig[i].type === 'gdb' && jsonConfig[i].ssh) {
if (!jsonConfig[i].ssh.host || jsonConfig[i].ssh.host !== host) {
jsonConfig[i].ssh.host = host;
isChanged = true;
}
if (!jsonConfig[i].ssh.user || jsonConfig[i].ssh.user !== user) {
jsonConfig[i].ssh.user = user;
isChanged = true;
}
if (!jsonConfig[i].ssh.keyfile || jsonConfig[i].ssh.keyfile !== keyfile) {
jsonConfig[i].ssh.keyfile = keyfile;
isChanged = true;
}
if (!jsonConfig[i].ssh.cwd || jsonConfig[i].ssh.cwd !== cwd) {
jsonConfig[i].ssh.cwd = cwd;
isChanged = true;
}
}
}
if (isChanged) {
const jsonString = JSON.stringify(jsonObject, null, '\t');
pfs.writeFile(jsonPath, jsonString);
}
} catch (error) { }
});
}
// run command and get the results
public getCmdResultList(command: string): TPromise<string[]> {
return new TPromise<string[]>((c, e) => {
exec(command, (err, stdout, stderr) => { // run command
if (err || stderr) {
return e(err);
}
return c(stdout.toString().trim().replace(/\n+/g, '\n').split('\n'));
});
});
}
// create C++ ROS node
public addCppNode(path: string, name: string): TPromise<any> {
const pubFilePath = join(path, 'src', `${name}_pub.cpp`);
return pfs.exists(pubFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
const subFilePath = join(path, 'src', `${name}_sub.cpp`);
return pfs.exists(subFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
return pfs.mkdirp(join(path, 'src')).then(() =>
pfs.writeFile(pubFilePath, rosTemplateCppPubNode.replace(/\${node_name}/g, name))
).then(() =>
pfs.writeFile(subFilePath, rosTemplateCppSubNode.replace(/\${node_name}/g, name))
);
});
});
}
// create Python ROS node
public addPythonNode(path: string, name: string): TPromise<any> {
const pubFilePath = join(path, 'src', `${name}_pub.py`);
return pfs.exists(pubFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
const subFilePath = join(path, 'src', `${name}_sub.py`);
return pfs.exists(subFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
return pfs.mkdirp(join(path, 'src')).then(() =>
pfs.writeFile(pubFilePath, rosTemplatePythonPubNode.replace(/\${node_name}/g, name))
).then(() =>
pfs.writeFile(subFilePath, rosTemplatePythonSubNode.replace(/\${node_name}/g, name))
);
});
});
}
// create C++ class
public addCppClass(path: string, pkgName: string, name: string): TPromise<any> {
const headerFilePath = join(path, 'include', pkgName, `${name}.h`);
return pfs.exists(headerFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
const cppFilePath = join(path, 'src', `${name}.cpp`);
return pfs.exists(cppFilePath).then((exists) => {
if (exists) {
return TPromise.wrapError(new Error(nls.localize('fileExists', "File name already exists!")));
}
return pfs.mkdirp(join(path, 'include', pkgName)).then(() =>
pfs.mkdirp(join(path, 'src'))
).then(() =>
pfs.writeFile(headerFilePath, rosTemplateCppClassDefine.replace(/\${class_name}/g, name))
).then(() =>
pfs.writeFile(cppFilePath, rosTemplateCppClassImplement.replace(/\${class_name}/g, name))
);
});
});
}
} | the_stack |
import { Directionality } from '@angular/cdk/bidi';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ESCAPE, hasModifierKey, UP_ARROW } from '@angular/cdk/keycodes';
import {
ScrollStrategy,
OverlayConfig,
Overlay,
OverlayRef,
FlexibleConnectedPositionStrategy,
} from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { DOCUMENT } from '@angular/common';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnChanges,
OnDestroy,
Optional,
Output,
TemplateRef,
ViewContainerRef,
ViewEncapsulation,
} from '@angular/core';
import { CanColor, mixinColor, ThemePalette } from '@angular/material/core';
import { Subject, Subscription, merge } from 'rxjs';
import { filter, take } from 'rxjs/operators';
import { mtxColorpickerAnimations } from './colorpicker-animations';
import { ColorFormat, MtxColorpickerInput } from './colorpicker-input';
import { ColorEvent } from 'ngx-color';
import { TinyColor } from '@ctrl/tinycolor';
/** Used to generate a unique ID for each colorpicker instance. */
let colorpickerUid = 0;
/** Injection token that determines the scroll handling while the panel is open. */
export const MTX_COLORPICKER_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mtx-colorpicker-scroll-strategy'
);
export function MTX_COLORPICKER_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** Possible positions for the colorpicker dropdown along the X axis. */
export type ColorpickerDropdownPositionX = 'start' | 'end';
/** Possible positions for the colorpicker dropdown along the Y axis. */
export type ColorpickerDropdownPositionY = 'above' | 'below';
export const MTX_COLORPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MTX_COLORPICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MTX_COLORPICKER_SCROLL_STRATEGY_FACTORY,
};
// Boilerplate for applying mixins to MtxColorpickerContent.
/** @docs-private */
const _MtxColorpickerContentBase = mixinColor(
class {
constructor(public _elementRef: ElementRef) {}
}
);
@Component({
selector: 'mtx-colorpicker-content',
templateUrl: './colorpicker-content.html',
styleUrls: ['colorpicker-content.scss'],
host: {
'class': 'mtx-colorpicker-content',
'[@transformPanel]': '_animationState',
'(@transformPanel.done)': '_animationDone.next()',
},
animations: [mtxColorpickerAnimations.transformPanel],
exportAs: 'mtxColorpickerContent',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
inputs: ['color'],
})
export class MtxColorpickerContent
extends _MtxColorpickerContentBase
implements OnDestroy, CanColor
{
picker!: MtxColorpicker;
/** Current state of the animation. */
_animationState: 'enter-dropdown' | 'void' = 'enter-dropdown';
/** Emits when an animation has finished. */
readonly _animationDone = new Subject<void>();
constructor(elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef) {
super(elementRef);
}
_startExitAnimation() {
this._animationState = 'void';
this._changeDetectorRef.markForCheck();
}
ngOnDestroy() {
this._animationDone.complete();
}
getColorString(e: ColorEvent): string {
return {
hex: e.color.rgb.a === 1 ? e.color.hex : new TinyColor(e.color.rgb).toHex8String(),
rgb: new TinyColor(e.color.rgb).toRgbString(),
hsl: new TinyColor(e.color.hsl).toHslString(),
hsv: new TinyColor(e.color.hsv).toHsvString(),
}[this.picker.format];
}
}
@Component({
selector: 'mtx-colorpicker',
template: '',
exportAs: 'mtxColorpicker',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MtxColorpicker implements OnChanges, OnDestroy {
private _scrollStrategy: () => ScrollStrategy;
private _inputStateChanges = Subscription.EMPTY;
/** Custom colorpicker content set by the consumer. */
@Input() content!: TemplateRef<any>;
/** Emits when the colorpicker has been opened. */
@Output('opened') openedStream: EventEmitter<void> = new EventEmitter<void>();
/** Emits when the colorpicker has been closed. */
@Output('closed') closedStream: EventEmitter<void> = new EventEmitter<void>();
@Input() get disabled() {
return this._disabled === undefined && this.pickerInput
? this.pickerInput.disabled
: !!this._disabled;
}
set disabled(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._disabled) {
this._disabled = newValue;
this._disabledChange.next(newValue);
}
}
private _disabled!: boolean;
/** Preferred position of the colorpicker in the X axis. */
@Input()
xPosition: ColorpickerDropdownPositionX = 'start';
/** Preferred position of the colorpicker in the Y axis. */
@Input()
yPosition: ColorpickerDropdownPositionY = 'below';
/**
* Whether to restore focus to the previously-focused element when the panel is closed.
* Note that automatic focus restoration is an accessibility feature and it is recommended that
* you provide your own equivalent, if you decide to turn it off.
*/
@Input()
get restoreFocus(): boolean {
return this._restoreFocus;
}
set restoreFocus(value: boolean) {
this._restoreFocus = coerceBooleanProperty(value);
}
private _restoreFocus = true;
/** Whether the panel is open. */
@Input()
get opened(): boolean {
return this._opened;
}
set opened(value: boolean) {
coerceBooleanProperty(value) ? this.open() : this.close();
}
private _opened = false;
/** The id for the colorpicker panel. */
id = `mtx-colorpicker-${colorpickerUid++}`;
/** Color palette to use on the colorpicker's panel. */
@Input()
get color(): ThemePalette {
return this._color || (this.pickerInput ? this.pickerInput.getThemePalette() : undefined);
}
set color(value: ThemePalette) {
this._color = value;
}
private _color: ThemePalette;
/** The input and output color format. */
@Input()
get format(): ColorFormat {
return this._format || this.pickerInput.format;
}
set format(value: ColorFormat) {
this._format = value;
}
_format!: ColorFormat;
/** The currently selected color. */
get selected(): string {
return this._validSelected;
}
set selected(value: string) {
this._validSelected = value;
}
private _validSelected: string = '';
/** A reference to the overlay when the picker is opened as a popup. */
private _overlayRef!: OverlayRef | null;
/** Reference to the component instance rendered in the overlay. */
private _componentRef!: ComponentRef<MtxColorpickerContent> | null;
/** The element that was focused before the colorpicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
/** Unique class that will be added to the backdrop so that the test harnesses can look it up. */
private _backdropHarnessClass = `${this.id}-backdrop`;
/** The input element this colorpicker is associated with. */
pickerInput!: MtxColorpickerInput;
/** Emits when the datepicker is disabled. */
readonly _disabledChange = new Subject<boolean>();
/** Emits new selected color when selected color changes. */
readonly _selectedChanged = new Subject<string>();
constructor(
private _overlay: Overlay,
private _ngZone: NgZone,
private _viewContainerRef: ViewContainerRef,
@Inject(MTX_COLORPICKER_SCROLL_STRATEGY) scrollStrategy: any,
@Optional() private _dir: Directionality,
@Optional() @Inject(DOCUMENT) private _document: any
) {
this._scrollStrategy = scrollStrategy;
}
ngOnChanges() {}
ngOnDestroy() {
this._destroyOverlay();
this.close();
this._inputStateChanges.unsubscribe();
this._disabledChange.complete();
}
/** Selects the given color */
select(nextVal: string): void {
const oldValue = this.selected;
this.selected = nextVal;
// TODO: `nextVal` should compare with `oldValue`
this._selectedChanged.next(nextVal);
}
/**
* Register an input with this colorpicker.
* @param input The colorpicker input to register with this colorpicker.
*/
registerInput(input: MtxColorpickerInput): void {
if (this.pickerInput) {
throw Error('A Colorpicker can only be associated with a single input.');
}
this.pickerInput = input;
this._inputStateChanges = input._valueChange.subscribe(
(value: string) => (this.selected = value)
);
}
open(): void {
if (this._opened || this.disabled) {
return;
}
if (!this.pickerInput) {
throw Error('Attempted to open an Colorpicker with no associated input.');
}
if (this._document) {
this._focusedElementBeforeOpen = this._document.activeElement;
}
this._openOverlay();
this._opened = true;
this.openedStream.emit();
}
/** Close the panel. */
close(): void {
if (!this._opened) {
return;
}
if (this._componentRef) {
const instance = this._componentRef.instance;
instance._startExitAnimation();
instance._animationDone.pipe(take(1)).subscribe(() => this._destroyOverlay());
}
const completeClose = () => {
// The `_opened` could've been reset already if
// we got two events in quick succession.
if (this._opened) {
this._opened = false;
this.closedStream.emit();
this._focusedElementBeforeOpen = null;
}
};
if (
this._restoreFocus &&
this._focusedElementBeforeOpen &&
typeof this._focusedElementBeforeOpen.focus === 'function'
) {
// Because IE moves focus asynchronously, we can't count on it being restored before we've
// marked the colorpicker as closed. If the event fires out of sequence and the element that
// we're refocusing opens the colorpicker on focus, the user could be stuck with not being
// able to close the panel at all. We work around it by making the logic, that marks
// the colorpicker as closed, async as well.
this._focusedElementBeforeOpen.focus();
setTimeout(completeClose);
} else {
completeClose();
}
}
/** Forwards relevant values from the colorpicker to the colorpicker content inside the overlay. */
protected _forwardContentValues(instance: MtxColorpickerContent) {
instance.picker = this;
instance.color = this.color;
}
/** Open the colopicker as a popup. */
private _openOverlay(): void {
this._destroyOverlay();
const labelId = this.pickerInput.getOverlayLabelId();
const portal = new ComponentPortal<MtxColorpickerContent>(
MtxColorpickerContent,
this._viewContainerRef
);
const overlayRef = (this._overlayRef = this._overlay.create(
new OverlayConfig({
positionStrategy: this._getDropdownStrategy(),
hasBackdrop: true,
backdropClass: ['mat-overlay-transparent-backdrop', this._backdropHarnessClass],
direction: this._dir,
scrollStrategy: this._scrollStrategy(),
panelClass: `mtx-colorpicker-popup`,
})
));
const overlayElement = overlayRef.overlayElement;
overlayElement.setAttribute('role', 'dialog');
if (labelId) {
overlayElement.setAttribute('aria-labelledby', labelId);
}
this._getCloseStream(overlayRef).subscribe(event => {
if (event) {
event.preventDefault();
}
this.close();
});
this._componentRef = overlayRef.attach(portal);
this._forwardContentValues(this._componentRef.instance);
// Update the position once the panel has rendered. Only relevant in dropdown mode.
this._ngZone.onStable.pipe(take(1)).subscribe(() => overlayRef.updatePosition());
}
private _destroyOverlay() {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = this._componentRef = null;
}
}
/** Gets a position strategy that will open the panel as a dropdown. */
private _getDropdownStrategy() {
const strategy = this._overlay
.position()
.flexibleConnectedTo(this.pickerInput.getConnectedOverlayOrigin())
.withTransformOriginOn('.mtx-colorpicker-content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition();
return this._setConnectedPositions(strategy);
}
/** Sets the positions of the colorpicker in dropdown mode based on the current configuration. */
private _setConnectedPositions(strategy: FlexibleConnectedPositionStrategy) {
const primaryX = this.xPosition === 'end' ? 'end' : 'start';
const secondaryX = primaryX === 'start' ? 'end' : 'start';
const primaryY = this.yPosition === 'above' ? 'bottom' : 'top';
const secondaryY = primaryY === 'top' ? 'bottom' : 'top';
return strategy.withPositions([
{
originX: primaryX,
originY: secondaryY,
overlayX: primaryX,
overlayY: primaryY,
},
{
originX: primaryX,
originY: primaryY,
overlayX: primaryX,
overlayY: secondaryY,
},
{
originX: secondaryX,
originY: secondaryY,
overlayX: secondaryX,
overlayY: primaryY,
},
{
originX: secondaryX,
originY: primaryY,
overlayX: secondaryX,
overlayY: secondaryY,
},
]);
}
/** Gets an observable that will emit when the overlay is supposed to be closed. */
private _getCloseStream(overlayRef: OverlayRef) {
return merge(
overlayRef.backdropClick(),
overlayRef.detachments(),
overlayRef.keydownEvents().pipe(
filter(event => {
// Closing on alt + up is only valid when there's an input associated with the colorpicker.
return (
(event.keyCode === ESCAPE && !hasModifierKey(event)) ||
(this.pickerInput && hasModifierKey(event, 'altKey') && event.keyCode === UP_ARROW)
);
})
)
);
}
static ngAcceptInputType_disabled: BooleanInput;
} | the_stack |
import { AwsEsdkKMSInterface } from './kms_types'
import {
needs,
Keyring,
EncryptionMaterial,
DecryptionMaterial,
SupportedAlgorithmSuites,
KeyringTrace,
KeyringTraceFlag,
EncryptedDataKey,
immutableClass,
readOnlyProperty,
unwrapDataKey,
Newable,
Catchable,
} from '@aws-crypto/material-management'
import {
KMS_PROVIDER_ID,
generateDataKey,
encrypt,
decrypt,
kmsResponseToEncryptedDataKey,
} from './helpers'
import {
mrkAwareAwsKmsKeyIdCompare,
parseAwsKmsKeyArn,
validAwsKmsIdentifier,
} from './arn_parsing'
export interface AwsKmsMrkAwareSymmetricKeyringInput<
Client extends AwsEsdkKMSInterface
> {
keyId: string
client: Client
grantTokens?: string[]
}
export interface IAwsKmsMrkAwareSymmetricKeyring<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
> extends Keyring<S> {
keyId: string
client: Client
grantTokens?: string[]
_onEncrypt(material: EncryptionMaterial<S>): Promise<EncryptionMaterial<S>>
_onDecrypt(
material: DecryptionMaterial<S>,
encryptedDataKeys: EncryptedDataKey[]
): Promise<DecryptionMaterial<S>>
}
export interface AwsKmsMrkAwareSymmetricKeyringConstructible<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
> {
new (
input: AwsKmsMrkAwareSymmetricKeyringInput<Client>
): IAwsKmsMrkAwareSymmetricKeyring<S, Client>
}
export function AwsKmsMrkAwareSymmetricKeyringClass<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
>(
BaseKeyring: Newable<Keyring<S>>
): AwsKmsMrkAwareSymmetricKeyringConstructible<S, Client> {
class AwsKmsMrkAwareSymmetricKeyring
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.5
//# MUST implement the AWS Encryption SDK Keyring interface (../keyring-
//# interface.md#interface)
extends BaseKeyring
implements IAwsKmsMrkAwareSymmetricKeyring<S, Client>
{
public keyId!: string
public client!: Client
public grantTokens?: string[]
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6
//# On initialization the caller MUST provide:
constructor({
client,
keyId,
grantTokens,
}: AwsKmsMrkAwareSymmetricKeyringInput<Client>) {
super()
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6
//# The AWS KMS key identifier MUST NOT be null or empty.
needs(
keyId && typeof keyId === 'string',
'An AWS KMS key identifier is required.'
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6
//# The AWS KMS
//# key identifier MUST be a valid identifier (aws-kms-key-arn.md#a-
//# valid-aws-kms-identifier).
needs(
validAwsKmsIdentifier(keyId),
`Key id ${keyId} is not a valid identifier.`
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.6
//# The AWS KMS
//# SDK client MUST NOT be null.
needs(!!client, 'An AWS SDK client is required')
readOnlyProperty(this, 'client', client)
readOnlyProperty(this, 'keyId', keyId)
readOnlyProperty(this, 'grantTokens', grantTokens)
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# OnEncrypt MUST take encryption materials (structures.md#encryption-
//# materials) as input.
async _onEncrypt(
material: EncryptionMaterial<S>
): Promise<EncryptionMaterial<S>> {
const { client, keyId, grantTokens } = this
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the input encryption materials (structures.md#encryption-
//# materials) do not contain a plaintext data key OnEncrypt MUST attempt
//# to generate a new plaintext data key by calling AWS KMS
//# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html).
if (!material.hasUnencryptedDataKey) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# The keyring MUST call
//# AWS KMS GenerateDataKeys with a request constructed as follows:
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the call to AWS KMS GenerateDataKey
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html) does not succeed, OnEncrypt MUST NOT modify
//# the encryption materials (structures.md#encryption-materials) and
//# MUST fail.
const dataKey = await generateDataKey(
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the keyring calls AWS KMS GenerateDataKeys, it MUST use the
//# configured AWS KMS client to make the call.
client,
material.suite.keyLengthBytes,
keyId,
material.encryptionContext,
grantTokens
)
/* This should be impossible given that generateDataKey only returns false if the client supplier does. */
needs(dataKey, 'Generator KMS key did not generate a data key')
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# The Generate Data Key response's "KeyId" MUST be A valid AWS
//# KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-
//# key).
needs(parseAwsKmsKeyArn(dataKey.KeyId), 'Malformed arn.')
const flags =
KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX |
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
const trace: KeyringTrace = {
keyNamespace: KMS_PROVIDER_ID,
keyName: dataKey.KeyId,
flags,
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If verified,
//# OnEncrypt MUST do the following with the response from AWS KMS
//# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html):
material
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the Generate Data Key call succeeds, OnEncrypt MUST verify that
//# the response "Plaintext" length matches the specification of the
//# algorithm suite (algorithm-suites.md)'s Key Derivation Input Length
//# field.
//
// setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements.
.setUnencryptedDataKey(dataKey.Plaintext, trace)
.addEncryptedDataKey(
kmsResponseToEncryptedDataKey(dataKey),
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# * OnEncrypt MUST output the modified encryption materials
//# (structures.md#encryption-materials)
return material
} else {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# Given a plaintext data key in the encryption materials
//# (structures.md#encryption-materials), OnEncrypt MUST attempt to
//# encrypt the plaintext data key using the configured AWS KMS key
//# identifier.
const unencryptedDataKey = unwrapDataKey(
material.getUnencryptedDataKey()
)
const flags =
KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the call to AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) does not succeed, OnEncrypt MUST fail.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# The keyring
//# MUST AWS KMS Encrypt call with a request constructed as follows:
const kmsEDK = await encrypt(
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# The keyring MUST call AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) using the configured AWS KMS client.
client,
unencryptedDataKey,
keyId,
material.encryptionContext,
grantTokens
)
/* This should be impossible given that encrypt only returns false if the client supplier does. */
needs(
kmsEDK,
'AwsKmsMrkAwareSymmetricKeyring failed to encrypt data key'
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If the Encrypt call succeeds The response's "KeyId" MUST be A valid
//# AWS KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-
//# region-key).
needs(parseAwsKmsKeyArn(kmsEDK.KeyId), 'Malformed arn.')
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If verified, OnEncrypt MUST do the following with the response from
//# AWS KMS Encrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html):
material.addEncryptedDataKey(
kmsResponseToEncryptedDataKey(kmsEDK),
flags
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//# If all Encrypt calls succeed, OnEncrypt MUST output the modified
//# encryption materials (structures.md#encryption-materials).
return material
}
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
async _onDecrypt(
material: DecryptionMaterial<S>,
encryptedDataKeys: EncryptedDataKey[]
): Promise<DecryptionMaterial<S>> {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
if (material.hasValidKey()) return material
const { client, keyId, grantTokens } = this
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration.
const decryptableEDKs = encryptedDataKeys.filter(filterEDKs(keyId))
const cmkErrors: Catchable[] = []
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key.
for (const edk of decryptableEDKs) {
const { providerId, encryptedDataKey } = edk
try {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
const dataKey = await decrypt(
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
client,
// For MRKs the key identifier MUST be the configured key identifer.
{ providerId, encryptedDataKey, providerInfo: this.keyId },
material.encryptionContext,
grantTokens
)
/* This should be impossible given that decrypt only returns false if the client supplier does
* or if the providerId is not "aws-kms", which we have already filtered out
*/
needs(dataKey, 'decrypt did not return a data key.')
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# * The "KeyId" field in the response MUST equal the configured AWS
//# KMS key identifier.
needs(
dataKey.KeyId === this.keyId,
'KMS Decryption key does not match the requested key id.'
)
const flags =
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
const trace: KeyringTrace = {
keyNamespace: KMS_PROVIDER_ID,
keyName: dataKey.KeyId,
flags,
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# If the response does satisfies these requirements then OnDecrypt MUST
//# do the following with the response:
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
//
// setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements.
material.setUnencryptedDataKey(dataKey.Plaintext, trace)
return material
} catch (e) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# If this attempt
//# results in an error, then these errors MUST be collected.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# If the response does not satisfies these requirements then an error
//# MUST be collected and the next encrypted data key in the filtered set
//# MUST be attempted.
cmkErrors.push({ errPlus: e })
}
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all the collected errors.
needs(
material.hasValidKey(),
[
`Unable to decrypt data key${
!decryptableEDKs.length ? ': No EDKs supplied' : ''
}.`,
...cmkErrors.map((e, i) => `Error #${i + 1} \n${e.errPlus.stack}`),
].join('\n')
)
return material
}
}
immutableClass(AwsKmsMrkAwareSymmetricKeyring)
return AwsKmsMrkAwareSymmetricKeyring
}
function filterEDKs(keyringKeyId: string) {
return function filter({ providerId, providerInfo }: EncryptedDataKey) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# * Its provider ID MUST exactly match the value "aws-kms".
if (providerId !== KMS_PROVIDER_ID) return false
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
const arnInfo = parseAwsKmsKeyArn(providerInfo)
needs(
arnInfo && arnInfo.ResourceType === 'key',
'Unexpected EDK ProviderInfo for AWS KMS EDK'
)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.8
//# * The the function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-
//# for-decrypt.md#implementation) called with the configured AWS KMS
//# key identifier and the provider info MUST return "true".
return mrkAwareAwsKmsKeyIdCompare(keyringKeyId, providerInfo)
}
} | the_stack |
import { html } from ".";
import { deepDiff, diffArrays } from "./diff";
import { Parts } from "./htmlSafeString";
describe("test diffs", () => {
it("diff is empty if no difference between parts", () => {
const previousState = html`something ${"foo"} blah`;
const nextState = html`something ${"foo"} blah`;
const diff = deepDiff(previousState.partsTree(), nextState.partsTree());
expect(diff).toStrictEqual({});
});
it("dynamics array ('d' key) is different so entire 'd' array is diff", () => {
type FooItem = { name: string; which: "foo" | string };
const renderFooOrBar = (item: FooItem) => html`${item.which === "foo" ? "foo" : "bar"}`;
const items: FooItem[] = [
{ name: "a", which: "foo" },
{ name: "b", which: "bar" },
{ name: "c", which: "other" },
];
const previousState = html`${items.map(renderFooOrBar)}`;
expect(previousState.partsTree()).toMatchInlineSnapshot(`
Object {
"0": Object {
"d": Array [
Array [
"foo",
],
Array [
"bar",
],
Array [
"bar",
],
],
"s": Array [
"",
"",
],
},
"s": Array [
"",
"",
],
}
`);
// always render foo
const nextState = html`${items
.map((f) => {
f.which = "foo";
return f;
})
.map(renderFooOrBar)}`;
const diff = deepDiff(previousState.partsTree(), nextState.partsTree());
expect(diff).toStrictEqual({
"0": {
d: [["foo"], ["foo"], ["foo"]],
},
});
expect(diff).toMatchInlineSnapshot(`
Object {
"0": Object {
"d": Array [
Array [
"foo",
],
Array [
"foo",
],
Array [
"foo",
],
],
},
}
`);
});
it("indexed dymamic value is different", () => {
const render = (toggle: boolean = false) => html`something ${"foo"} blah ${toggle ? "bar" : "baz"}`;
const previousState = render();
const nextState = render(true);
const diff = deepDiff(previousState.partsTree(), nextState.partsTree());
expect(diff).toMatchInlineSnapshot(`
Object {
"1": "bar",
}
`);
});
it("keys aren't both strings nor both Parts - one is a string and one is a part", () => {
let toggle = false;
const previousState = html`something ${"foo"} blah ${toggle ? "bar" : html`baz`}`;
toggle = true;
const nextState = html`something ${"foo"} blah ${toggle ? "bar" : html`baz`}`;
const diff = deepDiff(previousState.partsTree(), nextState.partsTree());
expect(diff).toStrictEqual({
"1": "bar",
});
});
it("newParts has a key that oldParts doesn't have", () => {
const subbaz = html`subbaz`;
let toggle = false;
const previousState = html`something ${"foo"} blah ${toggle ? "bar" : html`baz${toggle ? "" : subbaz}`}`;
toggle = true;
// not sure this should happen IRL because templates should be the same but for sake of testing
const nextState = html`something ${"foo"} blah ${toggle ? "bar" : html`baz${toggle ? "" : subbaz}`} ${"newkey"}`;
const diff = deepDiff(previousState.partsTree(), nextState.partsTree());
console.log("prevState", previousState.partsTree(), "nextState", nextState.partsTree(), "diff", diff);
expect(diff).toStrictEqual({
1: "bar",
2: "newkey",
s: ["something ", " blah ", " ", ""],
});
});
it("diffs for empty strings", () => {
// simulate a LiveComponent at the "1" key but with diff "0" keys
let oldParts: Parts = { 0: "" };
let newParts: Parts = { 0: "" };
expect(deepDiff(oldParts, newParts)).toMatchInlineSnapshot(`Object {}`);
});
it("diffs for live components", () => {
// simulate a LiveComponent at the "1" key but with diff "0" keys
let oldParts: Parts = { 0: "something", 1: 1 };
let newParts: Parts = { 0: "something else", 1: 1 };
expect(deepDiff(oldParts, newParts)).toMatchInlineSnapshot(`
Object {
"0": "something else",
}
`);
// simulate diff live component at key "1"
oldParts = { 0: "something", 1: 1 };
newParts = { 0: "something else", 1: 2 };
expect(deepDiff(oldParts, newParts)).toMatchInlineSnapshot(`
Object {
"0": "something else",
"1": 2,
}
`);
});
it("diffs correctly", () => {
const oldParts = {
"0": "",
"1": "",
"2": {
"0": 1,
"1": { s: [""] },
s: [
"\n <h1>Decarbonize Calculator</h1>\n <div>\n ",
"\n </div>\n <div>\n ",
"\n </div>\n ",
],
},
s: ['\n <main role="main" class="container">\n ', "\n ", "\n ", "\n </main>\n "],
};
const newParts = {
"0": "",
"1": "",
"2": {
"0": 1,
"1": {
"0": "13",
s: [
"\n <div>\n <h3>Carbon Footprint 👣</h3>\n <p>",
" tons of CO2</p>\n </div>\n ",
],
},
s: [
"\n <h1>Decarbonize Calculator</h1>\n <div>\n ",
"\n </div>\n <div>\n ",
"\n </div>\n ",
],
},
s: ['\n <main role="main" class="container">\n ', "\n ", "\n ", "\n </main>\n "],
};
expect(JSON.stringify(deepDiff(oldParts, newParts))).toMatchInlineSnapshot(
`"{\\"2\\":{\\"1\\":{\\"0\\":\\"13\\",\\"s\\":[\\"\\\\n <div>\\\\n <h3>Carbon Footprint 👣</h3>\\\\n <p>\\",\\" tons of CO2</p>\\\\n </div>\\\\n \\"]}}}"`
);
});
it("diffs arrays where both parts are objects but not arrays", () => {
const oldArray = [{ 0: "a", 1: "b", s: ["1", "2", "3"] }];
const newArray = [{ 0: "a", 1: "b", s: ["1", "2", "3"] }];
expect(diffArrays(oldArray, newArray)).toBeFalsy();
});
it("diffs arrays where both parts are objects but not arrays", () => {
const oldArray = [{ 0: "a", 1: "b", s: ["1", "2", "3"] }];
const newArray = [{ 0: "a", 1: "c", s: ["1", "2", "3"] }];
expect(diffArrays(oldArray, newArray)).toBeTruthy();
});
it("diffs arrays with objs with diff key lengths return true", () => {
const oldArray = [{ 0: "a", 1: "b", s: ["1", "2", "3"] }];
const newArray = [{ 0: "a", s: ["1", "2", "3"] }];
expect(diffArrays(oldArray, newArray)).toBeTruthy();
});
it("diffs arrays with diff lengths return true", () => {
const oldArray = [{ 0: "a" }, { 0: "b" }];
const newArray = [{ 0: "a" }];
expect(diffArrays(oldArray, newArray)).toBeTruthy();
});
it("diffs arrays with same number parts returns false", () => {
const oldArray = [{ 0: 1 }];
const newArray = [{ 0: 1 }];
expect(diffArrays(oldArray, newArray)).toBeFalsy();
});
it("diffs this", () => {
const oldParts = require("../../../diffs/220323/oldView.json");
const newParts = require("../../../diffs/220323/view.json");
const diff = deepDiff(oldParts, newParts);
console.log(JSON.stringify(diff, null, 2));
expect(diff).toMatchInlineSnapshot(`
Object {
"1": Object {
"0": Object {
"0": Object {
"0": "general",
"1": "Basic Account Details",
"s": Array [
"
<!-- Completed Step -->
<a href=\\"#\\" class=\\"group\\">
<span
class=\\"absolute top-0 left-0 w-1 h-full lg:w-full lg:h-1 lg:bottom-0 lg:top-auto bg-transparent group-hover:bg-gray-200\\"
aria-hidden=\\"true\\"></span>
<span class=\\"px-6 py-5 flex items-start text-sm font-medium\\">
<span class=\\"flex-shrink-0\\">
<span class=\\"w-10 h-10 flex items-center justify-center rounded-full bg-green-600 \\">
<!-- Heroicon name: solid/check -->
<svg
class=\\"w-6 h-6 text-white\\"
xmlns=\\"http://www.w3.org/2000/svg\\"
viewBox=\\"0 0 20 20\\"
fill=\\"currentColor\\"
aria-hidden=\\"true\\">
<path
fill-rule=\\"evenodd\\"
d=\\"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z\\"
clip-rule=\\"evenodd\\" />
</svg>
</span>
</span>
<span class=\\"mt-0.5 ml-4 min-w-0 flex flex-col\\">
<span class=\\"text-xs font-semibold tracking-wide uppercase\\">",
"</span>
<span class=\\"text-sm font-medium text-gray-500\\">",
"</span>
</span>
</span>
</a>
",
],
},
},
"1": Object {
"0": Object {
"s": Array [
"
<!-- Current Step -->
<span
class=\\"absolute top-0 left-0 w-1 h-full lg:w-full lg:h-1 lg:bottom-0 lg:top-auto bg-green-600\\"
aria-hidden=\\"true\\"></span>
<span class=\\"px-6 py-5 flex items-start text-sm font-medium lg:pl-9\\">
<span class=\\"flex-shrink-0\\">
<span class=\\"w-10 h-10 flex items-center justify-center rounded-full border-2 border-green-600\\">
<span class=\\"text-green-600\\">",
"</span>
</span>
</span>
<span class=\\"mt-0.5 ml-4 min-w-0 flex flex-col\\">
<span class=\\"text-xs font-semibold text-green-600 tracking-wide uppercase\\">",
"</span>
<span class=\\"text-sm font-medium text-gray-500\\">",
"</span>
</span>
</span>
",
],
},
},
},
"2": Object {
"0": Object {
"0": "",
"1": "program",
"2": "post",
"3": Object {
"s": Array [
" phx-submit=\\"save\\"",
],
},
"4": Object {
"s": Array [
" phx-change=\\"validate\\"",
],
},
"s": Array [
"<form",
" action=\\"",
"\\" method=\\"",
"\\"",
"",
">",
],
},
"s": Array [
"
",
"
<input type=\\"text\\" name=\\"company_name\\" placeholder=\\"Program\\" />
<button type=\\"submit\\">Next</button>
</form>
",
],
},
}
`);
});
}); | the_stack |
import {
BehaviorSubject,
Observable,
Subject,
Subscription
} from "rxjs";
import { Auditor } from "./auditor";
import { hook } from "./detect";
import { Detector } from "./detector";
import { hidden } from "./hidden";
import { identify } from "./identify";
import { defaultLogger, Logger, PartialLogger, toLogger } from "./logger";
import { Match, matches, toString as matchToString } from "./match";
import { hide } from "./operators";
import {
CyclePlugin,
DebugPlugin,
Deck,
GraphPlugin,
LetPlugin,
LogPlugin,
Notification,
ObservableSnapshot,
PausePlugin,
Plugin,
SnapshotPlugin,
StackTracePlugin,
StatsPlugin,
SubscriberSnapshot,
SubscriptionSnapshot
} from "./plugin";
import { wrap } from "./spy-console";
import { Ctor, Options, Spy, Teardown } from "./spy-interface";
import { SubscriptionRef } from "./subscription-ref";
import { toSubscriber } from "./util";
declare const __RX_SPY_VERSION__: string;
/*tslint:disable-next-line:deprecation*/
const observableSubscribe = Observable.prototype.subscribe;
const previousWindow: Record<string, any> = {};
export class SpyCore implements Spy {
private static spy_: SpyCore | undefined = undefined;
private auditor_: Auditor;
private defaultLogger_: PartialLogger;
private maxLogged_ = 20;
private plugins_: Plugin[];
private pluginsSubject_: BehaviorSubject<Plugin[]>;
private teardown_: Teardown | undefined;
private tick_: number;
private undos_: Plugin[];
private warned_: { [key: string]: boolean };
constructor(options: {
[key: string]: any,
audit?: number;
defaultLogger?: PartialLogger,
defaultPlugins?: boolean,
global?: string,
plugins?: Plugin[],
warning?: boolean
} = {}) {
if (SpyCore.spy_) {
throw new Error("Already spying on Observable.prototype.subscribe.");
}
if (options.warning) {
/*tslint:disable-next-line:no-console*/
console.warn("Spying on Observable.prototype.subscribe.");
}
SpyCore.spy_ = this;
/*tslint:disable-next-line:deprecation*/
Observable.prototype.subscribe = SpyCore.coreSubscribe_;
this.auditor_ = new Auditor(options.audit || 0);
this.defaultLogger_ = options.defaultLogger || defaultLogger;
if (options.defaultPlugins === false) {
this.plugins_ = [];
} else {
this.plugins_ = [
new StackTracePlugin(options as Options),
new GraphPlugin(options as Options),
new SnapshotPlugin(this, options as Options),
new CyclePlugin(this, this.defaultLogger_),
new StatsPlugin(this)
];
}
this.pluginsSubject_ = new BehaviorSubject(this.plugins_);
this.tick_ = 0;
this.undos_ = [];
this.warned_ = {};
const detector = new Detector(this);
hook((id) => this.detect_(id, detector));
if (typeof window !== "undefined") {
[options.global || "spy", "rxSpy"].forEach(key => {
if (window.hasOwnProperty(key)) {
this.defaultLogger_.log(`Overwriting window.${key}`);
previousWindow[key] = window[key];
}
window[key] = wrap(this, key === "rxSpy" ?
() => this.warnOnce(this.defaultLogger_, `window.${key} is deprecated and has been renamed; use window.spy instead`) :
undefined
);
});
}
this.teardown_ = () => {
if (typeof window !== "undefined") {
[options.global || "spy", "rxSpy"].forEach(key => {
if (previousWindow.hasOwnProperty(key)) {
this.defaultLogger_.log(`Restoring window.${key}`);
window[key] = previousWindow[key];
delete previousWindow[key];
} else {
delete window[key];
}
});
}
hook(undefined);
this.plugins_.forEach((plugin) => plugin.teardown());
this.plugins_ = [];
this.pluginsSubject_.next(this.plugins_);
this.undos_ = [];
SpyCore.spy_ = undefined;
/*tslint:disable-next-line:deprecation*/
Observable.prototype.subscribe = observableSubscribe;
};
}
get auditor(): Auditor {
return this.auditor_;
}
get tick(): number {
return this.tick_;
}
get undos(): Plugin[] {
return [...this.undos_];
}
get version(): string {
return __RX_SPY_VERSION__;
}
debug(match: Match, ...notifications: Notification[]): Teardown {
if (notifications.length === 0) {
notifications = ["complete", "error", "next", "subscribe", "unsubscribe"];
}
return this.plug(new DebugPlugin(match, notifications));
}
find<T extends Plugin>(ctor: Ctor<T>): T | undefined {
const found = this.plugins_.find((plugin) => plugin instanceof ctor);
return found ? found as T : undefined;
}
findAll<T extends Plugin>(ctor: Ctor<T>): T[];
findAll(): Plugin[];
findAll<T extends Plugin>(ctor?: Ctor<T>): T[] | Plugin[] {
return ctor ?
this.plugins_.filter((plugin) => plugin instanceof ctor) as T[] :
this.plugins_;
}
flush(): void {
this.plugins_.forEach((plugin) => plugin.flush());
}
let(match: Match, select: (source: Observable<any>) => Observable<any>, options?: Options): Teardown {
return this.plug(new LetPlugin(match, select, options));
}
log(tagMatch: Match, notificationMatch: Match, partialLogger?: PartialLogger): Teardown;
log(tagMatch: Match, partialLogger?: PartialLogger): Teardown;
log(partialLogger?: PartialLogger): Teardown;
log(...args: any[]): Teardown {
let tagMatch: Match = /.+/;
let notificationMatch: Match = /.+/;
let partialLogger: PartialLogger = this.defaultLogger_;
if (args.length === 1) {
const [arg] = args;
if (typeof arg.log === "function") {
partialLogger = arg;
} else {
tagMatch = arg;
}
} else if (args.length === 2) {
let arg: any;
[tagMatch, arg] = args;
if (typeof arg.log === "function") {
partialLogger = arg;
} else {
notificationMatch = arg;
}
} else if (args.length === 3) {
[tagMatch, notificationMatch, partialLogger] = args;
}
return this.plug(new LogPlugin(this, tagMatch, notificationMatch, partialLogger));
}
maxLogged(value: number): void {
this.maxLogged_ = Math.max(value, 1);
}
pause(match: Match): Deck {
const pausePlugin = new PausePlugin(match);
const teardown = this.plug(pausePlugin);
const deck = pausePlugin.deck;
deck.teardown = teardown;
return deck;
}
plug(...plugins: Plugin[]): Teardown {
this.plugins_.push(...plugins);
this.pluginsSubject_.next(this.plugins_);
this.undos_.push(...plugins);
return () => this.unplug(...plugins);
}
query(
predicate: (record: {
complete: boolean;
error: any;
incomplete: boolean;
path: string;
root: boolean;
tag: string | undefined;
type: string;
unsubscribed: boolean;
}) => boolean,
partialLogger?: PartialLogger
): void {
const snapshotPlugin = this.find(SnapshotPlugin);
if (!snapshotPlugin) {
this.warnOnce(console, "Snapshotting is not enabled.");
return;
}
const snapshot = snapshotPlugin.snapshotAll();
const observableSnapshots = Array.from(snapshot.observables.values());
const logger = toLogger(partialLogger || this.defaultLogger_);
snapshot.mapStackTraces(observableSnapshots).subscribe(() => {
const found: {
observable: ObservableSnapshot;
subs: {
subscriber: SubscriberSnapshot;
subscription: SubscriptionSnapshot;
}[]
}[] = [];
observableSnapshots.forEach(observableSnapshot => {
let find: typeof found[0] | undefined;
const { subscriptions } = observableSnapshot;
subscriptions.forEach((subscriptionSnapshot) => {
const subscriberSnapshot = snapshot.subscribers.get(subscriptionSnapshot.subscriber);
if (subscriberSnapshot) {
if (predicate({
complete: subscriptionSnapshot.complete,
error: subscriptionSnapshot.error,
incomplete: !subscriptionSnapshot.complete && !subscriptionSnapshot.error,
path: observableSnapshot.path,
root: subscriptionSnapshot.sink === subscriptionSnapshot.rootSink,
tag: observableSnapshot.tag,
type: observableSnapshot.type,
unsubscribed: subscriptionSnapshot.unsubscribed
})) {
if (!find) {
find = {
observable: observableSnapshot,
subs: []
};
}
find.subs.push({
subscriber: subscriberSnapshot,
subscription: subscriptionSnapshot
});
}
}
});
if (find) {
found.push(find);
}
});
const { maxLogged_ } = this;
const notLogged = (found.length > maxLogged_) ? found.length - maxLogged_ : 0;
if (notLogged) {
found.splice(maxLogged_, notLogged);
}
logger.group(`${found.length + notLogged} snapshot(s) found`);
const observableGroupMethod = (found.length > 3) ? "groupCollapsed" : "group";
found.forEach(find => {
const observableSnapshot = find.observable;
logger[observableGroupMethod].call(logger, observableSnapshot.tag ?
`Tag = ${observableSnapshot.tag}` :
`Type = ${observableSnapshot.type}`
);
logger.log("Path =", observableSnapshot.path);
const { subs } = find;
const subscriberGroupMethod = (find.subs.length > 3) ? "groupCollapsed" : "group";
logger.group(`${subs.length} subscriber(s)`);
subs.forEach(sub => {
const subscriptionSnapshot = sub.subscription;
const subscriberSnapshot = sub.subscriber;
const { values, valuesFlushed } = subscriberSnapshot;
logger[subscriberGroupMethod].call(logger, "Subscriber");
logger.log("Value count =", values.length + valuesFlushed);
if (values.length > 0) {
logger.log("Last value =", values[values.length - 1].value);
}
logSubscription(logger, subscriptionSnapshot);
const otherSubscriptions = Array
.from(subscriberSnapshot.subscriptions.values())
.filter((otherSubscriptionSnapshot) => otherSubscriptionSnapshot !== subscriptionSnapshot);
otherSubscriptions.forEach((otherSubscriptionSnapshot) => {
logger.groupCollapsed("Other subscription");
logSubscription(logger, otherSubscriptionSnapshot);
logger.groupEnd();
});
logger.groupEnd();
});
logger.groupEnd();
logger.groupEnd();
});
if (notLogged) {
logger.log(`... another ${notLogged} snapshot(s) not logged.`);
}
logger.groupEnd();
});
}
show(match: Match, partialLogger?: PartialLogger): void;
show(partialLogger?: PartialLogger): void;
show(match: any, partialLogger?: PartialLogger): void {
const anyTagged = /.+/;
if (!match) {
match = anyTagged;
} else if (typeof match.log === "function") {
partialLogger = match;
match = anyTagged;
}
const snapshotPlugin = this.find(SnapshotPlugin);
if (!snapshotPlugin) {
this.warnOnce(console, "Snapshotting is not enabled.");
return;
}
const snapshot = snapshotPlugin.snapshotAll();
const matched = Array
.from(snapshot.observables.values())
.filter((observableSnapshot) => matches(observableSnapshot.observable, match));
const logger = toLogger(partialLogger || this.defaultLogger_);
const { maxLogged_ } = this;
const notLogged = (matched.length > maxLogged_) ? matched.length - maxLogged_ : 0;
if (notLogged) {
matched.splice(maxLogged_, notLogged);
}
snapshot.mapStackTraces(matched).subscribe(() => {
logger.group(`${matched.length + notLogged} snapshot(s) matching ${matchToString(match)}`);
const observableGroupMethod = (matched.length > 3) ? "groupCollapsed" : "group";
matched.forEach((observableSnapshot) => {
logger[observableGroupMethod].call(logger, observableSnapshot.tag ?
`Tag = ${observableSnapshot.tag}` :
`Type = ${observableSnapshot.type}`
);
logger.log("Path =", observableSnapshot.path);
const { subscriptions } = observableSnapshot;
const subscriberGroupMethod = (subscriptions.size > 3) ? "groupCollapsed" : "group";
logger.group(`${subscriptions.size} subscriber(s)`);
subscriptions.forEach((subscriptionSnapshot) => {
const subscriberSnapshot = snapshot.subscribers.get(subscriptionSnapshot.subscriber);
if (subscriberSnapshot) {
const { values, valuesFlushed } = subscriberSnapshot;
logger[subscriberGroupMethod].call(logger, "Subscriber");
logger.log("Value count =", values.length + valuesFlushed);
if (values.length > 0) {
logger.log("Last value =", values[values.length - 1].value);
}
logSubscription(logger, subscriptionSnapshot);
const otherSubscriptions = Array
.from(subscriberSnapshot.subscriptions.values())
.filter((otherSubscriptionSnapshot) => otherSubscriptionSnapshot !== subscriptionSnapshot);
otherSubscriptions.forEach((otherSubscriptionSnapshot) => {
logger.groupCollapsed("Other subscription");
logSubscription(logger, otherSubscriptionSnapshot);
logger.groupEnd();
});
logger.groupEnd();
} else {
logger.warn("Cannot find subscriber snapshot");
}
});
logger.groupEnd();
logger.groupEnd();
});
if (notLogged) {
logger.log(`... another ${notLogged} snapshot(s) not logged.`);
}
logger.groupEnd();
});
}
stats(partialLogger?: PartialLogger): void {
const statsPlugin = this.find(StatsPlugin);
if (!statsPlugin) {
this.warnOnce(console, "Stats are not enabled.");
return;
}
const stats = statsPlugin.stats;
const { leafSubscribes, maxDepth, flattenedSubscribes, rootSubscribes, totalDepth } = stats;
const logger = toLogger(partialLogger || this.defaultLogger_);
logger.group("Stats");
logger.log("Subscribes =", stats.subscribes);
if (rootSubscribes > 0) {
logger.log("Root subscribes =", rootSubscribes);
}
if (leafSubscribes > 0) {
logger.log("Leaf subscribes =", leafSubscribes);
}
if (flattenedSubscribes > 0) {
logger.log("Flattened subscribes =", flattenedSubscribes);
}
logger.log("Unsubscribes =", stats.unsubscribes);
logger.log("Nexts =", stats.nexts);
logger.log("Errors =", stats.errors);
logger.log("Completes =", stats.completes);
if (maxDepth > 0) {
logger.log("Max. depth =", maxDepth);
logger.log("Avg. depth =", (totalDepth / leafSubscribes).toFixed(1));
}
logger.log("Tick =", stats.tick);
logger.log("Timespan =", stats.timespan);
logger.groupEnd();
}
teardown(): void {
if (this.teardown_) {
this.teardown_();
this.teardown_ = undefined;
}
}
unplug(...plugins: Plugin[]): void {
plugins.forEach((plugin) => {
plugin.teardown();
this.plugins_ = this.plugins_.filter((p) => p !== plugin);
this.pluginsSubject_.next(this.plugins_);
this.undos_ = this.undos_.filter((u) => u !== plugin);
});
}
/** @deprecated Use warnOnce */
warn(logger: PartialLogger, message: any, ...args: any[]): void {
this.warnOnce(logger, message, ...args);
}
warnOnce(logger: PartialLogger, message: any, ...args: any[]): void {
if (!this.warned_[message]) {
toLogger(logger).warn(message, ...args);
this.warned_[message] = true;
}
}
/*tslint:disable-next-line:member-ordering*/
private static coreSubscribe_(this: Observable<any>, ...args: any[]): Subscription {
/*tslint:disable-next-line:no-invalid-this*/
const observable = this;
const { spy_ } = SpyCore;
if (!spy_) {
return observableSubscribe.apply(observable, args);
}
if (hidden(observable)) {
SpyCore.spy_ = undefined;
try {
return observableSubscribe.apply(observable, args);
} finally {
SpyCore.spy_ = spy_;
}
}
const notify_ = (before: (plugin: Plugin) => void, block: () => void, after: (plugin: Plugin) => void) => {
++spy_.tick_;
spy_.plugins_.forEach(before);
block();
spy_.plugins_.forEach(after);
};
const subscriber = toSubscriber.apply(undefined, args);
const ref: SubscriptionRef = {
observable,
subscriber,
subscription: new Subscription(),
timestamp: Date.now(),
unsubscribed: false
};
identify(observable);
identify(subscriber);
identify(ref);
const subscriberUnsubscribe = subscriber.unsubscribe;
subscriber.unsubscribe = () => {
if (!subscriber.closed) {
notify_(
(plugin) => plugin.beforeUnsubscribe(ref),
() => {
ref.subscription.unsubscribe();
ref.unsubscribed = true;
subscriberUnsubscribe.call(subscriber);
},
(plugin) => plugin.afterUnsubscribe(ref)
);
} else {
subscriberUnsubscribe.call(subscriber);
}
};
const postSelectObserver = {
complete(): void {
notify_(
(plugin) => plugin.beforeComplete(ref),
() => subscriber.complete(),
(plugin) => plugin.afterComplete(ref)
);
},
error(error: any): void {
notify_(
(plugin) => plugin.beforeError(ref, error),
() => subscriber.error(error),
(plugin) => plugin.afterError(ref, error)
);
},
next(value: any): void {
notify_(
(plugin) => plugin.beforeNext(ref, value),
() => subscriber.next(value),
(plugin) => plugin.afterNext(ref, value)
);
}
};
const preSelectObserver = {
complete(): void {
this.completed = true;
if (this.preSelectSubject) {
this.preSelectSubject.complete();
} else {
this.postSelectObserver.complete();
}
},
completed: false,
error(error: any): void {
this.errored = true;
if (this.preSelectSubject) {
this.preSelectSubject.error(error);
} else {
this.postSelectObserver.error(error);
}
},
errored: false,
let(plugins: Plugin[]): void {
const selectors = plugins.map((plugin) => plugin.select(ref)).filter(Boolean);
if (selectors.length > 0) {
if (!this.preSelectSubject) {
this.preSelectSubject = new Subject<any>();
}
if (this.postSelectSubscription) {
this.postSelectSubscription.unsubscribe();
}
let source = this.preSelectSubject.asObservable();
selectors.forEach(selector => source = selector!(source));
this.postSelectSubscription = source.pipe(hide()).subscribe(postSelectObserver);
} else if (this.postSelectSubscription) {
this.postSelectSubscription.unsubscribe();
this.postSelectSubscription = undefined;
this.preSelectSubject = undefined;
}
},
next(value: any): void {
if (this.preSelectSubject) {
this.preSelectSubject.next(value);
} else {
this.postSelectObserver.next(value);
}
},
postSelectObserver,
postSelectSubscription: undefined as Subscription | undefined,
preSelectSubject: undefined as Subject<any> | undefined,
unsubscribe(): void {
if (!this.unsubscribed) {
this.unsubscribed = true;
if (!this.completed && !this.errored) {
if (this.postSelectSubscription) {
this.postSelectSubscription.unsubscribe();
this.postSelectSubscription = undefined;
}
}
}
},
unsubscribed: false
};
subscriber.add(spy_.pluginsSubject_.pipe(hide()).subscribe({
next: (plugins: any) => preSelectObserver.let(plugins)
}));
notify_(
(plugin) => plugin.beforeSubscribe(ref),
() => {
subscriber.add(observableSubscribe.call(observable, preSelectObserver));
subscriber.add(() => preSelectObserver.unsubscribe());
},
(plugin) => plugin.afterSubscribe(ref)
);
return subscriber;
}
private detect_(id: string, detector: Detector): void {
const { auditor_, defaultLogger_ } = this;
auditor_.audit(id, (ignored) => {
const detected = detector.detect(id);
const logger = toLogger(defaultLogger_);
if (detected) {
const audit = (ignored === 0) ? "" : `; ignored ${ignored}`;
logger.group(`Subscription changes detected; id = '${id}'${audit}`);
detected.subscriptions.forEach((s) => {
logSubscription(logger, "Subscription", s);
});
detected.unsubscriptions.forEach((s) => {
logSubscription(logger, "Unsubscription", s);
});
detected.flatteningSubscriptions.forEach((s) => {
logSubscription(logger, "Flattening subscription", s);
});
detected.flatteningUnsubscriptions.forEach((s) => {
logSubscription(logger, "Flattening unsubscription", s);
});
logger.groupEnd();
}
function logSubscription(logger: Logger, name: string, subscription: SubscriptionSnapshot): void {
logger.group(name);
logger.log("Root subscribe", subscription.rootSink ?
subscription.rootSink.stackTrace :
subscription.stackTrace
);
logger.log("Subscribe", subscription.stackTrace);
logger.groupEnd();
}
});
}
}
function logStackTrace(logger: Logger, subscriptionSnapshot: SubscriptionSnapshot): void {
const { mappedStackTrace, rootSink } = subscriptionSnapshot;
const mapped = rootSink ? rootSink.mappedStackTrace : mappedStackTrace;
mapped.subscribe(stackTrace => logger.log("Root subscribe", stackTrace));
}
function logSubscription(logger: Logger, subscriptionSnapshot: SubscriptionSnapshot): void {
const { complete, error, unsubscribed } = subscriptionSnapshot;
logger.log("State =", complete ? "complete" : error ? "error" : "incomplete");
if (error) {
logger.error("Error =", error);
}
if (unsubscribed) {
logger.log("Unsubscribed =", true);
}
logStackTrace(logger, subscriptionSnapshot);
} | the_stack |
import { AggregateRewriteData, ConditionalStyle, ConditionalStyleExpression, StyleExpression } from "./AggregateRewriteData";
const root = Symbol("style root");
const STYLE_TYPE = Symbol("style type");
const IMPLICATION_TYPE = Symbol("style type");
interface StyleCondition {
type: typeof STYLE_TYPE;
style: number;
condition: ConditionalStyleExpression;
}
interface ImplicationCondition {
type: typeof IMPLICATION_TYPE;
fromStyle: number;
toStyles: Array<number>;
condition: ConditionalStyleExpression;
}
enum Operator {
AND = 1,
OR = 2,
NOT = 3,
}
function assertNever(_value: never): never {
throw new Error("[Internal Error] This should have never happened.");
}
type Condition = StyleCondition | ImplicationCondition;
/**
* The goal of style resolution is to use the relationships declared between
* different CSS Block styles to infer the presence of some styles based
* on the current runtime set of styles applied explicitly by the author.
*
* In addition to adding styles to an element, style resolution can result in
* the removal of an explicitly applied style when the element's styles do not
* meet the requirements of those styles based on the presence of related
* styles.
*
* Specifically, style resolution handles the following CSS Block features:
* - Block Inheritance.
* - Stylesheet-based style composition.
* - Block aliases.
* - Class attributes only matching an element when the element has the class.
*
* This class implements a graph where the nodes are styles and directed edges
* are "implications". That is, the edge of (s1, s2) means that style s1 implies
* the presence of style s2.
*
* The graph's start node is a javascript Symbol named `root`. A style is
* considered to be applied to the element if it is reachable from the start
* node.
*
* We first populate the graph the graph with all possible styles that might be
* applied to the element and as we do so we record any requirements for the presence
* of that applied style because we can't know whether the requirements are properly
* met until all styles are added to the graph.
*
* Some requirements only remove one or more implications, which might leave
* the style node connected through some other path. Other requirements can
* cause the style node and all outbound implications to be removed.
*
* Because we use a unique number to represent a style, this graph is
* constructed a little differently from most graphs: There is no node type.
* Instead, we use a Map where the key is a style id and the value is a set of
* style ids implied by the key.
*
* The RuntimeDataGenerator emits data about the CSS Blocks styles that has
* undergone a significant amount of data preparation in order for this resolver
* to run without needing to perform its work in the domain of the CSS Block
* interfaces. Instead the CSS Block relationships are boiled down to implied
* styles and style requirements.
*
* An implied style takes one of three forms:
* - A style id (always implied)
* - A css class name (from an alias)
* - A conditional style implies one or more styles but only when the condition
* is satisfied. The condition is a boolean style expression of the same format
* that is used by the optimizer's output classnames. These conditions become a
* type of style requirement.
*
* A style requirement is a mapping from a style id to a boolean style
* expression that must evaluate to true in order for the style to be allowed
* to remain on the element.
*
* In order to enforce style requirements, once we've added all possible styles
* to the graph, we iterate over the requirements and remove any styles or
* implications that are not satisfied. If any styles are removed, this may
* cause a style requirement that previously was satisfied to become
* dissatisfied. Because of this we keep iterating over the list of style
* requirements until no styles are removed.
*
* During style requirements processing it's possible for sections of the graph
* to become disconnected from the root node, thus causing all the styles that
* were transitively implied by the removed style to also be removed from the
* element.
*
* Unfortunately, this means that during requirements processing we must
* perform a depth first search for any style that is mentioned in a boolean
* style expression. Fortunately, the size of the graph is generally small
* and relatively flat. However, there are ways to optimize the graph
* so that these reads are faster and in aggregate might result in a small
* runtime performance boost.
*/
export class StyleResolver {
/** source data for implied styles and style requirements. */
data: AggregateRewriteData;
/** This is the implication graph. */
implications: Map<number | typeof root, Set<number>>;
_impliedClassNames: Map<number, Set<string>>;
/** Style requirements that must be satisfied. */
conditionals: Array<Condition>;
constructor(data: AggregateRewriteData) {
this.data = data;
this.implications = new Map<typeof root | number, Set<number>>();
this._impliedClassNames = new Map<number, Set<string>>();
this.conditionals = [];
}
/**
* Returns true if the style is currently connected to the root node.
*/
public hasStyle(styleToFind: number): boolean {
return this.hasStyleFrom(root, styleToFind);
}
private hasStyleFrom(fromStyle: number | typeof root, styleToFind: number): boolean {
let implication = this.implications.get(fromStyle);
if (implication) {
if (implication.has(styleToFind)) return true;
for (let s of implication) {
if (this.hasStyleFrom(s, styleToFind)) return true;
}
}
return false;
}
/**
* Adds an explicitly declared style to the style resolver.
*/
public addStyle(style: number) {
this.addImpliedStyle(root, style);
}
/**
* This method mutates the graph and should only be called a single time
* once all styles are added.
*/
public resolve(): Set<number> {
this.importRequirements();
this.processConditions();
return this.currentStyles();
}
/**
* Gets all the implied class names for styles currently connected to root.
*/
public impliedClassNames(): Set<string> {
let classNames = new Set<string>();
for (let style of this.currentStyles()) {
let implied = this._impliedClassNames.get(style);
if (implied) {
for (let className of implied) {
classNames.add(className);
}
}
}
return classNames;
}
public currentStyles(): Set<number> {
let styles = new Set<number>();
this.currentStylesFrom(root, styles);
return styles;
}
private addImpliedStyle(impliedBy: number | typeof root, style: number) {
addValueToMap(this.implications, impliedBy, style);
this._importImpliedStyles(style);
}
/**
* Imports implied styles from the read only aggregate rewrite data into this
* resolver.
*/
private _importImpliedStyles(fromStyle: number) {
let implied = this.data.impliedStyles[fromStyle];
if (implied) {
for (let i of implied) {
if (typeof i === "string") {
this.addImpliedClassName(fromStyle, i);
} else if (typeof i === "number") {
this.addImpliedStyle(fromStyle, i);
} else {
this.addCondition(fromStyle, i);
}
}
}
}
/**
* Adds style implications and records the associated style requirements.
*/
private addCondition(fromStyle: number, condition: ConditionalStyle) {
this.conditionals.push({
type: IMPLICATION_TYPE,
fromStyle,
toStyles: condition.styles,
condition: condition.conditions,
});
for (let s of condition.styles) {
this.addImpliedStyle(fromStyle, s);
}
}
private addImpliedClassName(impliedBy: number, className: string) {
addValueToMap(this._impliedClassNames, impliedBy, className);
}
private processConditions() {
// This removes all the styles for which the condition isn't satisfied.
// Doing so might cause some other condition to no longer be satisfied,
// So we keep processing the conditionals until nothing was removed.
let checkAgain = true;
while (checkAgain) {
checkAgain = false;
for (let conditional of this.conditionals) {
if (!this.evaluateExpression(conditional.condition)) {
if (conditional.type === STYLE_TYPE) {
let result = this.removeStyle(conditional.style);
checkAgain = checkAgain || result;
} else if (conditional.type === IMPLICATION_TYPE) {
for (let s of conditional.toStyles) {
let result = this.removeImplication(conditional.fromStyle, s);
checkAgain = checkAgain || result;
}
} else {
assertNever(conditional);
}
}
}
}
}
/**
* Evaluates a boolean style expression.
*/
private evaluateExpression(expr: StyleExpression): boolean {
if (typeof expr === "number") return this.hasStyle(expr);
let op: Operator = expr[0];
if (op === Operator.AND) {
for (let i = 1; i < expr.length; i++) {
if (!this.evaluateExpression(expr[i])) return false;
}
return true;
} else if (op === Operator.OR) {
for (let i = 1; i < expr.length; i++) {
if (this.evaluateExpression(expr[i])) return true;
}
return false;
} else if (op === Operator.NOT) {
return !this.evaluateExpression(expr[1]);
} else {
assertNever(op);
}
}
/**
* Removes an edge from the graph. This may leave orphaned nodes in the graph.
*/
private removeImplication(fromStyle: number, toStyle: number): boolean {
if (this.implications.has(fromStyle)) {
return this.implications.get(fromStyle)!.delete(toStyle);
}
return false;
}
/**
* Remove a style from the graph. This returns true if a style
* is removed, however that style might not be connected to the root node.
*/
private removeStyle(style: number): boolean {
let wasRemoved = false;
this.implications.delete(style);
for (let implication of this.implications.values()) {
let removed = implication.delete(style);
wasRemoved = wasRemoved || removed;
}
return wasRemoved;
}
/**
* Helper function that is used to construct a set of all styles reachable
* from the root.
*/
private currentStylesFrom(fromStyle: number | typeof root, styles: Set<number>): void {
if (fromStyle !== root) {
styles.add(fromStyle);
}
let implications = this.implications.get(fromStyle);
if (!implications) return;
for (let s of implications) {
this.currentStylesFrom(s, styles);
}
}
private importRequirements() {
for (let style of this.currentStyles()) {
let condition = this.data.styleRequirements[style];
if (condition) {
this.addRequirement(style, condition);
}
}
}
private addRequirement(style: number, condition: ConditionalStyleExpression) {
this.conditionals.push({
type: STYLE_TYPE,
style,
condition,
});
}
}
function addValueToMap<K, V>(map: Map<K, Set<V>>, key: K, value: V) {
if (!map.has(key)) {
map.set(key, new Set());
}
map.get(key)!.add(value);
} | the_stack |
import util from 'somes/util';
import paths from './paths';
import * as fs from 'somes/fs';
import path from 'somes/path';
import keys from 'somes/keys';
import FtrBuild, {PackageJson,native_source,native_header} from './build';
import { getLocalNetworkHost } from 'somes/network_host';
import * as child_process from 'child_process';
const isWindows = process.platform == 'win32';
function parse_json_file(filename: string, strict?: boolean) {
try {
var str = fs.readFileSync(filename, 'utf-8');
if (strict) {
return JSON.parse(str);
} else {
return eval('(\n' + str + '\n)');
}
} catch (err) {
err.message = filename + ': ' + err.message;
throw err;
}
}
function resolveLocal(...args: string[]) {
return path.fallbackPath(path.resolve(...args));
}
function filter_repeat(array: string[], ignore?: string) {
var r: Dict = {};
array.forEach(function(item) {
if ( !ignore || ignore != item ) {
r[item] = 1;
}
});
return Object.getOwnPropertyNames(r);
}
type PkgJson = PackageJson;
interface OutputGypi extends Dict {}
class Package {
readonly host: FtrExport;
readonly outputName: string;
readonly gypi_path: string;
readonly source_path: string;
readonly json: PkgJson;
readonly is_app: boolean;
readonly includes: string[] = [];
readonly include_dirs: string[] = [];
readonly sources: string[] = [ 'public' ];
readonly dependencies: string[] = [];
readonly dependencies_recursion: string[] = [];
readonly bundle_resources: string[] = [];
private _binding = false;
private _binding_gyp = false;
private _native = false;
private _gypi: OutputGypi | null = null;
get native() {
return this._native;
}
get gypi() {
util.assert(this._gypi);
return this._gypi as OutputGypi;
}
private get_start_argv() {
var self = this;
if ( self.is_app ) {
var name = self.outputName;
var json = self.json;
var inspect = '--inspect=0.0.0.0:9229 ';
var start_argv = name;
var start_argv_debug = inspect + 'http://' + getLocalNetworkHost()[0] + ':1026/' + name;
if ( json.skipInstall ) {
console.warn( 'skipInstall params May lead to Application', name, ' to start incorrectly' );
}
return [start_argv, start_argv_debug].map(e=>`ftr ${e}`);
}
return [] as string[];
}
constructor(host: FtrExport, source_path: string, outputName: string, json: PkgJson, is_app?: boolean) {
this.host = host;
this.source_path = source_path;
this.json = json;
this.is_app = is_app || false;
this.outputName = outputName;
this.gypi_path = host.output + '/' + outputName + '.gypi';
host.outputs[outputName] = this;
}
private _dependencies() {
var self = this;
var pkgs: Package[] = [];
var outputs = self.host.outputs;
for (var [k,v] of Object.entries((self.json.dependencies || {}) as Dict<string>)) {
// TODO looking for the right package
var version = v.replace(/^(~|\^)/, '');
var fullname = k + '@' + version;
var pkg = outputs[fullname];
if (!pkg) {
fullname = k;
pkg = outputs[fullname];
}
if (pkg) {
pkgs.push(pkg);
}
}
return pkgs;
}
private _dependencies_recursion(Out: Set<Package>) {
var self = this;
for (var pkg of self._dependencies()) {
Out.add(pkg);
pkg._dependencies_recursion(Out);
}
}
private get_dependencies_recursion() {
var pkgs: Package[] = [];
var set = new Set<Package>();
this._dependencies_recursion(set);
for (var pkg of set) {
pkgs.push(pkg);
}
return pkgs;
}
// reset app resources
private gen_before() {
var self = this;
var deps = self.get_dependencies_recursion();
var is_app = self.is_app;
var json = self.json;
if ( !json.skipInstall ) { // no skip install pkg
self.bundle_resources.push('install/' + this.outputName);
}
self.dependencies_recursion.push(...self.dependencies);
for (var pkg of self._dependencies()) {
self.dependencies.push(pkg.outputName);
}
if (is_app) {
for (var pkg of deps) {
self.includes.push(pkg.gypi_path);
self.dependencies_recursion.push(pkg.outputName);
if (!pkg.json.skipInstall)
self.bundle_resources.push('install/' + pkg.outputName);
}
self.includes.splice(0, Infinity, ...filter_repeat(self.includes));
self.dependencies_recursion.splice(0, Infinity, ...filter_repeat(self.dependencies_recursion, this.outputName));
self.bundle_resources.splice(0, Infinity, ...filter_repeat(self.bundle_resources));
}
self.dependencies.splice(0, Infinity, ...filter_repeat(self.dependencies, this.outputName));
if (self._binding || self._binding_gyp) {
self._native = true;
} else { // is native
for (var pkg of deps) {
if (pkg._native || pkg._binding || pkg._binding_gyp) {
this._native = true;
break;
}
}
}
}
initialize() {
var self = this;
var host = this.host;
var source_path = this.source_path;
var relative_source = path.relative(host.output, source_path);
// console.log('initialize relative', relative_source, '-', host.output, source_path);
// add native and source
if ( fs.existsSync(source_path + '/binding.gyp') ) {
var targets = parse_json_file(source_path + '/binding.gyp').targets as any[];
if (targets.length) {
var target = targets[0];
var target_name = target.target_name;
if (target_name) {
self.dependencies.push(path.relative(host.source, source_path) + '/binding.gyp:' + target_name);
self._binding_gyp = true;
}
}
}
var is_include_dirs = false;
// add source
fs.listSync(source_path, true, function(stat, pathname) {
var name = stat.name;
if ( name[0] != '.' ) {
if ( stat.isFile() ) {
var extname = path.extname(name).toLowerCase();
if (native_source.indexOf(extname) != -1) {
if (!self._binding_gyp) {
self._binding = true;
self.sources.push( relative_source + '/' + pathname );
} // else not add native source
is_include_dirs = true;
} else {
if (native_header.indexOf(extname) != -1) {
is_include_dirs = true;
}
self.sources.push( relative_source + '/' + pathname );
}
} else if ( stat.isDirectory() ) {
if (name == 'node_modules') {
var node_modules = source_path + '/' + pathname;
fs.listSync(node_modules, function(stat, pathname) {
if (pathname && stat.isDirectory())
host.solve(node_modules + '/' + stat.name, false, true);
});
return true; // cancel each children
}
}
}
});
if ( is_include_dirs ) {
self.include_dirs.push(relative_source);
}
}
private gen_ios_gypi(): OutputGypi {
var self = this;
var is_app = self.is_app;
var name = self.outputName;
var host = self.host;
var sources = self.sources;
var id = self.json.id || 'org.ftr.${PRODUCT_NAME:rfc1034identifier}';
var app_name = self.json.app || '${EXECUTABLE_NAME}';
var version = self.json.version;
var xcode_settings = {};
if ( is_app ) { // copy platfoem file
xcode_settings = {
'INFOPLIST_FILE': '<(XCODE_INFOPLIST_FILE)',
//'OTHER_LDFLAGS': '-all_load',
'SKIP_INSTALL': 'NO',
'ASSETCATALOG_COMPILER_APPICON_NAME': 'AppIcon',
'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME': 'LaunchImage',
'PRODUCT_BUNDLE_IDENTIFIER': id,
};
var out = host.proj_out;
var template = __dirname + '/export/'+ host.os +'/';
var plist = out + '/' + name + '.plist';
var storyboard = out + '/' + name + '.storyboard';
var xcassets = out + '/' + name + '.xcassets';
var main = out + '/' + name + '.mm';
var str;
// .plist
fs.cp_sync(template + 'main.plist', plist, { replace: false });
str = fs.readFileSync(plist).toString('utf8');
var reg0 = /(\<key\>CFBundleIdentifier\<\/key\>\n\r?\s*\<string\>)([^\<]+)(\<\/string\>)/;
var reg1 = /(\<key\>CFBundleDisplayName\<\/key\>\n\r?\s*\<string\>)([^\<]+)(\<\/string\>)/;
var reg2 = /(\<key\>CFBundleShortVersionString\<\/key\>\n\r?\s*\<string\>)([^\<]+)(\<\/string\>)/;
str = str.replace(reg0, function(a,b,c,d) { return b + id + d });
str = str.replace(reg1, function(a,b,c,d) { return b + app_name + d });
if (version) str = str.replace(reg2, function(a,b,c,d) { return b + version + d });
str = str.replace('[Storyboard]', name);
fs.writeFileSync( plist, str );
// .storyboard
fs.cp_sync( template + 'main.storyboard', storyboard, { replace: false } );
// .xcassets
fs.cp_sync( template + 'Images.xcassets', xcassets, { replace: false } );
self.bundle_resources.push('../Project/<(os)/' + name + '.storyboard');
self.bundle_resources.push('../Project/<(os)/' + name + '.xcassets');
if ( !fs.existsSync(main) ) { // main.mm
var start_argv = self.get_start_argv();
str = fs.readFileSync(template + 'main.mm').toString('utf8');
str = str.replace(/ARGV_DEBUG/, start_argv[1]);
str = str.replace(/ARGV_RELEASE/, start_argv[0]);
fs.writeFileSync( main, str );
}
sources.push('../Project/<(os)/' + name + '.plist');
sources.push('../Project/<(os)/' + name + '.storyboard');
sources.push('../Project/<(os)/' + name + '.mm');
}
// create gypi json data
var type = is_app ? 'executable' : self._binding ? 'static_library' : 'none';
var gypi =
{
'targets': [
{
'variables': is_app ? {
'XCODE_INFOPLIST_FILE': '$(SRCROOT)/Project/<(os)/' + name + '.plist'
} : {},
'target_name': name,
'product_name': is_app ? name + '-1' : name,
'type': type,
'include_dirs': self.include_dirs,
'dependencies': is_app ? self.dependencies_recursion: self.dependencies,
'direct_dependent_settings': {
'include_dirs': is_app ? [] : self.include_dirs,
},
'sources': sources,
'mac_bundle': is_app ? 1 : 0,
'mac_bundle_resources': is_app ? self.bundle_resources : [],
'xcode_settings': xcode_settings,
}
]
};
return gypi;
}
private gen_android_gypi(): OutputGypi {
var self = this;
var is_app = self.is_app;
var name = self.outputName;
var host = self.host;
var sources = self.sources;
var id = (self.json.id || 'org.ftr.' + name).replace(/-/gm, '_');
var app_name = self.json.app || name;
var version = self.json.version;
var java_pkg = id.replace(/\./mg, '/');
var so_pkg = self.native ? name : 'ftr-js';
if ( is_app ) { // copy platfoem file
var proj_out = host.proj_out;
var app = proj_out + '/' + name;
var AndroidManifest_xml = `${app}/src/main/AndroidManifest.xml`;
var strings_xml = `${app}/src/main/res/values/strings.xml`;
var MainActivity_java = `${app}/src/main/java/${java_pkg}/MainActivity.java`;
var build_gradle = `${app}/build.gradle`;
// copy android project template
fs.cp_sync(__dirname + '/export/android/proj_template', proj_out, { replace: false });
// copy android app template
fs.cp_sync(__dirname + '/export/android/app_template', proj_out + '/' + name, { replace: false });
fs.mkdirpSync(proj_out + '/' + name + '/src/main/assets');
fs.mkdirpSync(proj_out + '/' + name + '/src/main/java');
var str: string;
// MainActivity.java
var start_argv = self.get_start_argv();
fs.cp_sync(__dirname + '/export/android/MainActivity.java', MainActivity_java, { replace: false });
str = fs.readFileSync(MainActivity_java).toString('utf8');
str = str.replace(/\{id\}/gm, id);
str = str.replace(/String\s+LIBRARY\s+=\s+"[^\"]+"/, `String LIBRARY = "${so_pkg}"`);
str = str.replace(/ARGV_DEBUG/, start_argv[1]);
str = str.replace(/ARGV_RELEASE/, start_argv[0]);
fs.writeFileSync(MainActivity_java, str);
// AndroidManifest.xml
str = fs.readFileSync(AndroidManifest_xml).toString('utf8');
str = str.replace(/package\=\"[^\"]+\"/mg, `package="${id}"`);
str = str.replace(/android\:name\=\"android\.app\.lib_name\"\s+android\:value\=\"[^\"]+\"/,
`android:name="android.app.lib_name" android:value="${so_pkg}"`);
fs.writeFileSync(AndroidManifest_xml, str);
// strings.xml
str = fs.readFileSync(strings_xml).toString('utf8');
str = str.replace(/name\=\"app_name\"\>[^\<]+\</, `name="app_name">${app_name}<`);
fs.writeFileSync(strings_xml, str);
// build.gradle
str = fs.readFileSync(build_gradle).toString('utf8');
str = str.replace(/\{id\}/, id);
str = str.replace(/applicationId\s+('|")[^\'\"]+('|")/, `applicationId '${id}'`);
if (version) str = str.replace(/versionName\s+('|")[^\'\"]+('|")/, `versionName '${version}'`);
fs.writeFileSync(build_gradle, str);
}
// create gypi json data
var type = 'none';
if ( is_app ) {
if ( self.native ) {
type = 'shared_library';
if ( !self._binding ) {
// fs.writeFileSync(host.output, fs.readFileSync(__dirname + '/export/'));
fs.cp_sync(__dirname + '/export/empty.c', host.output + '/empty.c', { replace: false });
sources.push('empty.c');
}
}
} else if ( self._binding ) {
type = 'static_library';
}
var gypi =
{
'targets': [
{
'target_name': name,
'type': type,
'include_dirs': self.include_dirs,
'dependencies': is_app ? self.dependencies_recursion: self.dependencies,
'direct_dependent_settings': {
'include_dirs': is_app ? [] : self.include_dirs,
},
'sources': sources,
}
]
};
return gypi;
}
gen() {
if (!this._gypi) {
this.gen_before();
var os = this.host.os;
if ( os == 'ios' ) {
this._gypi = this.gen_ios_gypi();
} else if ( os == 'android' ) {
this._gypi = this.gen_android_gypi();
} else {
throw new Error('Not support');
}
}
return this._gypi;
}
}
export default class FtrExport {
readonly source: string;
readonly output: string;
readonly proj_out: string;
readonly os: string;
readonly bundle_resources: string[];
readonly outputs: Dict<Package> = {};
private m_project_name = 'app';
constructor(source: string, os: string) {
var self = this;
this.source = resolveLocal(source);
this.output = resolveLocal(source, 'out');
this.proj_out = resolveLocal(source, 'Project', os);
this.os = os;
function copy_libs(source: string) {
var [source, symlink] = source.split(/\s+/);
var libs = self.output + '/libs/';
if (symlink) {
source = libs + source;
fs.mkdirpSync(path.dirname(source));
if ( !fs.existsSync(source) ) {
fs.symlinkSync(symlink, source);
}
return '';
} else {
var target = libs + path.basename(source);
fs.copySync(source, target, { replace: false });
return path.relative(self.output, target);
}
}
// copy bundle resources and includes and librarys
this.bundle_resources = paths.bundle_resources.map(copy_libs);
if (paths.librarys[os])
paths.librarys[os].forEach(copy_libs);
paths.includes.forEach(copy_libs);
var proj_keys = this.source + '/proj.keys';
util.assert(fs.existsSync(proj_keys), `Export source does not exist ,${proj_keys}`);
fs.mkdirpSync(this.output);
fs.mkdirpSync(this.output + '/public');
fs.mkdirpSync(this.proj_out);
}
solve(pathname: string, is_app?: boolean, hasFullname?: boolean): Package | null {
var self = this;
var source_path = resolveLocal(pathname);
// ignore network pkg
if ( /^https?:\/\//i.test(source_path) ) {
console.warn(`ignore extern network Dependencies pkg`);
return null;
}
var json: PkgJson | null = null;
var __ = ()=>{
if (!json) {
json = parse_json_file(source_path + '/package.json') as PkgJson;
}
return json;
};
var outputName = hasFullname ? __().name + '@' + __().version: path.basename(source_path);
var pkg = self.outputs[outputName];
if ( !pkg ) {
pkg = new Package(self, source_path, outputName, __(), is_app);
pkg.initialize();
}
return pkg;
}
private gen_project_file(project_name: string) {
var self = this;
var gyp_exec = __dirname + (isWindows ? '/gyp/gyp.bat' : '/gyp/gyp');
var os = self.os;
var source = self.source;
var out = self.output;
var project = 'make';
var project_path: string[];
var proj_out = self.proj_out;
if ( os == 'ios' ) {
project = 'xcode';
project_path = [ `${proj_out}/${project_name}.xcodeproj` ];
} else if ( os == 'android' ) {
project = 'cmake-linux';
project_path = [
`${out}/android/${project_name}/out/Release/CMakeLists.txt`,
`${out}/android/${project_name}/out/Debug/CMakeLists.txt`,
];
proj_out = path.relative(source, `${out}/android/${project_name}`);
} else {
throw `Not Supported "${os}" export`;
}
// write _var.gypi
var include_gypi = ' -Iout/_var.gypi';
var var_gyp = { variables: { OS: os == 'ios' ? 'mac': os, os: os, project: project, DEPTH: source, } };
fs.writeFileSync(source + '/out/_var.gypi', JSON.stringify(var_gyp, null, 2));
// console.log('paths.includes_gypi', source, paths.includes_gypi);
paths.includes_gypi.forEach(function(str) {
include_gypi += ' -I' + path.relative(source, str);
});
// console.log('paths.includes_gypi', paths.includes_gypi);
var shell = `\
GYP_GENERATORS=${project} ${gyp_exec} \
-f ${project} \
--generator-output="${proj_out}" \
-Goutput_dir="${path.relative(source, out)}" \
-Gstandalone ${include_gypi} \
${project_name}.gyp \
--depth=. \
`;
var buf = child_process.execSync(shell);
if ( buf.length ) {
console.log(buf.toString());
}
return project_path;
}
private export_result() {
var self = this;
// write gyp
var source = self.source;
var includes = [];
for ( var i in self.outputs ) {
var pkg = self.outputs[i];
if ( !pkg.is_app ) { // node_modules
fs.writeFileSync( pkg.gypi_path, JSON.stringify(pkg.gen(), null, 2));
}
}
for ( var i in self.outputs ) {
var pkg = self.outputs[i];
if ( pkg.is_app ) {
fs.writeFileSync( pkg.gypi_path, JSON.stringify(pkg.gen(), null, 2));
includes.push(...pkg.includes, pkg.gypi_path);
}
}
includes = filter_repeat(includes).map(function(pathname) {
return path.relative(source, pathname);
});
var ftr_gyp = paths.ftr_gyp;
var gyp =
{
'variables': {
'libftr': [ ftr_gyp ? path.relative(source, ftr_gyp) + ':libftr': 'libftr' ],
},
'includes': includes,
};
var project_name = self.m_project_name;
var gyp_file = source + '/' + project_name +'.gyp';
// write gyp file
fs.writeFileSync( gyp_file, JSON.stringify(gyp, null, 2) );
var out = self.gen_project_file(project_name); // gen target project
try {
if (process.platform == 'darwin') {
child_process.execSync('open ' + out[0]); // open project
} else {
child_process.execSync('xdg-open ' + out[0]); // open project
}
} catch (e) {
//
}
fs.removerSync(gyp_file); // write gyp file
console.log(`export ${self.os} complete`);
}
private write_cmake_depe_to_android_build_gradle(pkg: Package, cmake: string, add: boolean) {
var self = this;
var build_gradle = `${self.proj_out}/${pkg.outputName}/build.gradle`;
var str = fs.readFileSync(build_gradle).toString('utf8');
str = str.replace(/^.*android\.externalNativeBuild\.cmake\.path\s*=\s*("|')[^"']*("|').*$/mg, '');
cmake = path.relative(`${self.proj_out}/${pkg.outputName}`, cmake);
cmake = `android.externalNativeBuild.cmake.path = '${cmake}'`;
if ( add ) {
str += cmake;
}
fs.writeFileSync(build_gradle, str);
}
private export_result_android() {
var self = this;
// write gyp
var output = self.output;
var proj_out = self.proj_out;
var settings_gradle = [];
var use_ndk = false;
var source = self.source;
var str: string;
for ( var i in self.outputs ) {
var pkg = self.outputs[i];
if ( !pkg.is_app ) { // node_modules
fs.writeFileSync( pkg.gypi_path, JSON.stringify(pkg.gen(), null, 2));
} else {
settings_gradle.push("':" + i + "'");
}
}
// gen gyp and native cmake
// android 每个项目需单独创建`gyp`并生成`.cmake`
for ( var i in self.outputs ) {
var pkg = self.outputs[i];
if ( pkg.is_app ) {
fs.writeFileSync( pkg.gypi_path, JSON.stringify(pkg.gen(), null, 2));
// console.log(pkg.name, pkg.native)
if ( pkg.native ) {
// android并不完全依赖`gyp`,只需针对native项目生成.cmake文件
use_ndk = true;
var includes = pkg.includes.concat(pkg.gypi_path).map(function(pathname) {
return path.relative(source, pathname);
});
var ftr_gyp = paths.ftr_gyp;
var gyp =
{
'variables': {
'libftr': [ ftr_gyp ? path.relative(source, ftr_gyp) + ':libftr': 'libftr' ],
},
'includes': includes,
};
var gyp_file = source + '/' + pkg.outputName +'.gyp';
// write gyp file
fs.writeFileSync( gyp_file, JSON.stringify(gyp, null, 2) );
// gen cmake
var out = self.gen_project_file(pkg.outputName); // gen target project
fs.removerSync(gyp_file); // write gyp file
//对于android这两个属性会影响输出库.so的默认路径,导致无法捆绑.so库文件,所以从文件中删除它
//set_target_properties(examples PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${builddir}/pkg.${TOOLSET}")
//set_source_files_properties(${builddir}/pkg.${TOOLSET}/pkgexamples.so PROPERTIES GENERATED "TRUE")
var reg0 = /^set_target_properties\([^ ]+ PROPERTIES LIBRARY_OUTPUT_DIRECTORY [^\)]+\)/mg;
var reg1 = /^set_source_files_properties\([^ ]+ PROPERTIES GENERATED "TRUE"\)/mg;
out.forEach(function(cmake) {
str = fs.readFileSync(cmake).toString('utf8');
str = str.replace(reg0, '').replace(reg1, '');
fs.writeFileSync(cmake, str);
});
// write CMakeLists.txt path
self.write_cmake_depe_to_android_build_gradle(pkg, out[0], true);
} else {
self.write_cmake_depe_to_android_build_gradle(pkg, '', false);
}
// copy pkgrary bundle resources to android assets directory
var android_assets = `${proj_out}/${pkg.outputName}/src/main/assets`;
pkg.bundle_resources.forEach(function(res) {
var basename = path.basename(res);
var source = path.relative(android_assets, output + '/' + res);
if (!fs.existsSync(output + '/' + res))
return;
var target = `${android_assets}/${basename}`;
try {
// if ( fs.existsSync(target) )
fs.unlinkSync(target);
} catch(e) {}
fs.symlinkSync(source, target);
});
}
}
// write settings.gradle
fs.writeFileSync(proj_out + '/settings.gradle', 'include ' + settings_gradle.join(','));
// set useDeprecatedNdk from gradle.properties
str = fs.readFileSync(proj_out + '/gradle.properties').toString('utf8');
str = str.replace(/useDeprecatedNdk\s*=\s*(false|true)/, function(){
return `useDeprecatedNdk=${use_ndk}`
});
fs.writeFileSync(proj_out + '/gradle.properties', str);
try {
if (process.platform == 'darwin') {
// open project
if (fs.existsSync('/Applications/Android Studio.app')) { // check is install 'Android Studio'
child_process.execSync('open -a "/Applications/Android Studio.app" Project/android');
} else {
child_process.execSync('open Project/android'); // open project
}
} else {
child_process.exec('xdg-open Project/android'); // open project
setTimeout(e=>process.exit(0),1e3); // force exit
}
} catch (e) {
//
}
console.log(`export ${self.os} complete`);
}
private exists(name: string) {
return fs.existsSync(this.output + '/install/' + name) || fs.existsSync(this.output + '/skip_install/' + name)
}
async export() {
var self = this;
var os = this.os;
var keys_path = self.source + '/proj.keys';
util.assert(
os == 'android' ||
os == 'ios', `Do not support ${os} os export`);
util.assert(fs.existsSync(keys_path), 'Proj.keys file not found');
var proj = keys.parseFile( keys_path );
var apps = [];
for (var key in proj) {
if ( key == '@projectName' ) {
this.m_project_name = proj['@projectName'];
} else if (key == '@apps') {
for (var app in proj['@apps']) {
apps.push(app);
}
}
}
// build apps
for (var app of apps) {
if ( !self.exists(app) )
await (new FtrBuild(this.source, this.output).build());
}
// export node_modules
var node_modules = self.source + '/node_modules';
if ( fs.existsSync(node_modules) && fs.statSync(node_modules).isDirectory() ) {
fs.listSync(node_modules).forEach(function(stat) {
var source = node_modules + '/' + stat.name;
if ( stat.isDirectory() && fs.existsSync(source + '/package.json') ) {
self.solve(source, false);
}
});
}
// export apps
for (var app of apps) {
util.assert(self.exists(app), 'Installation directory not found');
self.solve(this.source + '/' + app, true);
}
if ( os == 'android' ) {
self.export_result_android();
} else {
self.export_result();
}
}
} | the_stack |
export class DomEvents {
private handlers = new Map<{ removeEventListener: Function }, { [key: string]: Function[] }>();
constructor(private root: HTMLElement) {
}
public on(event: string, selector: string, handler: (UIEvent, target?: Element, root?: Element) => any, root?);
public on(event: string, handler: (UIEvent, target?: Element, root?: Element) => any, root?);
public on(...args: any[]) {
const event = args.shift();
const selector = typeof args[0] === "string" ? args.shift() : undefined;
const handler = typeof args[0] === "function" ? args.shift() : () => {
};
const root = args.shift();
const eventHolder = root || this.root;
if (!this.handlers.has(eventHolder)) {
this.handlers.set(eventHolder, {});
}
if (!this.handlers.get(eventHolder)[event]) {
this.handlers.get(eventHolder)[event] = [];
}
const evListener = (ev: UIEvent) => {
let target;
if (selector) {
const selected = Array.from(this.root.querySelectorAll(selector));
target = ev.target as HTMLElement;
while (target) {
if (selected.find(el => el === target)) {
break;
}
target = target.parentNode;
}
if (!target) {
return;
}
}
const handlerOutput = handler(ev, target || ev.target, this.root);
if (handlerOutput === false) {
return false;
}
return false;
};
eventHolder.addEventListener(event, evListener);
this.handlers.get(eventHolder)[event].push(evListener);
return function off() {
eventHolder.removeEventListener(event, evListener);
}
}
public keyup() {
}
public adaptedDrag(selector: string,
move?: (dx: number, dy: number, UIEvent, target?: Element, root?: Element) => any,
start?: (UIEvent, target?: Element, root?: Element) => any,
end?: (UIEvent, target?: Element, root?: Element) => any) {
let dragging = false;
let lastMove: MouseEvent;
let draggedEl: Element;
let moveEventCount = 0;
let mouseDownEv;
let threshold = 3;
let mouseOverListeners: EventListener[];
const onMouseDown = (ev, el) => {
dragging = true;
lastMove = ev;
draggedEl = el;
mouseDownEv = ev;
ev.preventDefault();
mouseOverListeners = this.detachHandlers("mouseover");
document.addEventListener("mousemove", moveHandler);
document.addEventListener("mouseup", upHandler);
return false;
};
const off = this.on("mousedown", selector, onMouseDown);
const moveHandler = (ev) => {
if (!dragging) {
return;
}
const dx = ev.screenX - lastMove.screenX;
const dy = ev.screenY - lastMove.screenY;
moveEventCount++;
if (moveEventCount === threshold && typeof start === "function") {
start(mouseDownEv, draggedEl, this.root);
}
if (moveEventCount >= threshold && typeof move === "function") {
move(dx, dy, ev, draggedEl, this.root);
}
};
const upHandler = (ev) => {
if (moveEventCount >= threshold) {
if (dragging) {
if (typeof end === "function") {
end(ev, draggedEl, this.root)
}
}
const parentNode = draggedEl.parentNode;
const clickCancellation = (ev) => {
ev.stopPropagation();
parentNode.removeEventListener("click", clickCancellation, true);
};
parentNode.addEventListener("click", clickCancellation, true);
}
dragging = false;
draggedEl = undefined;
lastMove = undefined;
moveEventCount = 0;
document.removeEventListener("mouseup", upHandler);
document.removeEventListener("mousemove", moveHandler);
for (let i in mouseOverListeners) {
this.root.addEventListener("mouseover", mouseOverListeners[i]);
this.handlers.get(this.root)["mouseover"] = [];
this.handlers.get(this.root)["mouseover"].push(mouseOverListeners[i]);
}
};
return off;
}
public drag(selector,
move?: (dx: number, dy: number, UIEvent, target?: Element, root?: Element) => any,
start?: (UIEvent, target?: Element, root?: Element) => any,
end?: (UIEvent, target?: Element, root?: Element) => any) {
let dragging = false;
let lastMove: MouseEvent;
let draggedEl: Element;
let moveEventCount = 0;
let mouseDownEv;
let threshold = 3;
let mouseOverListeners: EventListener[];
const onMouseDown = (ev, el, root) => {
dragging = true;
lastMove = ev;
draggedEl = el;
mouseDownEv = ev;
ev.preventDefault();
mouseOverListeners = this.detachHandlers("mouseover");
document.addEventListener("mousemove", moveHandler);
document.addEventListener("mouseup", upHandler);
return false;
};
const off = this.on("mousedown", selector, onMouseDown);
const moveHandler = (ev) => {
if (!dragging) {
return;
}
const dx = ev.screenX - lastMove.screenX;
const dy = ev.screenY - lastMove.screenY;
moveEventCount++;
if (moveEventCount === threshold && typeof start === "function") {
start(mouseDownEv, draggedEl, this.root);
}
if (moveEventCount >= threshold && typeof move === "function") {
move(dx, dy, ev, draggedEl, this.root);
}
};
const upHandler = (ev) => {
if (moveEventCount >= threshold) {
if (dragging) {
if (typeof end === "function") {
end(ev, draggedEl, this.root)
}
}
// When releasing the mouse button, if it happens over the same element that we initially had
// the mouseDown event, it will trigger a click event. We want to stop that, so we intercept
// it by capturing click top-down and stopping its propagation.
// However, if the mouseUp didn't happen above the starting element, it wouldn't trigger a click,
// but it would intercept the next (unrelated) click event unless we prevent interception in the
// first place by checking if we released above the starting element.
if (draggedEl.contains(ev.target)) {
const parentNode = draggedEl.parentNode;
const clickCancellation = (ev) => {
ev.stopPropagation();
parentNode.removeEventListener("click", clickCancellation, true);
};
parentNode.addEventListener("click", clickCancellation, true);
}
}
dragging = false;
draggedEl = undefined;
lastMove = undefined;
moveEventCount = 0;
document.removeEventListener("mouseup", upHandler);
document.removeEventListener("mousemove", moveHandler);
for (let i in mouseOverListeners) {
this.root.addEventListener("mouseover", mouseOverListeners[i]);
this.handlers.get(this.root)["mouseover"] = [];
this.handlers.get(this.root)["mouseover"].push(mouseOverListeners[i]);
}
};
return off;
}
public hover(element,
hover: (UIEvent, target?: HTMLElement, root?: HTMLElement) => any = () => {
},
enter: (UIEvent, target?: HTMLElement, root?: HTMLElement) => any = () => {
},
leave: (UIEvent, target?: HTMLElement, root?: HTMLElement) => any = () => {
}) {
let hovering = false;
element.addEventListener("mouseenter", (ev) => {
hovering = true;
enter(ev, element, this.root);
});
element.addEventListener("mouseleave", (ev) => {
hovering = false;
leave(ev, element, this.root);
});
element.addEventListener("mousemove", (ev) => {
if (!hovering) {
return;
}
hover(ev, element, this.root);
});
}
public detachHandlers(evName: string, root?): EventListener[] {
root = root || this.root;
let eventListeners: EventListener[] = [];
this.handlers.forEach((handlers: { [event: string]: EventListener[] }, listenerRoot: Element) => {
if (listenerRoot.id !== root.id || listenerRoot !== root) {
return;
}
for (let eventName in handlers) {
if (eventName !== evName) {
continue;
}
handlers[eventName].forEach((handler) => {
eventListeners.push(handler);
listenerRoot.removeEventListener(eventName, handler);
});
}
});
delete this.handlers.get(this.root)[evName];
return eventListeners;
}
public detachAll() {
this.handlers.forEach((handlers: { [event: string]: EventListener[] }, listenerRoot: Element) => {
for (let eventName in handlers) {
handlers[eventName].forEach(handler => listenerRoot.removeEventListener(eventName, handler));
}
});
this.handlers.clear();
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/customersMappers";
import * as Parameters from "../models/parameters";
import { BillingManagementClientContext } from "../billingManagementClientContext";
/** Class representing a Customers. */
export class Customers {
private readonly client: BillingManagementClientContext;
/**
* Create a Customers.
* @param {BillingManagementClientContext} client Reference to the service client.
*/
constructor(client: BillingManagementClientContext) {
this.client = client;
}
/**
* Lists the customers that are billed to a billing profile. The operation is supported only for
* billing accounts with agreement type Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param [options] The optional parameters
* @returns Promise<Models.CustomersListByBillingProfileResponse>
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: Models.CustomersListByBillingProfileOptionalParams): Promise<Models.CustomersListByBillingProfileResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options: Models.CustomersListByBillingProfileOptionalParams, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: Models.CustomersListByBillingProfileOptionalParams | msRest.ServiceCallback<Models.CustomerListResult>, callback?: msRest.ServiceCallback<Models.CustomerListResult>): Promise<Models.CustomersListByBillingProfileResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
options
},
listByBillingProfileOperationSpec,
callback) as Promise<Models.CustomersListByBillingProfileResponse>;
}
/**
* Lists the customers that are billed to a billing account. The operation is supported only for
* billing accounts with agreement type Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param [options] The optional parameters
* @returns Promise<Models.CustomersListByBillingAccountResponse>
*/
listByBillingAccount(billingAccountName: string, options?: Models.CustomersListByBillingAccountOptionalParams): Promise<Models.CustomersListByBillingAccountResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccount(billingAccountName: string, options: Models.CustomersListByBillingAccountOptionalParams, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
listByBillingAccount(billingAccountName: string, options?: Models.CustomersListByBillingAccountOptionalParams | msRest.ServiceCallback<Models.CustomerListResult>, callback?: msRest.ServiceCallback<Models.CustomerListResult>): Promise<Models.CustomersListByBillingAccountResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
options
},
listByBillingAccountOperationSpec,
callback) as Promise<Models.CustomersListByBillingAccountResponse>;
}
/**
* Gets a customer by its ID. The operation is supported only for billing accounts with agreement
* type Microsoft Partner Agreement.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param [options] The optional parameters
* @returns Promise<Models.CustomersGetResponse>
*/
get(billingAccountName: string, customerName: string, options?: Models.CustomersGetOptionalParams): Promise<Models.CustomersGetResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param callback The callback
*/
get(billingAccountName: string, customerName: string, callback: msRest.ServiceCallback<Models.Customer>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param customerName The ID that uniquely identifies a customer.
* @param options The optional parameters
* @param callback The callback
*/
get(billingAccountName: string, customerName: string, options: Models.CustomersGetOptionalParams, callback: msRest.ServiceCallback<Models.Customer>): void;
get(billingAccountName: string, customerName: string, options?: Models.CustomersGetOptionalParams | msRest.ServiceCallback<Models.Customer>, callback?: msRest.ServiceCallback<Models.Customer>): Promise<Models.CustomersGetResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
customerName,
options
},
getOperationSpec,
callback) as Promise<Models.CustomersGetResponse>;
}
/**
* Lists the customers that are billed to a billing profile. The operation is supported only for
* billing accounts with agreement type Microsoft Partner Agreement.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.CustomersListByBillingProfileNextResponse>
*/
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CustomersListByBillingProfileNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CustomerListResult>, callback?: msRest.ServiceCallback<Models.CustomerListResult>): Promise<Models.CustomersListByBillingProfileNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingProfileNextOperationSpec,
callback) as Promise<Models.CustomersListByBillingProfileNextResponse>;
}
/**
* Lists the customers that are billed to a billing account. The operation is supported only for
* billing accounts with agreement type Microsoft Partner Agreement.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.CustomersListByBillingAccountNextResponse>
*/
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CustomersListByBillingAccountNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CustomerListResult>): void;
listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CustomerListResult>, callback?: msRest.ServiceCallback<Models.CustomerListResult>): Promise<Models.CustomersListByBillingAccountNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingAccountNextOperationSpec,
callback) as Promise<Models.CustomersListByBillingAccountNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByBillingProfileOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/customers",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.search,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CustomerListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingAccountOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers",
urlParameters: [
Parameters.billingAccountName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.search,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CustomerListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}",
urlParameters: [
Parameters.billingAccountName,
Parameters.customerName
],
queryParameters: [
Parameters.apiVersion0,
Parameters.expand
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Customer
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingProfileNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CustomerListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingAccountNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CustomerListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { TextCheckerElement } from "./text-checker-element";
import { TextCheckerCard, TextCheckerPopupElement, TextCheckerPopupElementArgs } from "./text-checker-popup-element";
import type { TextlintMessage, TextlintResult } from "@textlint/types";
import type { TextCheckerElementRectItem } from "./text-checker-store";
import pDebounce from "p-debounce";
import { debug } from "./util/logger";
const createCompositionHandler = () => {
let onComposition = false;
return {
onComposition,
handleEvent: (event: Event) => {
if (event.type === "compositionend") {
onComposition = false;
} else if (event.type === "compositionstart") {
onComposition = true;
}
}
};
};
/**
* Lint Server API
*/
export type LintEngineAPI = {
// Lint Text
lintText({ text }: { text: string }): Promise<TextlintResult[]>;
// Fix Text with linted results
fixText({ text, messages }: { text: string; messages: TextlintMessage[] }): Promise<{ output: string }>;
// ignore the text
ignoreText({ text, message }: { text: string; message: TextlintMessage }): Promise<boolean>;
// merge config and update
mergeConfig?({ textlintrc }: { textlintrc: string }): Promise<void>;
};
export type AttachTextAreaParams = {
/**
* target textarea element
*/
textAreaElement: HTMLTextAreaElement;
/**
* linting debounce timeout millisecond
* default: 200ms
*/
lintingDebounceMs: number;
// user should implement LintEngineAPI and pass it
lintEngine: LintEngineAPI;
};
const createTextCheckerPopupElement = (args: TextCheckerPopupElementArgs) => {
const textCheckerPopup = new TextCheckerPopupElement(args);
document.body.append(textCheckerPopup);
return textCheckerPopup;
};
/**
* Return true if the element in viewport
* @param element
*/
function isVisibleInViewport(element: HTMLElement): boolean {
const style = window.getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden") {
return false;
}
const rect = element.getBoundingClientRect();
if (rect.height === 0 || rect.width === 0) {
return false;
}
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
/**
* Dismiss all popup
*
* - Update text(includes fixed)
* - Scroll textarea/Scroll window
* - Focus on textarea
* - Click out of textarea/popup
* - popup → textarea → other → dismiss
* - textarea → popup → other → dismiss
*/
/**
* Dismiss a single popup(500ms delay)
*
* - Leave from popup
* - Leave from RectItem
* - Focus on textarea
*
*/
/**
* Show popup condition
* - onUpdate
*/
/**
* Attach text-checker component to `<textarea>` element
*/
export const attachToTextArea = ({
textAreaElement,
lintingDebounceMs,
lintEngine
}: AttachTextAreaParams): (() => void) => {
if (!textAreaElement) {
debug("Can not attach. No textarea", textAreaElement);
return () => {};
}
if (textAreaElement.readOnly) {
debug("Can not attach textarea that is readonly", textAreaElement);
return () => {};
}
if (textAreaElement.dataset.attachedTextCheckerElement === "true") {
debug("Can not attach textarea that is already attached", textAreaElement);
return () => {};
}
const dismissCards = () => {
debug("dismissCards", {
textCheckerPopup: textCheckerPopup.isHovering,
textChecker: textChecker.isHovering,
textCheckerF: textChecker.isFocus
});
if (!textCheckerPopup.isHovering && !textChecker.isHovering && !textChecker.isFocus) {
textCheckerPopup.dismissCards();
textChecker.resetHoverState();
}
};
const textCheckerPopup = createTextCheckerPopupElement({
onLeave() {
dismissCards();
}
});
const textChecker = new TextCheckerElement({
targetElement: textAreaElement,
hoverPadding: 20,
onLeave() {
dismissCards();
}
});
textAreaElement.before(textChecker);
const compositionHandler = createCompositionHandler();
const update = pDebounce(async () => {
if (!isVisibleInViewport(textAreaElement)) {
return;
}
// stop lint on IME composition
if (compositionHandler.onComposition) {
return;
}
// dismiss card before update annotations
// dismissCards();
const text = textAreaElement.value;
const results = await lintEngine.lintText({
text
});
debug("lint results", results);
const updateText = async (newText: string, card: TextCheckerCard) => {
const currentText = textAreaElement.value;
if (currentText === text && currentText !== newText) {
textAreaElement.value = newText;
await update();
textCheckerPopup.dismissCard(card);
}
};
const annotations = results.flatMap((result) => {
return result.messages.map((message) => {
const card: TextCheckerCard = {
id: message.ruleId + "::" + message.index,
message: message.message,
messageRuleId: message.ruleId,
fixable: Boolean(message.fix)
};
let dismissTimerId: null | any = null;
return {
id: `${message.ruleId}::${message.line}:${message.column}`,
start: message.index,
end: message.index + 1,
onMouseEnter: ({ rectItem }: { rectItem: TextCheckerElementRectItem }) => {
debug("annotation - onMouseEnter");
if (dismissTimerId) {
clearTimeout(dismissTimerId);
}
textCheckerPopup.updateCard({
card: card,
rect: {
top:
rectItem.boxBorderWidth +
rectItem.boxMarginTop +
rectItem.boxPaddingTop +
rectItem.boxAbsoluteY +
rectItem.top +
rectItem.height,
left: rectItem.boxAbsoluteX + rectItem.left,
width: rectItem.width
},
handlers: {
async onFixText() {
const fixResults = await lintEngine.fixText({
text,
messages: [message]
});
await updateText(fixResults.output, card);
},
async onFixAll() {
const fixResults = await lintEngine.fixText({
text,
messages: result.messages
});
await updateText(fixResults.output, card);
},
async onFixRule() {
const messages = result.messages.filter(
(aMessage) => aMessage.ruleId === message.ruleId
);
const fixResults = await lintEngine.fixText({
text,
messages
});
await updateText(fixResults.output, card);
},
async onIgnore() {
await lintEngine.ignoreText({
text,
message
});
await update();
},
onSeeDocument() {
const id = message.ruleId.includes("/")
? message.ruleId.split("/")[1]
: message.ruleId;
window.open(
`https://github.com/search?q=textlint ${encodeURIComponent(id)}`,
"_blank",
"noopener"
);
}
}
});
},
async onMouseLeave({ rectItem }: { rectItem: TextCheckerElementRectItem }) {
try {
debug("annotation - onMouseLeave");
dismissTimerId = setTimeout(() => {
const isHover = textChecker.isHoverRectItem(rectItem);
debug("dismiss", {
textCheckerPopup: textCheckerPopup.isHovering,
isRectElementHover: isHover
});
if (textCheckerPopup.isHovering || isHover) {
return;
}
textCheckerPopup.dismissCard(card);
}, 500);
} catch (error) {
debug("Abort dismiss popup", error);
}
}
};
});
});
debug("annotations", annotations);
textChecker.updateAnnotations(annotations);
}, lintingDebounceMs);
// Events
// when resize element, update annotation
const resizeObserver = new ResizeObserver(() => {
debug("ResizeObserver do update");
textCheckerPopup.dismissCards();
textChecker.resetAnnotations();
update();
});
resizeObserver.observe(textAreaElement);
// when scroll window, update annotation
const onScroll = () => {
textCheckerPopup.dismissCards();
textChecker.resetAnnotations();
update();
};
const onFocus = () => {
textCheckerPopup.dismissCards();
update();
};
const onBlur = (event: FocusEvent) => {
// does not dismiss on click popup items(require tabindex)
if (event.relatedTarget === textChecker || event.relatedTarget === textCheckerPopup) {
return;
}
textCheckerPopup.dismissCards();
};
textAreaElement.addEventListener("compositionstart", compositionHandler);
textAreaElement.addEventListener("compositionend", compositionHandler);
textAreaElement.addEventListener("input", update);
textAreaElement.addEventListener("focus", onFocus);
textAreaElement.addEventListener("blur", onBlur);
textAreaElement.addEventListener("focusout", dismissCards);
window.addEventListener("scroll", onScroll);
// when scroll the element, update annotation
textAreaElement.addEventListener("scroll", onScroll);
update();
return () => {
window.removeEventListener("scroll", onScroll);
textAreaElement.removeEventListener("scroll", onScroll);
textAreaElement.removeEventListener("compositionstart", compositionHandler);
textAreaElement.removeEventListener("compositionend", compositionHandler);
textAreaElement.removeEventListener("input", update);
textAreaElement.removeEventListener("focus", onFocus);
textAreaElement.removeEventListener("blur", onBlur);
resizeObserver.disconnect();
};
}; | the_stack |
import * as I from '../lib/interfaces'
import 'mocha'
import assert from 'assert'
import {queryTypes} from '../lib/qrtypes'
import sel from '../lib/sel'
import {vCmp, vDec, V_EMPTY, vToRange} from '../lib/version'
import {bitHas} from '../lib/bit'
import {subResults} from '../lib/subvalues'
import {inspect} from 'util'
import {Console} from 'console'
const ins = (x: any) => inspect(x, {depth: null, colors: true})
global.console = new (Console as any)({
stdout: process.stdout,
stderr: process.stderr,
inspectOptions: {depth: null}
})
const assertThrows = async (block: () => Promise<void>, errType?: string) => {
try {
await block()
} catch (e) {
if (errType) assert.strictEqual(e.name, errType)
return
}
throw Error('Block did not throw')
}
type SimpleResult<Val = any> = {
results: Val,
versions: I.FullVersionRange,
}
const rangeContainsVersion = (range: I.VersionRange, v: I.Version) => vCmp(v, range.from) >= 0 && vCmp(v, range.to) <= 0
const rangeContainsRange = (r1: I.VersionRange, r2: I.VersionRange) => vCmp(r1.from, r2.from) <= 0 && vCmp(r1.to, r2.to) >= 0
const rangeContainsV = (range: I.VersionRange, v: I.Version | I.VersionRange) =>
v instanceof Uint8Array ? rangeContainsVersion(range, v) : rangeContainsRange(range, v)
const versionAtLeast = (v1: I.Version, v2: I.Version | I.VersionRange) =>
v2 instanceof Uint8Array ? v2 >= v1 : v2.from >= v1
const versionSatisfies = (v1: I.Version | I.VersionRange, v2: I.Version | I.VersionRange) =>
v1 instanceof Uint8Array ? versionAtLeast(v1, v2) : rangeContainsV(v1, v2)
const fullVersionSatisfies = (r1: I.FullVersion | I.FullVersionRange, r2: I.FullVersion | I.FullVersionRange) => {
for (let i = 0; i < r1.length; i++) if (r1[i] != null) {
const rs = r2[i]
if (rs !== null && !versionSatisfies(r1[i]!, rs)) return false
}
return true
}
const assertEqualResults = (actual: SimpleResult, expected: SimpleResult, strictVersionCheck: boolean = false) => {
// console.log('ev', expected.versions, '\nav', actual.versions)
// assert.deepStrictEqual(actual.versions, expected.versions)
if (strictVersionCheck) assert.deepStrictEqual(actual.versions, expected.versions)
else assert(fullVersionSatisfies(expected.versions, actual.versions))
// console.log('ar', actual.results)
// console.log('er', expected.results)
assert.deepStrictEqual(actual.results, expected.results)
}
const id = <T>(x: T) => x
const flatMap = <X, Y>(arr: X[], f: (a: X) => Y[]): Y[] => ([] as Y[]).concat.apply([], arr.map(f))
const filter = <K, V>(orig: Map<K, V>, keep: Set<K>) => {
const result = new Map<K, V>()
for (const k of keep) {
const v = orig.get(k)
if (v !== undefined) result.set(k, v)
}
return result
}
const toKVMap = <T>(qtype: I.QueryType, keys: Set<I.Key>, m: Map<I.Key, T> | [I.Key, T][][]): Map<I.Key, T> => (
!(m instanceof Map)
? new Map(flatMap(m, id))
: qtype === I.QueryType.KV ? m
: filter(m, keys)
)
// let nextId = 1
// Fetch using fetch() and through subscribe.
const eachFetchMethod = async <Val>(store: I.Store<Val>, query: I.Query, minVersion: I.FullVersion, keys: Set<I.Key>): Promise<SimpleResult<Val>> => {
const qtype = query.type
assert(bitHas(store.storeInfo.capabilities.queryTypes, qtype),
`${qtype} queries not supported by store`)
// let id = nextId++
const results: SimpleResult[] = await Promise.all([
(async () => {
let {results, versions, bakedQuery} = await store.fetch(query, {minVersion})
if (bakedQuery) {
const r2 = await store.fetch(bakedQuery)
assert.deepStrictEqual(r2.results, results)
// TODO: And versions?
}
// console.log(id, 'fetch finished', versions)
return {results: toKVMap(query.type, keys, results), versions}
})(),
// new Promise<SimpleResult>((resolve, reject) => {
(async () => {
const rtype = queryTypes[qtype].resultType
const sub = store.subscribe(query, {supportedTypes: new Set()})
outer: for await (const {results, versions} of subResults(rtype.type!, sub)) {
for (let i = 0; i < minVersion.length; i++) {
const mv = minVersion[i]
if (mv && vCmp(versions[i]!.to, mv) < 0) {
console.log(id, 'waitting...', mv, versions)
continue outer
}
}
// console.log(id, 'sub finished')
// console.log('ok')
// Ok we're done.
sub.return()
// console.log(query.type, 'r', versions)
return {results: toKVMap(query.type, keys, results), versions}
}
throw Error('Subscription closed prematurely')
})()
])
// console.log('r fetch', query.type, results[0])
// console.log('r sub', query.type, results[1])
// assertEqualResults(results[0], results[1], false)
while (results.length > 1) {
const x = results.shift()!
// console.log('qtype', qtype, 'x', x, results[0])
assertEqualResults(x, results[0], false)
}
return results[0]
}
async function runAllKVQueries<T>(
store: I.Store<any>,
keys: I.KVQuery,
fn: (q: I.Query, keys: I.KVQuery) => Promise<T>,
allowRange: boolean
// checkEq: (a: T, b: T) => void
): Promise<T[]> {
assert(bitHas(store.storeInfo.capabilities.queryTypes, I.QueryType.KV), 'Store does not support KV queries')
// TODO: Add regular ranges here as well.
// const promises = (['range'] as I.QueryType[])
const types: I.QueryType[] = [I.QueryType.KV, I.QueryType.AllKV, I.QueryType.StaticRange]
// const types: I.QueryType[] = []
if (allowRange) types.push(I.QueryType.Range)
const promises = types.filter(qtype => bitHas(store.storeInfo.capabilities.queryTypes, qtype))
.map(qtype => {
const query = qtype === I.QueryType.StaticRange || qtype === I.QueryType.Range
? Array.from(keys).map(k => ({
low: sel(k, false),
high: sel(k, true),
}))
: qtype === I.QueryType.KV ? keys
: true
return fn({type: qtype, q: query} as I.Query, keys)
}) //.filter(x => x != null)
const vals = await Promise.all(promises)
// console.log('vals', ins(vals))
return vals
}
async function assertKVResults<Val>(
store: I.Store<Val>,
keys: I.Key[],
minVersion: I.FullVersion,
expectedVals: [I.Key, Val][],
expectedVers?: I.FullVersion | I.FullVersionRange) {
const results = await runAllKVQueries<SimpleResult<Val>>(
store,
new Set(keys),
(query, keys) => eachFetchMethod(store, query, minVersion, keys),
true
)
// console.log('expected', ins(expectedVals), ins(expectedVers))
// console.log('actual', ins(result))
results.forEach(r => {
assert.deepStrictEqual(r.results, new Map(expectedVals))
// console.log('rv', r.versions)
// console.log('ev', expectedVers)
// if (expectedVers) console.log('satisfies', fullVersionSatisfies(expectedVers, r.versions))
if (expectedVers != null) assert(fullVersionSatisfies(expectedVers, r.versions), 'Version does not match')
})
// TODO: Then take the queryRun and pass it back into the store & check we
// get the same thing.
}
const getOpsBoth = async (store: I.Store<any>, keys: I.Key[], versions: I.FullVersionRange, opts: I.GetOpsOptions = {}) => {
const vals = await runAllKVQueries<I.GetOpsResult<any>>(
store,
new Set(keys),
async (query, keys) => {
let results = await store.getOps(query, versions, opts)
if (query.type === I.QueryType.AllKV) {
results.ops.filter(txn => {
const txn_ = queryTypes[I.QueryType.KV].adaptTxn(txn.txn, keys)
if (txn_ == null) return false
else {
txn.txn = txn_
return true
}
})
}
results.ops = results.ops.filter(op => {
op.txn = toKVMap(query.type, keys, op.txn as I.KVTxn<any> | I.RangeTxn<any>)
return op.txn.size > 0
})
return results
},
false
)
while (vals.length > 1) {
const x = vals.shift()!
assert.deepStrictEqual(x, vals[0])
}
return vals[0]
}
type SingleVersion<V> = {source: I.Source, version: V}
// Convert from a version object with exactly 1 entry to a [source, version] pair
function splitSingleVersions<V>(store: I.Store<any>, versions: (V | null)[]): SingleVersion<V> {
const sources = store.storeInfo.sources
// Only 1 version from the versions array should be non-null.
const idxArr = versions
.map((v, i) => v == null ? -1 : i)
.filter(i => i >= 0)
assert.strictEqual(idxArr.length, 1)
const idx = idxArr[0]
return {
source: sources[idx],
version: versions[idx]!
}
}
// TODO: Consider replacing these with the equivalents in utils.
const ssTxn = <Val>(k: I.Key, v: Val): I.KVTxn<Val> => new Map([[k, {type:'set', data:v}]])
const setSingle = async <Val>(store: I.Store<Val>, key: I.Key, value: Val, versions: I.FullVersion = []): Promise<SingleVersion<I.Version>> => {
// if (typeof versions === 'function') [versions, callback] = [{}, versions]
const txn = ssTxn(key, value)
const vs = await store.mutate(I.ResultType.KV, txn, versions, {})
return splitSingleVersions(store, vs)
}
const delSingle = async (store: I.Store<any>, key: I.Key): Promise<SingleVersion<I.Version>> => {
// if (typeof versions === 'function') [versions, callback] = [{}, versions]
const txn = new Map([[key, {type:'rm'}]])
const vs = await store.mutate(I.ResultType.KV, txn)
return splitSingleVersions(store, vs)
}
type SingleValue<Val = any> = {source: I.Source, version: I.VersionRange, value: Val}
const getSingle = async <Val>(store: I.Store<Val>, key: I.Key, opts?: I.FetchOpts) => {
const r = await store.fetch({type:I.QueryType.KV, q:new Set([key])}, opts)
const results = r.results as Map<I.Key, Val>
assert(results.size <= 1)
// console.log('r', results.entries().next().value[1])
const vs = splitSingleVersions(store, r.versions)
const entry = results.entries().next().value
if (entry != null) assert.strictEqual(entry[0], key)
return {source: vs.source, version: vs.version, value: entry ? entry[1] : null}
}
const getVersionForKeys = async (store: I.Store<any>, _keys: I.Key[] | I.Key): Promise<SingleVersion<I.VersionRange>> => {
const keys = Array.isArray(_keys) ? new Set(_keys) : new Set([_keys])
const {versions} = await store.fetch({type:I.QueryType.KV, q:keys}, {noDocs:true})
return splitSingleVersions(store, versions)
}
const sparseSV = <V>(source: I.Source, store: I.Store<any>, val: V): (V | null)[] => {
const i = store.storeInfo.sources.indexOf(source)
if (i < 0) throw Error('Invalid source - source ' + source + ' not in storeinfo')
const result = []
result[i] = val
return result
}
interface Context extends Mocha.Context {
store: I.Store<any>
}
export default function runTests(createStore: () => Promise<I.Store<any>>, teardownStore?: (store: I.Store<any>) => void) {
describe('common tests', () => {
beforeEach(async function() {
const store = await createStore()
this.rawStore = store
this.store = store//easyapi(withkv(store))
})
afterEach(function() {
// TODO: And nuke all the contents.
this.store.close()
if (teardownStore) teardownStore(this.rawStore)
})
// Some simple sanity tests
it('returns nothing when running an empty query', async function() {
await assertKVResults(this.store, [], [], [])
})
it('returns nothing when fetching a nonexistant document', async function() {
await assertKVResults(this.store, ['doesnotexist'], [], [])
})
it('can store things and return them', async function() {
const txn = new Map([['a', {type:'set', data:'hi there'}]])
const vs = await (this.store as I.Store<any>).mutate(I.ResultType.KV, txn, [], {})
// The version we get back here should contain exactly 1 source with a
// single integer version.
assert.strictEqual(Object.keys(vs!).length, 1)
assert(Object.values(vs!)[0] instanceof Uint8Array)
await assertKVResults(this.store, ['a'], vs, [['a', 'hi there']], vs!)
})
it('allows you to delete a key', async function() {
const v1 = (await setSingle(this.store, 'a', 1)).version
const v2 = (await delSingle(this.store, 'a')).version
assert(vCmp(v2, v1) > 0)
const r = await getSingle(this.store, 'a', {minVersion: [v2]})
const expected: SingleValue = {source: r.source, version: {from: v2, to: v2}, value: null}
assert.deepStrictEqual(r, expected)
})
it('allows you to delete a nonexistant key', async function() {
const {version} = await delSingle(this.store, 'a')
const r = await getSingle(this.store, 'a', {minVersion: [version]})
assert.equal(r.value, null)
assert.deepStrictEqual(version, r.version.from)
assert.deepStrictEqual(version, r.version.to)
})
// This test relies on the full version semantics of statecraft's native stores.
it('returns acceptable version ranges for queries', async function() {
// Set in 3 different transactions so we get a document version range.
const {source, version: v1} = await setSingle(this.store, 'a', 1)
const v2 = (await setSingle(this.store, 'b', 2)).version
const v3 = (await setSingle(this.store, 'c', 3)).version
assert(vCmp(v1, v2) < 0 && vCmp(v2, v3) < 0)
await assertKVResults(this.store, ['a'], [v3], [['a', 1]], sparseSV(source, this.store, {from:v1, to:v3}))
})
it('makes conflicting edits to the same key collide', async function() {
// TODO: Make a parallel version of this function.
const {source, version} = await getVersionForKeys(this.store, 'a')
const v = version.to
assert(vCmp(v, new Uint8Array()) > 0, 'Empty version in fetch') // The version should be defined - normally zeros.
// Now set it. This should succeed...
await setSingle(this.store, 'a', 1, sparseSV(source, this.store, v))
await assertThrows(async () => {
await setSingle(this.store, 'a', 2, sparseSV(source, this.store, v))
}, 'WriteConflictError')
})
it('allows concurrent edits to different keys', async function() {
const {source, version} = await getVersionForKeys(this.store, ['a', 'b'])
const v = version.to
// TODO: Make a parallel variant of this function
await setSingle(this.store, 'a', 1, sparseSV(source, this.store, v))
await setSingle(this.store, 'b', 1, sparseSV(source, this.store, v))
})
it('supports opts.noDocs in fetch', async function() {
const v1 = (await setSingle(this.store, 'a', {some:'big object'})).version
const {value, version: v2} = await getSingle(this.store, 'a', {noDocs:true, minVersion: [v1]})
assert(value === true || value === 1, 'Store should not fetch document')
assert.deepStrictEqual(v1, v2.to)
})
it('supports conflicting read keys') // but NYI.
describe('object model', () => {
it('a document that was never created does not appear in a kv result set', async function() {
const store = (this as Context).store
if (!bitHas(store.storeInfo.capabilities.queryTypes, I.QueryType.KV)) this.skip()
const result = await store.fetch({type:I.QueryType.KV, q:new Set(['x'])})
assert(!result.results.has('x'))
})
it('a document with value null does not appear in a kv result set', async function() {
const store = (this as Context).store
if (!bitHas(store.storeInfo.capabilities.queryTypes, I.QueryType.KV)) this.skip()
await setSingle(store, 'x', 123)
await setSingle(store, 'x', null)
await setSingle(store, 'y', 321)
await delSingle(store, 'y')
const result = await store.fetch({type:I.QueryType.KV, q:new Set(['x', 'y'])})
assert.strictEqual(result.results.size, 0)
})
it('a document which was made null by an OT operation does not appear in kv results')
it('allows operations to be submitted against missing documents. Apply gets snapshot: null')
it('transforms correctly if two operations have identical create arguments')
it('allows two concurrent operations with the same create argument to mutually succeed')
it('ignores create arguments if the document exists')
it('transforms with different create parameters conflict')
})
describe('skv', () => {
it('supports subscribing to a range')
it('includes deleted documents in version information')
it('supports skip and limit') // ??? TODO
})
describe('getOps', () => {
beforeEach(async function() {
// Setting these in a series of operations so we have something to query over.
const {source, version: v1} = await setSingle(this.store, 'a', 1)
this.source = source
this.v1 = v1
this.v2 = (await setSingle(this.store, 'b', 2)).version
this.v3 = (await setSingle(this.store, 'a', 3)).version
this.v4 = (await setSingle(this.store, 'b', 4)).version
this.expectedOps = [
{versions:sparseSV(source, this.store, this.v1), txn:ssTxn('a', 1), meta:{}},
{versions:sparseSV(source, this.store, this.v2), txn:ssTxn('b', 2), meta:{}},
{versions:sparseSV(source, this.store, this.v3), txn:ssTxn('a', 3), meta:{}},
{versions:sparseSV(source, this.store, this.v4), txn:ssTxn('b', 4), meta:{}},
]
this.allVersions = sparseSV(source, this.store, {from: vDec(this.v1), to: this.v4})
})
const emptyOpsResult: I.GetOpsResult<any> = Object.freeze({ops: [], versions: []})
it('returns an empty list when no versions are requested', async function() {
const result = await getOpsBoth(this.store, ['a', 'b', 'c', 'd'], [])
assert.deepStrictEqual(result, emptyOpsResult)
})
it('returns an empty list for closed ranges', async function() {
const result = await getOpsBoth(this.store, ['a', 'b', 'c', 'd'], sparseSV(this.source, this.store, {from:this.v1, to:this.v1}))
// TODO: I'm not sure if this should return [from:v1, to:v1] or just [].
assert.deepStrictEqual(result, {ops:[], versions: [{from:this.v1, to:this.v1}]})
})
it('returns an empty list with the current version when the top of the range is unbounded', async function() {
const result = await getOpsBoth(this.store, ['a', 'b', 'c', 'd'], sparseSV(this.source, this.store, {from:this.v4, to:V_EMPTY}))
assert.deepStrictEqual(result, {ops:[], versions: [{from:this.v4, to:this.v4}]})
})
it('gets all ops when the top range is unbound', async function() {
const result = await getOpsBoth(this.store, ['a', 'b'], sparseSV(this.source, this.store, {from:vDec(this.v1), to:V_EMPTY}))
assert.deepStrictEqual(result.versions, this.allVersions)
assert.deepStrictEqual(result.ops, this.expectedOps)
})
it('gets all ops when the range is explicit', async function() {
const result = await getOpsBoth(this.store, ['a', 'b', 'c', 'd'], sparseSV(this.source, this.store, {from:vDec(this.v1), to:this.v4}))
assert.deepStrictEqual(result.versions, this.allVersions)
assert.deepStrictEqual(result.ops, this.expectedOps)
})
it('filters the operations based on the query', async function() {
const result = await getOpsBoth(this.store, ['a'], sparseSV(this.source, this.store, {from:vDec(this.v1), to:this.v4}))
assert.deepStrictEqual(result.versions, this.allVersions)
assert.deepStrictEqual(result.ops, [this.expectedOps[0], this.expectedOps[2]])
})
it('filters operations based on the supplied versions', async function() {
const result = await getOpsBoth(this.store, ['a', 'b'], sparseSV(this.source, this.store, {from:this.v1, to:this.v3}))
assert.deepStrictEqual(result.versions, sparseSV(this.source, this.store, {from: this.v1, to: this.v3}))
assert.deepStrictEqual(result.ops, [this.expectedOps[1], this.expectedOps[2]])
})
// TODO: How does the op store respond to operations which edit multiple keys?
})
describe('subscribe', () => {
beforeEach(async function() {
const {source, version: v1} = await setSingle(this.store, 'a', 1)
// console.log('v1', v1)
this.source = source
this.v1 = v1
})
it('allows you to subscribe from the current version, specified explicitly', async function() {
const sub = (this.store as I.Store<any>).subscribe({type: I.QueryType.KV, q: new Set(['a'])}, {fromVersion: sparseSV(this.source, this.store, this.v1)})
// The first message will be a catchup, which should be empty.
const {value: catchup} = await sub.next()
// console.log('cu', catchup, catchup.txns)
assert.deepStrictEqual(catchup.txns, [])
const v2 = (await setSingle(this.store, 'a', 2)).version
const {value: update} = await sub.next()
assert.deepStrictEqual(update.txns[0].txn, ssTxn('a', 2))
assert.deepStrictEqual(update.toVersion[this.store.storeInfo.sources.indexOf(this.source)], v2)
})
it('allows you to subscribe from the previous version, specified explicitly', async function() {
const v2 = (await setSingle(this.store, 'a', 2)).version
const sub = (this.store as I.Store<any>).subscribe({type: I.QueryType.KV, q: new Set(['a'])}, {fromVersion: sparseSV(this.source, this.store, this.v1)})
// The first message will be a catchup, which should bring us to v2.
const {value: catchup} = await sub.next()
// Depending on the store, this might return a replace operation.
if (catchup.replace) assert.deepStrictEqual(catchup.replace.with.get('a'), 2)
else assert.deepStrictEqual(catchup.txns[0].txn, ssTxn('a', 2))
const si = this.store.storeInfo.sources.indexOf(this.source)
assert.deepStrictEqual(catchup.toVersion[si], v2)
// And we should also be able to submit a subsequent op to get to v3.
const v3 = (await setSingle(this.store, 'a', 3)).version
const {value: update} = await sub.next()
assert.deepStrictEqual(update.txns[0].txn, ssTxn('a', 3))
assert.deepStrictEqual(update.toVersion[si], v3)
})
it('propogates a subscription close through to the backing store') // No idea how to test this here.
})
})
}
/*
describe('limits', () => {
// limits are advisory only. We'll check for conformance and if it fails
// we'll mark the test as skipped.
beforeEach(function(done) {
const txn = new Map([
['a', {type:'set', data:'a data'}],
['b', {type:'set', data:'b data'}],
['c', {type:'set', data:'c data'}],
['d', {type:'set', data:'d data'}],
])
this.store.mutate(txn, {}, {}, (err, vs) => done(err))
})
it('supports doc limits in fetch', function(done) {
eachAsync([1,2,3,4], (limit, _, done) => {
this.store.fetch('kv', ['a', 'b', 'c', 'd'], {limitDocs:limit}, (err, results) => {
if (err) throw err
// TODO: Check results.queryRun as well.
if (results.results.size !== limit) done(Error('Limit not respected'))
else done()
})
}, err => {
if (err && err.message === 'Limit not respected') return this.skip()
else done()
})
})
it('supports byte limits in fetch', function(done) {
this.store.fetch('kv', ['a', 'b', 'c', 'd'], {limitBytes: 1}, (err, results) => {
if (err) throw err
// TODO: also check results.queryRun
if (results.results.size !== 1) return this.skip()
done()
})
})
})
*/ | the_stack |
import { AnimationClip } from 'three';
import { Camera } from 'three';
import { EventDispatcher } from 'three';
import { Quaternion } from 'three';
import { Scene } from 'three';
import { Vector3 } from 'three';
/**
* Mapping of rotation action to axis
*/
export declare interface ActionAxes {
[CameraAction.Pan]: Axis;
[CameraAction.Tilt]: Axis;
[CameraAction.Roll]: Axis;
}
/**
* Enum of axes
*/
export declare enum Axis {
X = "x",
Y = "y",
Z = "z"
}
export declare abstract class BaseAdaptor extends EventDispatcher {
constructor();
abstract connect(): void;
abstract disconnect(): void;
abstract update(time?: number): void;
abstract isEnabled(): boolean;
}
export declare interface BaseControls {
enable(): void;
disable(): void;
update(time?: number): void;
}
/**
* Enum of camera actions used to control a {@link three-story-controls#CameraRig}
*/
export declare enum CameraAction {
Pan = "Pan",
Tilt = "Tilt",
Roll = "Roll",
Truck = "Truck",
Pedestal = "Pedestal",
Dolly = "Dolly",
Zoom = "Zoom"
}
/**
* A helper tool for creating camera animation paths and/or choosing camera look-at positions for points of interest in a scene
*
* @remarks
* A helper tool for creating camera animation paths and/or choosing camera look-at positions for points of interest in a scene.
*
* The `CameraHelper` can be set up with any scene along with {@link three-story-controls#FreeMovementControls | FreeMovementControls}.
*
* It renders as an overlay with functionality to add/remove/reorders points of interest, and create an animation path between them.
* Each saved camera position is displayed with an image on the `CameraHelper` panel.
*
* The data can be exported as a JSON file that can then be used with different control schemes.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/camera-helper | DEMO }
*
* @example
* Here's an example of initializing the CameraHelper
* ```js
* const scene = new Scene()
* const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
* const cameraRig = new CameraRig(camera, scene)
* const controls = new FreeMovementControls(cameraRig)
*
* controls.enable()
*
* const cameraHelper = new CameraHelper(rig, controls, renderer.domElement)
*
* // Render loop
* // To allow for capturing an image of the canvas,
* // it's important to update the CameraHelper after the scene is rendered,
* // but before requesting the animation frame
* function render(t) {
* controls.update(t)
* renderer.render(scene, camera)
* cameraHelper.update(t)
* window.requestAnimationFrame(render)
* }
*
* render()
* ```
*
*
*
* The following examples demonstrate using the exported data. Note: Depending on your setup, you may need to change the .json extension to .js and prepend the text with `export default` such that you can import it as javascript
*
* @example
* Here's an example using the exported JSON data with ScrollControls.
* ```javascript
* import * as cameraData from 'camera-control.json'
* const scene = new Scene()
* const gltfLoader = new GLTFLoader()
* const camera = new PerspectiveCamera()
* const cameraRig = new CameraRig(camera, scene)
*
* // Parse the JSON animation clip
* cameraRig.setAnimationClip(AnimationClip.parse(cameraData.animationClip))
* cameraRig.setAnimationTime(0)
*
* const controls = new ScrollControls(cameraRig, {
* scrollElement: document.querySelector('.scroller'),
* })
*
* controls.enable()
*
* function render(t) {
* window.requestAnimationFrame(render)
* if (rig.hasAnimation) {
* controls.update(t)
* }
* renderer.render(scene, camera)
* }
* ```
*
* @example
* Here's an example using the exported data with Story Point controls
* ```javascript
* import * as cameraData from 'camera-control.json'
* const scene = new Scene()
* const gltfLoader = new GLTFLoader()
* const camera = new PerspectiveCamera()
* const cameraRig = new CameraRig(camera, scene)
*
* // Format the exported data to create three.js Vector and Quaternions
* const pois = cameraData.pois.map((poi, i) => {
* return {
* position: new Vector3(...poi.position),
* quaternion: new Quaternion(...poi.quaternion),
* duration: poi.duration,
* ease: poi.ease,
* }
* })
*
* const controls = new StoryPointsControls(rig, pois)
* controls.enable()
*
* function render(t) {
* window.requestAnimationFrame(render)
* controls.update(t)
* renderer.render(scene, camera)
* }
* ```
*/
export declare class CameraHelper {
readonly rig: CameraRig;
readonly controls: FreeMovementControls;
readonly canvas: HTMLCanvasElement;
private pois;
private currentIndex;
private drawer;
private domList;
private collapseBtn;
private fileInput;
private btnImport;
private doCapture;
private animationClip;
private isPlaying;
private playStartTime;
private useSlerp;
constructor(rig: CameraRig, controls: FreeMovementControls, canvas: HTMLCanvasElement, canvasParent?: HTMLElement);
private capture;
update(time: number): void;
private addPoi;
private updatePoi;
private movePoi;
private removePoi;
private goToPoi;
private createClip;
private scrubClip;
private playClip;
private import;
private export;
private exportImages;
private initUI;
private handleEvents;
private collapse;
private render;
}
/**
* Event: Fired when CameraRig ends a transition
* @example
* ```javascript
* rig.addEventListener('CameraMoveEnd', handlerFunction)
* ```
* */
export declare interface CameraMoveEndEvent {
type: 'CameraMoveEnd';
}
/**
* Event: Fired when CameraRig starts a transition
* @example
* ```javascript
* rig.addEventListener('CameraMoveStart', handlerFunction)
* ```
* */
export declare interface CameraMoveStartEvent {
type: 'CameraMoveStart';
}
/**
* Event: Fired on every tick of CameraRig's transition
* @example
* ```javascript
* rig.addEventListener('CameraMoveUpdate', handlerFunction)
* ```
* */
export declare interface CameraMoveUpdateEvent {
type: 'CameraMoveUpdate';
/** Percentage of transition completed, between 0 and 1. */
progress: number;
}
/**
* The CameraRig holds the camera, and can respond to {@link three-story-controls#CameraAction}s such as Pan/Tilt/Dolly etc. It can also be controlled along a given path (in the form of an `AnimationClip`), or tweened to specified points.
*
* @remarks
* The rig is constructed of three objects, analagous to a body, head and eyes. The camera is nested in the eyes and is never transformed directly.
*
* Instead of specifying the axis to rotate/translate the camera, {@link three-story-controls#CameraAction}s are used. The rotation order of actions is always `Pan` then `Tilt` then `Roll`.
* The mapping of these actions to axes depends on the up axis, which defaults to `Y` (but can be changed with the {@link CameraRig.setUpAxis | setUpAxis() method}):
*
* * `CameraAction.Pan` rotates around the `Y` axis
*
* * `CameraAction.Tilt` rotates around the `X` axis
*
* * `CameraAction.Roll` rotates around the `Z` axis
*
* * `CameraAction.Dolly` translates on the `Z` axis
*
* * `CameraAction.Truck` translates on the `X` axis
*
* * `CameraAction.Pedestal` translates on the `Y` axis
*
* Translations will be applied to the 'body' of the rig, and rotations to the 'eyes'. If an animation clip is provided, or the camera is tweened to a specific location,
* the rotations will be applied to the 'head', thus leaving the 'eyes' free to 'look around' from this base position.
*
* Additionally, the default setup assumes that the rig will move forward/backward (`Dolly`) in the direction the camera is panned to.
* This can be configured through {@link CameraRig.translateAlong | translateAlong property}.
* It can also be overwritten by providing the component name to the {@link CameraRig.do | do() method}, see {@link https://github.com/nytimes/three-story-controls/blob/main/src/controlschemes/ThreeDOFControls.ts#L96 | ThreeDOFControls implementation} for an example.
*
* To move the rig along a specified path, use the {@link CameraRig.setAnimationClip | setAnimationClip() method},
* and set the names for the `Translation` and `Rotation` objects to match those of the clip. The clip should have a `VectorKeyframeTrack` for the outer position/translation object,
* and a `QuaternionKeyframeTrack` for the inner orientation/rotation object.
*
* See {@link three-story-controls#CameraMoveStartEvent}, {@link three-story-controls#CameraMoveUpdateEvent} and {@link three-story-controls#CameraMoveEndEvent} for emitted event signatures.
*/
export declare class CameraRig extends EventDispatcher {
readonly camera: Camera;
readonly scene: Scene;
private body;
private head;
private eyes;
private cameraIsInRig;
private inTransit;
private upAxis;
private actionAxes;
private hasAnimation;
private animationClip;
private mixer;
private animationTranslationObjectName;
private animationRotationObjectName;
translateAlong: TranslateGuide;
constructor(camera: Camera, scene: Scene);
/**
* Get the axis for a given action
* @param action
* @returns x | y | z
*/
getAxisFor(action: CameraAction): string;
/**
* Get the axis' vector for a given action
* @param action
* @returns Normalized vector for the axis
*/
getAxisVectorFor(action: CameraAction): Vector3;
/**
* Main method for controlling the camera
* @param action - Action to perform
* @param amount - Amount to move/rotate/etc
* @param rigComponent - Override the default component to perform the action on
*/
do(action: CameraAction, amount: number, rigComponent?: RigComponent): void;
/**
* Get world position and orientation of the camera
*/
getWorldCoordinates(): {
position: Vector3;
quaternion: Quaternion;
};
/**
* Sets world coordinates for the camera, and configures rig component transforms accordingly.
* @param param0
*/
setWorldCoordinates({ position, quaternion }: {
position: Vector3;
quaternion: Quaternion;
}): void;
/**
* Packs transfrom into the body and head, and 0s out transforms of the eyes. Useful for preparing the
* rig for control through an animation clip.
*/
packTransform(): void;
/**
* Unpacks the current camera world coordinates and distributes transforms
* across the rig componenets.
*/
unpackTransform(): void;
/**
* Disassemble the camera from the rig and attach it to the scene.
*/
disassemble(): void;
/**
* Place the camera back in the rig
*/
assemble(): void;
/**
* Get the rotation order as a string compatible with what three.js uses
*/
getRotationOrder(): string;
/**
* Whether the camera is currently attached to the rig
*/
isInRig(): boolean;
/**
* If the camera is in the middle of a transition
*/
isMoving(): boolean;
/**
* Set the up axis for the camera
* @param axis - New Up axis
*/
setUpAxis(axis: Axis): void;
/**
* Set an animation clip for the rig
* @param {AnimationClip} clip - AnimationClip containing a VectorKeyFrameTrack for position and a QuaternionKeyFrameTrack for rotation
* @param {string} translationObjectName - Name of translation object
* @param {string} rotationObjectName - Name of rotation object
*/
setAnimationClip(clip: AnimationClip, translationObjectName?: string, rotationObjectName?: string): void;
/**
* Transition to a specific position and orientation in world space.
* Transform on eyes will be reset to 0 as a result of this.
* @param position
* @param quaternion
* @param duration
* @param ease
* @param useSlerp
*/
flyTo(position: Vector3, quaternion: Quaternion, duration?: number, ease?: string, useSlerp?: boolean): void;
/**
* Transition to a specific keyframe on the animation clip
* Transform on eyes will be reset to 0 as a result of this.
* @param frame - frame
* @param duration - duration
* @param ease - ease
*/
flyToKeyframe(frame: number, duration?: number, ease?: string): void;
/**
* @param percentage - percentage of animation clip to move to, between 0 and 1
*/
setAnimationPercentage(percentage: number): void;
/**
* @param time - timestamp of animation clip to move to
*/
setAnimationTime(time: number): void;
/**
* @param frame - frame of animation clip to move to
*/
setAnimationKeyframe(frame: number): void;
}
export declare interface ContinuousEvent {
type: 'update';
}
declare interface Coordinates extends DamperValues {
x: number;
y: number;
}
/**
* Damper uses simple linear damping for a given collection of values.
* On every call to update, the damper will approach a given set of target values.
* @example
* ```js
* const damper = new Damper({
* values: {x: 0, y: 0},
* dampingFactor: 0.4
* })
*
* damper.setTarget({ x: 1, y: 100 })
* damper.update() // would generally be called in an animation loop
* const values = damper.getCurrentValues() // values.x = 0.4; values.y = 40
* ```
*/
export declare class Damper {
private dampingFactor;
private epsilon;
private values;
private targetValues;
private deltaValues;
private hasReached;
constructor(props: DamperProps);
/**
* Update the damper, should generally be called on every frame
*/
update(): void;
/**
* Set the target values the damper needs to approach
* @param target DamperValues the damper needs to approach
*/
setTarget(target: DamperValues): void;
/**
* Increment/Decrement a specifc damper target value
* @param key The key of the value to modify
* @param value The amount to modify the target by
*/
addToTarget(key: string, value: number): void;
/**
* Reset all damper values to the fiven number
* @param value Number to reset all damper values to
*/
resetAll(value: number): void;
/**
* Reset damper values as described by the given DamperValues object
* @param values DamperValues object to reset the damper to
*/
resetData(values: DamperValues): void;
/**
* Get the current values
* @returns DamperValues object with the current values of the damper
*/
getCurrentValues(): DamperValues;
/**
* Get the change in values since the last update call
* @returns DamperValues object with the amount the values changed since the last `update()` call
*/
getDeltaValues(): DamperValues;
/**
* Whether the damper has reached its target
* @returns Whether the damper has reached its target (within permissible error range)
*/
reachedTarget(): boolean;
}
export declare interface DamperProps {
/** Values to be dampened */
values: DamperValues;
/** Multiplier used on each update to approach the target value, should be between 0 and 1, where 1 is no damping */
dampingFactor: number;
/** Amount of permitted error before a value is considered to have 'reached' its target. Defaults to 0.001 */
epsilon?: number;
}
export declare interface DamperValues {
/** A value to dampen, set to its initial state */
[key: string]: number | null;
}
export declare interface DiscreteEvent {
type: 'trigger';
}
/**
* Event: Fired when attempting to go the the next/previous point of interest, but none exists
* Fired on `StoryPointsControls` and `PathPointsControls`. `controls.addEventListener('ExitPOIs', ...)`
* */
export declare interface ExitPOIsEvent {
type: 'ExitPOIs';
exitFrom: 'start' | 'end';
}
/**
* Control scheme to move the camera with arrow/WASD keys and mouse wheel; and rotate the camera with click-and-drag events.
* @remarks
* Control scheme to move the camera with arrow/WASD keys and mouse wheel; and rotate the camera with click-and-drag events.
* On a touch device, 1 finger swipe rotates the camera, and 2 fingers tranlsate/move the camera.
*
*
* Note: CSS property `touch-action: none` will probably be needed on listener element.
*
* See {@link three-story-controls#FreeMovementControlsProps} for all properties that can be passed to the constructor.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/freemove | DEMO }
*
* @example
* ```js
* const scene = new Scene()
* const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
* const cameraRig = new CameraRig(camera, scene)
* const controls = new FreeMovementControls(cameraRig)
*
* controls.enable()
*
* // render loop
* function animate(t) {
* controls.update(t)
* }
* ```
*
*/
export declare class FreeMovementControls implements BaseControls {
readonly cameraRig: CameraRig;
private keyboardAdaptor;
private wheelAdaptor;
private pointerAdaptor;
private wheelScaleFactor;
private pointerScaleFactor;
private panDegreeFactor;
private tiltDegreeFactor;
private enabled;
/** {@inheritDoc three-story-controls#FreeMovementControlsProps#} */
constructor(cameraRig: CameraRig, props?: FreeMovementControlsProps);
isEnabled(): boolean;
enable(): void;
disable(): void;
private onWheel;
private onKey;
private onPointer;
update(time: number): void;
}
/**
* Properties that can be passed to the {@link three-story-controls#FreeMovementControls} constructor
*/
export declare interface FreeMovementControlsProps {
domElement?: HTMLElement;
/** Damping factor between 0 and 1. Defaults to 0.3 */
pointerDampFactor?: number;
/** Mutiplier for two-pointer translation. Defaults to 4 */
pointerScaleFactor?: number;
/** Damping factor between 0 and 1. Defaults to 0.5 */
keyboardDampFactor?: number;
/** Mutiplier for keyboard translation. Defaults to 0.5 */
keyboardScaleFactor?: number;
/** Damping factor between 0 and 1. Defaults to 0.25 */
wheelDampFactor?: number;
/** Mutiplier for wheel translation. Defaults to 0.05 */
wheelScaleFactor?: number;
/** Mutiplier for panning. Defaults to Math.PI / 4 */
panDegreeFactor?: number;
/** Mutiplier for tilting. Defaults to Math.PI / 10 */
tiltDegreeFactor?: number;
}
export declare interface IntertiaCompleteEvent {
type: 'inertiacomplete';
}
/**
* Parse keyboard events and emit either dampened values for continuous keypresses, or trigger events named according to a provided keymapping.
* @remarks
* See {@link three-story-controls#KeyboardAdaptorProps} for all properties that can be passed to the constructor.
* See {@link three-story-controls#KeyboardAdaptorDiscreteEvent} and {@link three-story-controls#KeyboardAdaptorContinuousEvent} for emitted event signatures.
* @example Continuous adaptor
* ```javascript
* const keyboardAdaptor = new KeyboardAdaptor({ type: 'continuous', dampingFactor: 0.2 })
* keyboardAdaptor.connect()
* keyboardAdaptor.addEventListener('update', (event) => {
* cube.rotation.y += event.deltas.right - event.deltas.left
* cube.rotation.x += event.deltas.up - event.deltas.down
* )}
* function animate() {
* keyboardAdaptor.update()
* window.requestAnimationFrame(animate)
* }
* animate()
* ```
*/
export declare class KeyboardAdaptor extends BaseAdaptor {
private type;
private damper;
private dampingFactor;
private incrementor;
private keyMapping;
private connected;
private preventBubbling;
constructor(props: KeyboardAdaptorProps);
connect(): void;
disconnect(): void;
update(): void;
isEnabled(): boolean;
private onKeyUp;
private onKeyDown;
}
/**
* Event: Fired when a key in a `continuous` KeyboardAdaptor's mapping is pressed (`onKeyDown`)
* @example
* ```javascript
* adaptor.on('update', () => { // do something })
* ```
* */
export declare interface KeyboardAdaptorContinuousEvent extends ContinuousEvent {
values: DamperValues;
deltas: DamperValues;
}
/**
* Event: Fired when a key in a `discrete` KeyboardAdaptor's mapping is released (`onKeyUp`)
* @example
* ```javascript
* adaptor.on('trigger', () => { // do something })
* ```
* */
export declare interface KeyboardAdaptorDiscreteEvent extends DiscreteEvent {
/** KeyMapping key that triggered the event */
trigger: string;
}
/**
* Properties that can be passed to the {@link three-story-controls#KeyboardAdaptor} constructor
*/
export declare interface KeyboardAdaptorProps {
/** 'discrete' or 'continuous' */
type: KeyboardAdaptorType;
/**
* Default key mapping uses forward/backward/up/down/left/right as semanic labels, with WASD and arrow keys mapped appropriately:
* @example keyMapping
* ```javascript
* {
* forward: ['ArrowUp', 'w', 'W'],
* backward: ['ArrowDown', 's', 'S'],
* left: ['ArrowLeft', 'a', 'A'],
* right: ['ArrowRight', 'd', 'D'],
* up: ['u', 'U'],
* down: ['n', 'N'],
* }
* ```
* */
keyMapping?: KeyMapping;
/** Only used for continuous adaptor, value between 0 and 1. Defaults to 0.5 */
dampingFactor?: number;
/** Only used for continuous adaptor, the amount to increment the target value on each keydown event. Defaults to 1 */
incrementor?: number;
/** Prevent event bubbling. Defaults to true */
preventBubbling?: boolean;
}
/**
* A discrete adaptor works as a trigger - only firing events on keyup,
* whereas a continuous adaptor continuously fires events on keydown
* */
export declare type KeyboardAdaptorType = 'discrete' | 'continuous';
/**
* Key-value pairs of semantic labels associated with an array of keys (corresponding to `KeybordEvent.keys` values)
*/
export declare interface KeyMapping {
/** The key is a semantic label, and the string[] is a corresponding collection of event.keys */
[key: string]: string[];
}
export declare interface PathPointMarker {
frame: number;
}
/**
* Control scheme to transition the camera between specific points (frames) along a path specified through an `AnimationClip`.
* @remarks
* Control scheme to transition the camera between specific points (frames) along a path specified through an `AnimationClip`.
* A mouse wheel or swipe or keyboard arrow event triggers the camera to smoothly transition from one given frame number to the next.
*
*
* Note: CSS property `touch-action: none` will probably be needed on listener element.
*
* See {@link three-story-controls#PathPointsControlsProps} for all properties that can be passed to the constructor.
*
* See {@link three-story-controls#PathPointMarker} for POI properties.
*
* See {@link three-story-controls#UpdatePOIsEvent} and {@link three-story-controls#ExitPOIsEvent} for emitted event signatures.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/path-points/ | DEMO }
* @example
* ```js
*
* const pois = [ { frame: 0 }, { frame: 54 } ....]
* const scene = new Scene()
* const gltfLoader = new GLTFLoader()
* let camera, cameraRig, controls
*
* gltfLoader.load(cameraPath, (gltf) => {
* camera = gltf.cameras[0]
* cameraRig = new CameraRig(camera, scene)
* cameraRig.setAnimationClip(gltf.animations[0])
* cameraRig.setAnimationTime(0)
* controls = new PathPointsControls(cameraRig, pois)
* controls.enable()
* controls.addEventListener('ExitPOIs', (e) => {
* // e.exitFrom will be either 'start' or 'end'
* })
* controls.addEventListener('update', (e) => {
* // e.currentIndex will be the index of the starting poi
* // e.upcomingIndex will be the index of the upcoming poi
* // e.progress will be a number 0-1 indicating progress of the transition
* })
* })
* ```
*/
export declare class PathPointsControls extends EventDispatcher implements BaseControls {
readonly cameraRig: CameraRig;
private wheelAdaptor;
private swipeAdaptor;
private keyboardAdaptor;
private pois;
private currentIndex;
private upcomingIndex;
private enabled;
private duration;
private ease;
private wheelThreshold;
private swipeThreshold;
private useKeyboard;
constructor(cameraRig: CameraRig, pois?: PathPointMarker[], props?: PathPointsControlsProps);
getCurrentIndex(): number;
enable(): void;
disable(): void;
update(): void;
isEnabled(): boolean;
private onKey;
private onTrigger;
private updatePois;
private onCameraStart;
private onCameraUpdate;
private onCameraEnd;
}
/**
* Properties that can be passed to the {@link three-story-controls#PathPointsControls} constructor
*/
export declare interface PathPointsControlsProps {
/** Threshold of wheel delta that triggers a transition. Defaults to 15 */
wheelThreshold?: number;
/** Threshold of swipe distance that triggers a transition. Defaults to 60 */
swipeThreshold?: number;
/** Transition duration, defaults to 1 */
duration?: number;
/** Transition easing, defaults to power1 */
ease?: string;
/** Use keyboard arrow keys as navigation, defaults to true */
useKeyboard?: boolean;
}
/**
* Parse pointer events to emit dampened, normalized coordinates along with the pointer count (for detecting multi-touch or drag events)
* @remarks
* See {@link three-story-controls#PointerAdaptorProps} for all properties that can be passed to the constructor.
* See {@link three-story-controls#PointerAdaptorEvent} for emitted event signatures.
* Note: CSS property `touch-action: none` will probably be needed on listener element.
* @example Pointer adaptor
* ```javascript
* const pointerAdaptor = new PointerAdaptor()
* pointerAdaptor.connect()
* pointerAdaptor.addEventListener('update', (event) => {
* switch(event.pointerCount) {
* case 0:
* cube.scale.x = event.values.x
* cube.scale.y = event.values.y
* break
* case 1:
* cube.position.x += event.deltas.x
* cube.position.y -= event.deltas.y
* break
* default:
* break
* }
* })
*
* // in RAF loop:
* function animate(t) {
* pointerAdaptor.update(t)
* }
* ```
*/
export declare class PointerAdaptor extends BaseAdaptor {
private domElement;
private dampingFactor;
private shouldNormalize;
private normalizeAroundZero;
private multipointerThreshold;
private damper;
private connected;
private width;
private height;
private pointerCount;
private recordedPosition;
private cache;
private lastDownTime;
private lastUpTime;
constructor(props: PointerAdaptorProps);
connect(): void;
disconnect(): void;
update(time: number): void;
isEnabled(): boolean;
private setDimensions;
private getPointerPosition;
private normalize;
private onPointerMove;
private onPointerDown;
private onPointerUp;
private onResize;
}
/**
* Event: Fired when when `PointerEvent`s are triggered
* @example
* ```javascript
* adaptor.on('trigger', (e) => {
* console.log('x/y coordinates', e.values.x, e.values.y)
* })
* ```
* */
export declare interface PointerAdaptorEvent extends ContinuousEvent {
/** Dampened x and y pointer coordinates */
values: Coordinates;
/** Pointer coordinate change since previous update */
deltas: Coordinates;
/** Number of pointers registered */
pointerCount: number;
}
/**
* Properties that can be passed to the {@link three-story-controls#PointerAdaptor} constructor
*/
export declare interface PointerAdaptorProps {
/** DOM element that should listen for pointer events. Defaults to `document.body` */
domElement?: HTMLElement;
/** Damping value between 0 and 1. Defaults to 0.5 */
dampingFactor?: number;
/** Whether to normalize the pointer position values. Defaults to true */
shouldNormalize?: boolean;
/** If values are normalized, whether they should be in -1 to 1 range. Defaults to true. */
normalizeAroundZero?: boolean;
/** Debounce for registering a change in the pointer count, in ms. Defaults to 100. */
multipointerThreshold?: number;
}
/**
* Enum of {@link three-story-controls#CameraRig} parts
*/
export declare enum RigComponent {
Body = "body",
Head = "head",
Eyes = "eyes"
}
/**
* ScrollActions provide a way to add custom callback hooks for specific parts of the scroll area
*/
export declare interface ScrollAction {
/** When to start the action, in %, px or vh. */
start: string;
/** When to end the action, in %, px or vh. */
end: string;
/** Callback with 0-1 progress when element is between start and end conditions. */
callback: (progress: number) => void;
/** @internal */
startPx: number;
/** @internal */
endPx: number;
/** @internal */
bufferedStartPx: number;
/** @internal */
bufferedEndPx: number;
}
/**
* Emits normalized values for the amount a given DOM element has been scrolled through.
* @remarks
* See {@link three-story-controls#ScrollAdaptorProps} for all properties that can be passed to the constructor.
* See {@link three-story-controls#ScrollAdaptorEvent} for emitted event signatures.
* @example Scroll adaptor
* ```javascript
* const scrollAdaptor = new ScrollAdaptor({ scrollElement: document.querySelector('.scroller'), dampingFactor: 0.1 })
* scrollAdaptor.connect()
* scrollAdaptor.addEventListener('update', (event) => {
* cube.rotation.y = event.dampenedValues.scrollPercent*Math.PI*2
* })
* ```
*/
export declare class ScrollAdaptor extends BaseAdaptor {
private scrollElement;
private damper;
private dampingFactor;
private connected;
private values;
private lastSeenScrollValue;
private previousScrollValue;
private startPosition;
private endPosition;
private distance;
private bufferedStartPosition;
private bufferedEndPosition;
private startOffset;
private endOffset;
private buffer;
private resizeObserver;
constructor(props: ScrollAdaptorProps);
connect(): void;
disconnect(): void;
update(): void;
isEnabled(): boolean;
parseOffset(offset: string): number;
private calculateOffset;
private calculateDimensions;
private onScroll;
}
/**
* Event: Fired when when the 'in view' amount of the given DOM element changes
*/
export declare interface ScrollAdaptorEvent extends ContinuousEvent {
values: DamperValues;
dampenedValues: DamperValues;
}
/**
* Properties that can be passed to the {@link three-story-controls#ScrollAdaptor} constructor
*/
export declare interface ScrollAdaptorProps {
/** Long DOM Element to observe */
scrollElement: HTMLElement;
/** Offset to start registering scroll, in px or vh. Default starts when top of element is at bottom of viewport. */
startOffset?: string;
/** Offset to end registering scroll, in px or vh. Default ends when bottom of element is at top of viewport. */
endOffset?: string;
/** Buffer before and after element to start registering scroll. Number between 0 and 1, defaults to 0.1 */
buffer?: number;
/** Value between 0 and 1. Defaults to 0.5 */
dampingFactor?: number;
}
/**
* Control scheme to scrub through the CameraRig's `AnimationClip` based on the scroll of a DOM Element
* @remarks
* Control scheme to scrub through the CameraRig's `AnimationClip` based on the scroll of a DOM Element.
* These controls expect to observe an element that is a few viewports long, and use the scroll distance to scrub through a camera animation.
* By default, the 'start' of the animation is when the element starts to be in view (ie the top of the element aligns with the bottom of the viewport),
* and the 'end' is when the element goes out of view (when the bottom of the elements aligns with the top of the viewport).
* These trigger points can be customised with the `cameraStart` and `cameraEnd` properties. Additional scroll-dependant procedures can also be defined through `scrollActions`.
*
*
* See {@link three-story-controls#ScrollControlsProps} for all properties that can be passed to the constructor.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/scroll-controls/ | DEMO }
*
* @example
* ```js
* const scene = new Scene()
* const gltfLoader = new GLTFLoader()
* const camera = new PerspectiveCamera()
* const cameraRig = new CameraRig(camera, scene)
* const controls = new ScrollControls(cameraRig, {
* scrollElement: document.querySelector('.scroller'),
* cameraStart: '12%',
* cameraEnd: '90%',
* scrollActions: [
* { start: '0%' , end: '10%', callback: e => fadeInElement(e) },
* { start: '85%' , end: '100%', callback: e => fadeOutElement(e) }
* ]
* })
*
* function fadeInElement(progress) { // entry fade transition }
* function fadeOutElement(progress) { // exit fade transition }
*
* gltfLoader.load(cameraPath, (gltf) => {
* cameraRig.setAnimationClip(gltf.animations[0])
* cameraRig.setAnimationTime(0)
* controls.enable()
* })
*
* // render loop
* function animate() {
* controls.update()
* }
* ```
*/
export declare class ScrollControls implements BaseControls {
readonly cameraRig: CameraRig;
private scrollAdaptor;
private enabled;
private cameraStart;
private cameraEnd;
private cameraStartPx;
private cameraEndPx;
private cameraBufferedStartPx;
private cameraBufferedEndPx;
private scrollActions;
private buffer;
constructor(cameraRig: CameraRig, props: ScrollControlsProps);
isEnabled(): boolean;
enable(): void;
disable(): void;
update(): void;
private calculateStops;
private onScroll;
}
/**
* Properties that can be passed to the {@link three-story-controls#ScrollControls} constructor
*/
export declare interface ScrollControlsProps {
/** Long DOM Element to observe */
scrollElement: HTMLElement;
/** Offset to start registering scroll, in px or vh. Default starts when top of element is at bottom of viewport. */
startOffset?: string;
/** Offset to end registering scroll, in px or vh. Default ends when bottom of element is at top of viewport. */
endOffset?: string;
/** Value between 0 and 1. Defaults to 1 */
dampingFactor?: number;
/** Buffer before and after element to start registering scroll. Number (percentage) between 0 and 1, defaults to 0.1 */
buffer?: number;
/** When in the scroll to start the camera animation, can be specified in px, % or vh */
cameraStart?: string;
/** When in the scroll to end the camera animation, can be specified in px, % or vh */
cameraEnd?: string;
/** Array of ScrollActions for custom scroll hooks */
scrollActions: ScrollAction[];
}
export declare interface StoryPointMarker {
/** Camera position */
position: Vector3;
/** Camera quaternion */
quaternion: Quaternion;
/** Transition duration, defaults to 1 */
duration?: number;
/** Transition easing, defaults to power1 */
ease?: string;
/** Use spherical interpolation for rotation, defaults to true */
useSlerp?: boolean;
}
/**
* Control scheme to transition the camera between given points in world space.
* @remarks
* See {@link three-story-controls#StoryPointsControlsProps} for all properties that can be passed to the constructor.
*
* See {@link three-story-controls#StoryPointMarker} for POI properties.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/story-points/ | DEMO }
*
* @example
* ```js
*
* const pois = [
* { position: new Vector3(...), quaternion: new Quaternion(...) },
* { position: new Vector3(...), quaternion: new Quaternion(...) },
* ]
* const scene = new Scene()
* const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
* const cameraRig = new CameraRig(camera, scene)
* const controls = new StoryPointsControls(cameraRig, pois)
*
* controls.enable()
* controls.goToPOI(0)
*
* // Assuming DOM elements with classes 'nextBtn' and 'prevBtn' have been created
* document.querySelector('.nextBtn').on('click', () => controls.nextPOI() )
* document.querySelector('.prevBtn').on('click', () => controls.prevPOI() )
* ```
*/
export declare class StoryPointsControls extends EventDispatcher implements BaseControls {
readonly cameraRig: CameraRig;
private keyboardAdaptor;
private pois;
private currentIndex;
private upcomingIndex;
private enabled;
private cycle;
private useKeyboard;
constructor(cameraRig: CameraRig, pois?: StoryPointMarker[], props?: StoryPointsControlsProps);
getCurrentIndex(): number;
nextPOI(): void;
prevPOI(): void;
goToPOI(index: number): void;
enable(): void;
disable(): void;
update(): void;
isEnabled(): boolean;
private updatePois;
private onCameraStart;
private onCameraUpdate;
private onCameraEnd;
private onKey;
}
/**
* Properties that can be passed to the {@link three-story-controls#StoryPointsControls} constructor
*/
export declare interface StoryPointsControlsProps {
/** Whether to cycle to the first/last POI after reaching the end/start. When false, controls with emit 'ExitStoryPoints' events. Defaults to false. */
cycle?: boolean;
/** Use keyboard arrow keys as navigation, defaults to true */
useKeyboard?: boolean;
}
/**
* Emits events in response to swipe gestures above a given threshold.
* @remarks
* See {@link three-story-controls#SwipeAdaptorProps} for all properties that can be passed to the constructor.
* See {@link three-story-controls#SwipeAdaptorEvent} for emitted event signatures.
* Note: CSS property `touch-action: none` will probably be needed on listener element
* @example Swipe adaptor
* ```javascript
* const swipeAdaptor = new SwipeAdaptor()
* swipeAdaptor.connect()
* swipeAdaptor.addEventListener('trigger', (event) => {
* cube.scale.y += event.y*0.1
* })
* ```
*/
export declare class SwipeAdaptor extends BaseAdaptor {
private domElement;
private thresholdX;
private thresholdY;
private startX;
private startY;
private connected;
constructor(props?: SwipeAdaptorProps);
connect(): void;
disconnect(): void;
update(): void;
isEnabled(): boolean;
private onPointerDown;
private onPointerUp;
}
/**
* Event: Fired when when swipe are registered
* @remarks
* The sign represents the direction of the swipe,
* y = 1 when swiping down-to-up, and x = 1 when swiping left-to-right
* */
export declare interface SwipeAdaptorEvent extends DiscreteEvent {
x: -1 | 1 | 0;
y: -1 | 1 | 0;
}
/**
* Properties that can be passed to the {@link three-story-controls#SwipeAdaptor} constructor
*/
export declare interface SwipeAdaptorProps {
/** DOM element to listen to events on. Defaults to document.body */
domElement?: HTMLElement;
/** Threshold of pointer's deltaX to trigger events. Defaults to 60 */
thresholdX?: number;
/** Threshold of pointer's deltaY to trigger events. Defaults to 60 */
thresholdY?: number;
}
/**
* Control scheme for slight rotation and translation movement in response to mouse movements (designed to be used in conjunction with other control schemes)
* @remarks
* Note: CSS property `touch-action: none` will probably be needed on listener element
*
* See {@link three-story-controls#ThreeDOFControlsProps} for all properties that can be passed to the constructor.
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/story-points/ | DEMO w/ story points }
*
* {@link https://nytimes.github.io/three-story-controls/examples/demos/scroll-controls/ | DEMO w/ scroll controls}
*
* @example
* ```js
* const scene = new Scene()
* const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
* const cameraRig = new CameraRig(camera, scene)
* const controls = new ThreeDOFControls(cameraRig)
*
* controls.enable()
*
* // render loop
* function animate(t) {
* controls.update(t)
* }
* ```
*/
export declare class ThreeDOFControls implements BaseControls {
readonly cameraRig: CameraRig;
private pointerAdaptor;
private enabled;
private panFactor;
private tiltFactor;
private truckFactor;
private pedestalFactor;
constructor(cameraRig: CameraRig, props?: ThreeDOFControlsProps);
isEnabled(): boolean;
enable(): void;
disable(): void;
update(time: number): void;
private onPointerMove;
}
/**
* Properties that can be passed to the {@link three-story-controls#ThreeDOFControls} constructor
*/
export declare interface ThreeDOFControlsProps {
/** DOM element that should listen for pointer events. Defaults to `document.body` */
domElement?: HTMLElement;
/** Mutiplier for panning. Defaults to Math.PI / 20 */
panFactor?: number;
/** Mutiplier for tilting. Defaults to Math.PI / 20 */
tiltFactor?: number;
/** Mutiplier for truck translation. Defaults to 1 */
truckFactor?: number;
/** Mutiplier for pedestal translation. Defaults to 1 */
pedestalFactor?: number;
/** Damping factor between 0 and 1. Defaults to 0.7 */
dampingFactor?: number;
}
/**
* Describe whether rig should translate along current rotation in each action axis
*/
export declare interface TranslateGuide {
[CameraAction.Pan]: boolean;
[CameraAction.Tilt]: boolean;
[CameraAction.Roll]: boolean;
}
/**
* Event: Fired when transitioning between points of interest. Fired on `StoryPointsControls` and `PathPointsControls`. `controls.addEventListener('update', ...)`
* */
export declare interface UpdatePOIsEvent {
type: 'update';
currentIndex: number;
upcomingIndex: number;
progress: number;
}
/**
* Parse mouse wheel events and emit either dampened values, or trigger events for swipes that cross a given threshold.
* @remarks
* See {@link three-story-controls#WheelAdaptorProps} for all properties that can be passed to the constructor.
* See {@link three-story-controls#WheelAdaptorDiscreteEvent} and {@link three-story-controls#WheelAdaptorContinuousEvent} for emitted event signatures.
* @example Discrete adaptor
* ```javascript
* const wheelAdaptor = new WheelAdaptor({ type: 'discrete' })
* wheelAdaptor.connect()
* wheelAdaptor.addEventListener('trigger', (event) => {
* cube.scale.y += event.y*0.1
* })
* ```
*/
export declare class WheelAdaptor extends BaseAdaptor {
private type;
private domElement;
private dampingFactor;
private damper;
private thresholdX;
private thresholdY;
private debounceDuration;
private lastThresholdTrigger;
private connected;
constructor(props: WheelAdaptorProps);
connect(): void;
disconnect(): void;
update(): void;
isEnabled(): boolean;
private onWheel;
}
/**
* Event: Fired on a continuous `WheelAdaptor` in response to `wheel` events
* @remarks
* DamperValues have `x` and `y` keys.
* */
export declare interface WheelAdaptorContinuousEvent extends ContinuousEvent {
values: DamperValues;
deltas: DamperValues;
}
/**
* Event: Fired when when discrete `wheel` events are registered
* @remarks
* The sign represents the the direction of the wheel event that caused the event to trigger
* */
export declare interface WheelAdaptorDiscreteEvent extends DiscreteEvent {
x: -1 | 1 | 0;
y: -1 | 1 | 0;
}
/**
* Properties that can be passed to the {@link three-story-controls#WheelAdaptor} constructor
*/
export declare interface WheelAdaptorProps {
/** 'discrete' or 'continuous' */
type: WheelAdaptorType;
/** DOM element to listen to events on. Defaults to window */
domElement?: HTMLElement;
/** Only used for continuous adaptor, value between 0 and 1. Defaults to 0.5 */
dampingFactor?: number;
/** Only used for discrete adaptor, threshold of wheel.deltaX to trigger events. Defaults to 15 */
thresholdX?: number;
/** Only used for discrete adaptor, threshold of wheel.deltaY to trigger events. Defaults to 15 */
thresholdY?: number;
/** Only used for discrete adaptor, rest duration between firing trigger events. Defaults to 700 */
debounceDuration?: number;
}
/**
* A discrete adaptor works as a trigger - only firing events when wheel events pass a given threshold,
* whereas a continuous adaptor continuously fires events on wheel
* */
export declare type WheelAdaptorType = 'discrete' | 'continuous';
export { } | the_stack |
import {
IAbort,
IAbortIf,
IAbortIfConditionsIsFalse,
IAbortIfConditionsIsTrue,
IAllowButton,
IApplyImpluse,
IBigMessage,
IChaseGlobalVariableAtRate,
IChaseGlobalVariableOverTime,
IChasePlayerVariableAtRate,
IChasePlayerVariableOverTime,
IClearStatus,
ICommunicate,
ICreateEffect,
ICreateHudText,
ICreateIcon,
ICreateInWorldText,
IDamage,
IDeclareMatchDraw,
IDeclarePlayerVictory,
IDeclareRoundVictory,
IDeclareTeamVictory,
IDestroyAllEffects,
IDestroyAllHudText,
IDestroyAllIcons,
IDestroyAllInWorldText,
IDestroyEffect,
IDestroyHudText,
IDestroyIcon,
IDestroyInWorldText,
IDisableBuiltInGameModeAnnouncer,
IDisableBuiltInGameModeCompletion,
IDisableBuiltInGameModeMusic,
IDisableBuiltInGameModeRespawning,
IDisableBuiltInGameModeScoring,
IDisableDeathSpectateAllPlayers,
IDisableDeathSpectateTargetHud,
IDisallowButton,
IEnableBuiltInGameModeAnnouncer,
IEnableBuiltInGameModeCompletion,
IEnableBuiltInGameModeMusic,
IEnableBuiltInGameModeRespawning,
IEnableBuiltInGameModeScoring,
IEnableDeathSpectateAllPlayers,
IEnableDeathSpectateTargetHud,
IGoToAssembleHeroes,
IHeal,
IKill,
ILoop,
ILoopIf,
ILoopIfConditionIsFalse,
ILoopIfConditionIsTrue,
IModifyGlobalVariable,
IModifyGlobalVariableAtIndex,
IModifyPlayerScore,
IModifyPlayerVariable,
IModifyPlayerVariableAtIndex,
IModifyTeamScore,
IPauseMatchTime,
IPlayEffect,
IPreloadHero,
IPressButton,
IResetPlayerHeroAvailability,
IRespawn,
IResurrect,
ISetAbility1Enabled,
ISetAbility2Enabled,
ISetAimSpeed,
ISetDamageDealt,
ISetDamageReceived,
ISetFacing,
ISetGlobalVariable,
ISetGlobalVariableAtIndex,
ISetGravity,
ISetHealingDealt,
ISetHealingReceived,
ISetInvisible,
ISetMatchTime,
ISetMaxHealth,
ISetMoveSpeed,
ISetObjectiveDescription,
ISetPlayerAllowedHeroes,
ISetPlayerVariable,
ISetPlayerVariableAtIndex,
ISetPrimaryFireEnabled,
ISetProjectileGravity,
ISetProjectileSpeed,
ISetRespawnMaxTime,
ISetSecondaryFireEnabled,
ISetSlowMotion,
ISetStatus,
ISetTeamScore,
ISetUltimateAbilityEnabled,
ISetUltimateCharge,
ISkip,
ISkipIf,
ISmallMessage,
IStartAccelerating,
IStartCamera,
IStartDamageModification,
IStartDamageOverTime,
IStartFacing,
IStartForcingPlayerToBeHero,
IStartForcingSpawnRoom,
IStartForcingThrottle,
IStartHealOverTime,
IStartHoldingButton,
IStopAccelerating,
IStopAllDamageModifications,
IStopAllDamageOverTime,
IStopAllHealOverTime,
IStopCamera,
IStopChasingGlobalVariable,
IStopChasingPlayerVariable,
IStopDamageModification,
IStopDamageOverTime,
IStopFacing,
IStopForcingPlayerToBeHero,
IStopForcingSpawnRoom,
IStopForcingThrottle,
IStopHealOverTime,
IStopHoldingButton,
ITeleport,
IUnpauseMatchTime,
IWait,
IStartTransformingThrottle,
IStopTransformingThrottle,
ICreateDummyBot,
IDestroyDummyBot,
IDestroyAllDummyBot,
IStartThrottleInDirection,
IStopThrottleInDirection,
ICreateBeamEffect,
} from './child'
import { ISetPlayerScore } from './child/setPlayerScore'
export interface IAction {
/**
* {0}
*/
abort: IAbort
/**
* {1}
*/
abortIf: IAbortIf
/**
* {2}
*/
abortIfConditionsIsFalse: IAbortIfConditionsIsFalse
/**
* {3}
*/
abortIfConditionsIsTrue: IAbortIfConditionsIsTrue
/**
* {4}
*/
allowButton: IAllowButton
/**
* {5}
*/
applyImpluse: IApplyImpluse
/**
* {6}
*/
bigMessage: IBigMessage
/**
* {7}
*/
chaseGlobalVariableAtRate: IChaseGlobalVariableAtRate
/**
* {8}
*/
chaseGlobalVariableOverTime: IChaseGlobalVariableOverTime
/**
* {9}
*/
chasePlayerVariableAtRate: IChasePlayerVariableAtRate
/**
* {10}
*/
chasePlayerVariableOverTime: IChasePlayerVariableOverTime
/**
* {11}
*/
clearStatus: IClearStatus
/**
* {12}
*/
communicate: ICommunicate
/**
* {13}
*/
createEffect: ICreateEffect
/**
* {14}
*/
createHudText: ICreateHudText
/**
* {15}
*/
createIcon: ICreateIcon
/**
* {16}
*/
createInWorldText: ICreateInWorldText
/**
* {17}
*/
damage: IDamage
/**
* {18}
*/
declareMatchDraw: IDeclareMatchDraw
/**
* {19}
*/
declarePlayerVictory: IDeclarePlayerVictory
/**
* {20}
*/
declareRoundVictory: IDeclareRoundVictory
/**
* {21}
*/
declareTeamVictory: IDeclareTeamVictory
/**
* {22}
*/
destroyAllEffects: IDestroyAllEffects
/**
* {23}
*/
destroyAllHudText: IDestroyAllHudText
/**
* {24}
*/
destroyAllIcons: IDestroyAllIcons
/**
* {25}
*/
destroyAllInWorldText: IDestroyAllInWorldText
/**
* {26}
*/
destroyEffect: IDestroyEffect
/**
* {27}
*/
destroyHudText: IDestroyHudText
/**
* {28}
*/
destroyIcon: IDestroyIcon
/**
* {29}
*/
destroyInWorldText: IDestroyInWorldText
/**
* {30}
*/
disableBuiltInGameModeAnnouncer: IDisableBuiltInGameModeAnnouncer
/**
* {31}
*/
disableBuiltInGameModeCompletion: IDisableBuiltInGameModeCompletion
/**
* {32}
*/
disableBuiltInGameModeMusic: IDisableBuiltInGameModeMusic
/**
* {33}
*/
disableBuiltInGameModeRespawning: IDisableBuiltInGameModeRespawning
/**
* {34}
*/
disableBuiltInGameModeScoring: IDisableBuiltInGameModeScoring
/**
* {35}
*/
disableDeathSpectateAllPlayers: IDisableDeathSpectateAllPlayers
/**
* {36}
*/
disableDeathSpectateTargetHud: IDisableDeathSpectateTargetHud
/**
* {37}
*/
disallowButton: IDisallowButton
/**
* {38}
*/
enableBuiltInGameModeAnnouncer: IEnableBuiltInGameModeAnnouncer
/**
* {39}
*/
enableBuiltInGameModeCompletion: IEnableBuiltInGameModeCompletion
/**
* {40}
*/
enableBuiltInGameModeMusic: IEnableBuiltInGameModeMusic
/**
* {41}
*/
enableBuiltInGameModeRespawning: IEnableBuiltInGameModeRespawning
/**
* {42}
*/
enableBuiltInGameModeScoring: IEnableBuiltInGameModeScoring
/**
* {43}
*/
enableDeathSpectateAllPlayers: IEnableDeathSpectateAllPlayers
/**
* {44}
*/
enableDeathSpectateTargetHud: IEnableDeathSpectateTargetHud
/**
* {45}
*/
goToAssembleHeroes: IGoToAssembleHeroes
/**
* {46}
*/
heal: IHeal
/**
* {47}
*/
kill: IKill
/**
* {48}
*/
loop: ILoop
/**
* {49}
*/
loopIf: ILoopIf
/**
* {50}
*/
loopIfConditionIsFalse: ILoopIfConditionIsFalse
/**
* {51}
*/
loopIfConditionIsTrue: ILoopIfConditionIsTrue
/**
* {52}
*/
modifyGlobalVariable: IModifyGlobalVariable
/**
* {53}
*/
modifyGlobalVariableAtIndex: IModifyGlobalVariableAtIndex
/**
* {54}
*/
modifyPlayerScore: IModifyPlayerScore
/**
* {55}
*/
modifyPlayerVariable: IModifyPlayerVariable
/**
* {56}
*/
modifyPlayerVariableAtIndex: IModifyPlayerVariableAtIndex
/**
* {57}
*/
modifyTeamScore: IModifyTeamScore
/**
* {58}
*/
pauseMatchTime: IPauseMatchTime
/**
* {59}
*/
playEffect: IPlayEffect
/**
* {60}
*/
preloadHero: IPreloadHero
/**
* {61}
*/
pressButton: IPressButton
/**
* {62}
*/
resetPlayerHeroAvailability: IResetPlayerHeroAvailability
/**
* {63}
*/
respawn: IRespawn
/**
* {64}
*/
resurrect: IResurrect
/**
* {65}
*/
setAbility1Enabled: ISetAbility1Enabled
/**
* {66}
*/
setAbility2Enabled: ISetAbility2Enabled
/**
* {67}
*/
setAimSpeed: ISetAimSpeed
/**
* {68}
*/
setDamageDealt: ISetDamageDealt
/**
* {69}
*/
setDamageReceived: ISetDamageReceived
/**
* {70}
*/
setFacing: ISetFacing
/**
* {71}
*/
setGlobalVariable: ISetGlobalVariable
/**
* {72}
*/
setGlobalVariableAtIndex: ISetGlobalVariableAtIndex
/**
* {73}
*/
setGravity: ISetGravity
/**
* {74}
*/
setHealingDealt: ISetHealingDealt
/**
* {75}
*/
setHealingReceived: ISetHealingReceived
/**
* {76}
*/
setInvisible: ISetInvisible
/**
* {77}
*/
setMatchTime: ISetMatchTime
/**
* {78}
*/
setMaxHealth: ISetMaxHealth
/**
* {79}
*/
setMoveSpeed: ISetMoveSpeed
/**
* {80}
*/
setObjectiveDescription: ISetObjectiveDescription
/**
* {81}
*/
setPlayerAllowedHeroes: ISetPlayerAllowedHeroes
/**
* {82}
*/
setPlayerScore: ISetPlayerScore
/**
* {83}
*/
setPlayerVariable: ISetPlayerVariable
/**
* {84}
*/
setPlayerVariableAtIndex: ISetPlayerVariableAtIndex
/**
* {85}
*/
setPrimaryFireEnabled: ISetPrimaryFireEnabled
/**
* {86}
*/
setProjectileGravity: ISetProjectileGravity
/**
* {87}
*/
setProjectileSpeed: ISetProjectileSpeed
/**
* {88}
*/
setRespawnMaxTime: ISetRespawnMaxTime
/**
* {89}
*/
setSecondaryFireEnabled: ISetSecondaryFireEnabled
/**
* {90}
*/
setSlowMotion: ISetSlowMotion
/**
* {91}
*/
setStatus: ISetStatus
/**
* {92}
*/
setTeamScore: ISetTeamScore
/**
* {93}
*/
setUltimateAbilityEnabled: ISetUltimateAbilityEnabled
/**
* {94}
*/
setUltimateCharge: ISetUltimateCharge
/**
* {95}
*/
skip: ISkip
/**
* {96}
*/
skipIf: ISkipIf
/**
* {97}
*/
smallMessage: ISmallMessage
/**
* {98}
*/
startAccelerating: IStartAccelerating
/**
* {99}
*/
startCamera: IStartCamera
/**
* {100}
*/
startDamageModification: IStartDamageModification
/**
* {101}
*/
startDamageOverTime: IStartDamageOverTime
/**
* {102}
*/
startFacing: IStartFacing
/**
* {103}
*/
startForcingPlayerToBeHero: IStartForcingPlayerToBeHero
/**
* {104}
*/
startForcingSpawnRoom: IStartForcingSpawnRoom
/**
* {105}
*/
startForcingThrottle: IStartForcingThrottle
/**
* {106}
*/
startHealOverTime: IStartHealOverTime
/**
* {107}
*/
startHoldingButton: IStartHoldingButton
/**
* {108}
*/
stopAccelerating: IStopAccelerating
/**
* {109}
*/
stopAllDamageModifications: IStopAllDamageModifications
/**
* {110}
*/
stopAllDamageOverTime: IStopAllDamageOverTime
/**
* {111}
*/
stopAllHealOverTime: IStopAllHealOverTime
/**
* {112}
*/
stopCamera: IStopCamera
/**
* {113}
*/
stopChasingGlobalVariable: IStopChasingGlobalVariable
/**
* {114}
*/
stopChasingPlayerVariable: IStopChasingPlayerVariable
/**
* {115}
*/
stopDamageModification: IStopDamageModification
/**
* {116}
*/
stopDamageOverTime: IStopDamageOverTime
/**
* {117}
*/
stopFacing: IStopFacing
/**
* {118}
*/
stopForcingPlayerToBeHero: IStopForcingPlayerToBeHero
/**
* {119}
*/
stopForcingSpawnRoom: IStopForcingSpawnRoom
/**
* {120}
*/
stopForcingThrottle: IStopForcingThrottle
/**
* {121}
*/
stopHealOverTime: IStopHealOverTime
/**
* {122}
*/
stopHoldingButton: IStopHoldingButton
/**
* {123}
*/
teleport: ITeleport
/**
* {124}
*/
unpauseMatchTime: IUnpauseMatchTime
/**
* {125}
*/
wait: IWait
/**
* {717}
*/
startTransformingThrottle: IStartTransformingThrottle
/**
* {722}
*/
stopTransformingThrottle: IStopTransformingThrottle
/**
* {728}
*/
createDummyBot: ICreateDummyBot
/**
* {734}
*/
destroyDummyBot: IDestroyDummyBot
/**
* {737}
*/
destroyAllDummyBot: IDestroyAllDummyBot
/**
* {738}
*/
startThrottleInDirection: IStartThrottleInDirection
/**
* {745}
*/
stopThrottleInDirection: IStopThrottleInDirection
/**
* {747}
*/
createBeamEffect: ICreateBeamEffect
} | the_stack |
import { LanguageKeys } from "#lib/i18n/languageKeys";
import { GuildLogEmbed } from "#lib/structures";
import { Events } from "#lib/types/Enums";
import { seconds } from "#utils/common";
import { Emojis } from "#utils/constants";
import { getAuditLogExecutor } from "#utils/util";
import { ApplyOptions } from "@sapphire/decorators";
import { Events as SapphireEvents, Listener, ListenerOptions } from "@sapphire/framework";
import { inlineCodeBlock, isNullish } from "@sapphire/utilities";
import { Guild, User } from "discord.js";
import type { TFunction } from 'i18next';
@ApplyOptions<ListenerOptions>({ event: Events.GuildUpdate })
export class UserListener extends Listener<typeof SapphireEvents.GuildUpdate> {
public async run(oldGuild: Guild, guild: Guild) {
if (isNullish(guild.id)) return;
const auditLogExecutor = await getAuditLogExecutor('GUILD_UPDATE', guild);
const guildSettings = await this.container.client.prisma.guildSettings.findFirst({ where: { guildID: guild.id } })
const T = this.container.i18n.getT(guildSettings?.language as string)
if (guildSettings?.logChannel && guildSettings.guildUpdateLog) {
this.container.client.emit(Events.GuildMessageLog, guild, guildSettings?.logChannel, Events.GuildUpdate, this.serverLog(oldGuild, guild, auditLogExecutor, T));
}
}
private async serverLog(oldGuild: Guild, guild: Guild, executor: User | null | undefined, t: TFunction) {
const embed = new GuildLogEmbed()
.setAuthor(guild.name, guild.iconURL() as string)
.setDescription(t(LanguageKeys.Miscellaneous.DisplayID, { id: guild.id }))
.setFooter(t(LanguageKeys.Events.Guilds.Logs.GuildUpdated, { by: executor ? t(LanguageKeys.Miscellaneous.By, { user: executor?.tag }) : undefined }), executor?.displayAvatarURL() ?? undefined)
.setType(Events.GuildUpdate);
// Name changed
if (oldGuild.name !== guild.name) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.NameChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortText, { before: oldGuild.name, after: guild.name }));
}
// Icon changed
if (oldGuild.icon !== guild.icon) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.GuildIconChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeLongText, { before: oldGuild.iconURL(), after: guild.iconURL() }));
}
// AFK channel changed
if (oldGuild.afkChannel !== guild.afkChannel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.AfkChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, {
before: oldGuild.afkChannel ? `<#${oldGuild.afkChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None)),
after: guild.afkChannel ? `<#${guild.afkChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None))
}));
}
// AFK timeout changed
if (oldGuild.afkTimeout !== guild.afkTimeout) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.AfkTimeoutChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortText, {
before: t(LanguageKeys.Globals.DurationValue, { value: seconds(oldGuild.afkTimeout) }),
after: t(LanguageKeys.Globals.DurationValue, { value: seconds(guild.afkTimeout) })
}));
}
// Invite splash changed
if (oldGuild.splash !== guild.splash) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SplashChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeLongText, {
before: oldGuild.splash ? oldGuild.splashURL({ format: 'png' }) : t(LanguageKeys.Globals.None),
after: guild.splash ? guild.splashURL({ format: 'png' }) : t(LanguageKeys.Globals.None)
}));
embed.setImage(guild.splashURL({ size: 256 }) as string);
}
// Banner changed
if (oldGuild.banner !== guild.banner) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.BannerChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeLongText, {
before: oldGuild.banner ? oldGuild.bannerURL({ format: 'png' }) : t(LanguageKeys.Globals.None),
after: guild.banner ? guild.bannerURL({ format: 'png' }) : t(LanguageKeys.Globals.None)
}));
embed.setImage(guild.bannerURL({ size: 256 }) as string);
}
// Default message notifications changed
if (oldGuild.defaultMessageNotifications !== guild.defaultMessageNotifications) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.DefaultMessageNotificationsChanged), t(LanguageKeys.Events.Guilds.Logs.DefaultMessageNotificationsFormatted, {
before: oldGuild.defaultMessageNotifications,
after: guild.defaultMessageNotifications
}));
}
// Discovery splash changed
if (oldGuild.discoverySplash !== guild.discoverySplash) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.DiscoverySplashChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeLongText, {
before: oldGuild.discoverySplash ? oldGuild.discoverySplashURL({ format: 'png' }) : t(LanguageKeys.Globals.None),
after: guild.discoverySplash ? guild.discoverySplashURL({ format: 'png' }) : t(LanguageKeys.Globals.None)
}));
embed.setImage(guild.discoverySplashURL({ size: 256 }) as string);
}
// Explicit content filter changed
if (oldGuild.explicitContentFilter !== guild.explicitContentFilter) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.ExplicitContentFilterChanged), t(LanguageKeys.Events.Guilds.Logs.ExplicitContentFilterFormatted, {
before: oldGuild.explicitContentFilter,
after: guild.explicitContentFilter
}));
}
// 2FA requirement toggled
if (oldGuild.mfaLevel !== guild.mfaLevel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.MfaLevelToggled), guild.mfaLevel === 'ELEVATED' ? Emojis.Check : Emojis.X);
}
// Ownership transferred
if (oldGuild.ownerId !== guild.ownerId) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.OwnerChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, { before: `<@${oldGuild.ownerId}>`, after: `<@${guild.ownerId}>` }));
}
// Preferred locale changed
if (oldGuild.preferredLocale !== guild.preferredLocale) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.PreferredLocaleChanged), t(LanguageKeys.Events.Guilds.Logs.PreferredLocaleFormatted, { before: oldGuild.preferredLocale, after: guild.preferredLocale }));
}
// Public updates channel changed
if (oldGuild.publicUpdatesChannel !== guild.publicUpdatesChannel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.PublicUpdatesChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, {
before: oldGuild.publicUpdatesChannel ? `<#${oldGuild.publicUpdatesChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None)),
after: guild.publicUpdatesChannel ? `<#${guild.publicUpdatesChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None))
}));
}
// Rules channel changed
if (oldGuild.rulesChannel !== guild.rulesChannel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.RulesChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, {
before: oldGuild.rulesChannel ? `<#${oldGuild.rulesChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None)),
after: guild.rulesChannel ? `<#${guild.rulesChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None))
}));
}
// System channel changed
if (oldGuild.systemChannel !== guild.systemChannel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, {
before: oldGuild.systemChannel ? `<#${oldGuild.systemChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None)),
after: guild.systemChannel ? `<#${guild.systemChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None))
}));
}
// System channel flags changed
if (oldGuild.systemChannelFlags !== guild.systemChannelFlags) {
this.systemChannelFlagChecker(oldGuild, guild, embed, t);
}
// Vanity URL changed
if (oldGuild.vanityURLCode !== guild.vanityURLCode) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortText, {
before: oldGuild.vanityURLCode ?? t(LanguageKeys.Globals.None),
after: guild.vanityURLCode ?? t(LanguageKeys.Globals.None)
}));
}
// Verification level changed
if (oldGuild.verificationLevel !== guild.verificationLevel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.VerificationLevelChanged), t(LanguageKeys.Events.Guilds.Logs.VerificationLevelFormatted, {
before: oldGuild.verificationLevel,
after: guild.verificationLevel
}));
}
// Widget channel changed
if (oldGuild.widgetChannel !== guild.widgetChannel) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.WidgetChannelChanged), t(LanguageKeys.Events.Guilds.Logs.ChangeShortObject, {
before: oldGuild.widgetChannel ? `<#${oldGuild.widgetChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None)),
after: guild.widgetChannel ? `<#${guild.widgetChannelId}>` : inlineCodeBlock(t(LanguageKeys.Globals.None))
}));
}
// Widget toggled
if (oldGuild.widgetEnabled !== guild.widgetEnabled) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.WidgetEnabledToggled), guild.widgetEnabled ? Emojis.Check : Emojis.X);
}
if (!embed.fields.length) return;
return embed;
}
private systemChannelFlagChecker(oldGuild: Guild, guild: Guild, embed: GuildLogEmbed, t: TFunction) {
const [allOn, boostHelpOn, welcomeHelpOn, helpOn, welcomeBoostOn, boostOn, welcomeOn, allOff] = [0, 1, 2, 3, 4, 5, 6, 7];
// All off
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === allOff && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
// All on
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === allOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
// Welcome on
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
// Boost on
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === boostOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
// Help on
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === helpOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
// Welcome and boost on
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeBoostOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.Check);
}
// Welcome and help on
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === boostHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
if (oldGuild.systemChannelFlags.bitfield === welcomeHelpOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.Check);
}
// Boost and help on
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === allOff) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === welcomeOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === boostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === helpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === welcomeBoostOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsHelpToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === welcomeHelpOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsBoostToggled), Emojis.X);
}
if (oldGuild.systemChannelFlags.bitfield === boostHelpOn && guild.systemChannelFlags.bitfield === allOn) {
embed.addField(t(LanguageKeys.Events.Guilds.Logs.SystemChannelFlagsWelcomeToggled), Emojis.Check);
}
}
} | the_stack |
import base64js from "base64-js";
import { generateRandomUInt32Array } from "../platform-dependent";
const UINT_32HASH_PRIME = 16777619;
/**
* Fast high quality 32 bit RNG for consistent guid.
*
* Good "randomness" (distribution); Period is approximately equal to 3.11*10^37
* Implementation was take from "Numerical recipes. The Art of Scientific Computing.", 3rd edition.
* Page 357, algorithm name: Ranlim32
*
*/
const guidRNG = {
u: 0,
v: 0,
w1: 0,
w2: 0,
isInitialized: false,
/**
* Initialize RNG.
* This function need to be called once, before the first guid gets created.
*
* @param in_seed - Optional 32-bit seed for guid RNG;
* If no seed is given, a combination of system's
* local time and Math.random() is used.
* @param in_enforceReInitialization - Optionally enforce re-initialization with another seed
*
* @returns The seed used to initialize the RNG;
* If re-initialization is not enforced,
* a zero indicates that the RNG was not re-seeded.
* @alias property-common.initializeGUIDGenerator
*/
initialize(in_seed?: number, in_enforceReInitialization: boolean = false): number {
// Quit if the RNG has already been initialized and we do not
// want to enforce a re-initialization with a new seed
if (this.isInitialized && !in_enforceReInitialization) {
return 0;
} else {
this.isInitialized = true;
if (in_seed === undefined) {
const randomValues = generateRandomUInt32Array(4);
this.u = randomValues[0];
this.v = randomValues[1];
this.w1 = randomValues[2];
this.w2 = randomValues[3];
} else {
this.v = 224461437;
this.w1 = 521288629;
this.w2 = 362436069;
this.u = in_seed ^ this.v;
this.genRandUInt32();
this.v = this.u;
this.genRandUInt32();
}
return -1;
}
},
/**
* @returns 32-bit random number based on the RNGs internal state
*/
genRandUInt32(): number {
this.u = multiply_uint32(this.u, 2891336453) + 1640531513;
this.v ^= this.v >>> 13;
this.v ^= this.v << 17;
this.v = ((this.v >>> 5) ^ this.v) >>> 0;
this.w1 = multiply_uint32(33378, (this.w1 & 0xffff)) + (this.w1 >>> 16);
this.w2 = multiply_uint32(57225, (this.w2 & 0xffff)) + (this.w2 >>> 16);
let x = this.u ^ (this.u << 9);
x ^= x >>> 17;
x ^= x << 6;
let y = this.w1 ^ (this.w1 << 17);
y ^= y >>> 15;
y ^= y << 5;
return (((x >>> 0) + this.v) ^ ((y >>> 0) + this.w2)) >>> 0;
},
};
/**
* Check if guid is base64 based on the length
* The length of base16 guid is 36, base64 - 22
*
* @param guid - Input guid
* @returns True if guid is base64
*/
const isBase64 = (guid: string): boolean => guid.length === 22;
/**
* Allows for 32-bit integer multiplication with C-like semantics
*
* @param a - unsigned int32 value
* @param b - unsigned int32 value
* @returns - result of unsigned integer multiplication
*/
function multiply_uint32(a: number, b: number): number {
let n = a;
let m = b;
n >>>= 0;
m >>>= 0;
const nlo = n & 0xffff;
return (((n - nlo) * m >>> 0) + (nlo * m)) >>> 0;
}
/**
* Helper function to convert base64 encoding to url friendly format
*
* @param base64 - Base64 string
*
* @returns Url-friendly base64 encoding.
*/
const toUrlBase64 = (base64: string): string => base64.replace(/\+/g, "-").replace(/\//g, "_").split("=")[0];
/**
* Helper function to recover padding of base64 encoding
*
* @param x - Base64 string
*
* @returns Padded base64 encoding.
*/
const toPaddedBase64 = function(x: string): string {
let base64 = x;
const padLength = 4 - base64.length % 4;
base64 += "=".repeat(padLength);
return base64;
};
/**
* Helper function to create a guid string from an array with 32Bit values
*
* @param in_guidArray - Array with the 32 bit values
* @param base64 - Use base64 encoding instead of standart guids
*
* @returns The guid
*/
const uint32x4ToGUID = function(in_guidArray: Uint32Array | Int32Array | number[], base64: boolean = false): string {
if (base64) {
const intArray = new Uint32Array(in_guidArray);
const byteArray = new Uint8Array(intArray.buffer);
const base64guid = base64js.fromByteArray(byteArray);
// return url-friendly base64
return toUrlBase64(base64guid);
} else {
// Convert to hexadecimal string
let str = "";
for (let i = 0; i < 4; i++) {
const hex = in_guidArray[i].toString(16);
str += ("0".repeat(8 - hex.length) + hex);
}
// eslint-disable-next-line max-len
return `${str.substr(0, 8)}-${str.substr(8, 4)}-${str.substr(12, 4)}-${str.substr(16, 4)}-${str.substr(20, 12)}`;
}
};
/**
* Convert guid to four 32Bit values.
*
* @param in_guid - The guid to convert
* @param io_result - An optional array to write the result to;
* If no array is given, a new one gets created
* @returns Four 32-bit values
*
*/
const guidToUint32x4 = function(in_guid: string, result: Uint32Array = new Uint32Array(4)): Uint32Array {
if (isBase64(in_guid)) {
const guid = toPaddedBase64(in_guid);
const bytes = base64js.toByteArray(guid);
const intArray = new Uint32Array(bytes.buffer);
result.set(intArray);
} else {
result[0] = parseInt(`0x${in_guid.substr(0, 8)}`, 16);
result[1] = parseInt(`0x${in_guid.substr(9, 4)}${in_guid.substr(14, 4)}`, 16);
result[2] = parseInt(`0x${in_guid.substr(19, 4)}${in_guid.substr(24, 4)}`, 16);
result[3] = parseInt(`0x${in_guid.substr(28, 8)}`, 16);
}
return result;
};
/**
* Convert base64 guid into base16.
*
* @param in_guid - Base64 guid to convert
* @returns Base16 guid
*
*/
const base64Tobase16 = (in_guid: string) => uint32x4ToGUID(guidToUint32x4(in_guid));
/**
* Convert base16 into base64 guid.
*
* @param in_guid - Base16 guid to convert
* @returns Base64 guid
*
*/
const base16ToBase64 = (in_guid: string) => uint32x4ToGUID(guidToUint32x4(in_guid), true);
/**
* Based on the boolean parameter generate either
* a 128 bit base16 guid with the following format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx
* or url-friendly base64 string guid of length 22
*
* This function is *not* thread safe!
*
* @param base64 - Use base64 encoding instead of standart guids
*
* @returns The guid
*/
const generateGUID = function(base64 = false): string {
const rnds = new Uint32Array(4);
// Random numbers for guid (4x32 bit)
rnds[0] = guidRNG.genRandUInt32();
rnds[1] = guidRNG.genRandUInt32();
rnds[2] = guidRNG.genRandUInt32();
rnds[3] = guidRNG.genRandUInt32();
return uint32x4ToGUID(rnds, base64);
};
// The last character is checked this way because last 4 bits of 22nd character are ignored
// by decoder, e.g. "+Q" and "+Z" result in the same decoding.
// The only characters with last 4 bits set to 0 are A, Q, g, w.
const reBase64 = (/^[\w-]{21}[AQgw]$/);
// eslint-disable-next-line unicorn/no-unsafe-regex
const reBase16 = (/^[\dA-Fa-f]{8}(?:-[\dA-Fa-f]{4}){3}-[\dA-Fa-f]{12}$/);
/**
* Routine used to check whether the given string is a valid guid
*
* @param in_guid - The guid to test.
* @returns True if the parameter is a valid guid, false otherwise.
*/
const isGUID = (in_guid: string) => reBase16.test(in_guid) || reBase64.test(in_guid);
/**
* Performs a hash combination operation on the two supplied Uint32 arrays of length 4 (using
* a variant of the algorithm from boost::hash_combine
*
* @param in_array1 - First array
* @param in_array2 - Second array
* @returns New combined hash
*/
const hashCombine4xUint32 = function(
in_array1: Uint32Array,
in_array2: Uint32Array,
io_result?: Uint32Array,
): Uint32Array {
let accumulated = io_result;
if (accumulated === undefined) {
accumulated = new Uint32Array(in_array2);
} else {
accumulated[0] = in_array2[0];
accumulated[1] = in_array2[1];
accumulated[2] = in_array2[2];
accumulated[3] = in_array2[3];
}
accumulated[0] += 0x9e3779b9;
accumulated[1] += 0x638f227;
accumulated[2] += 0x1aff2bad;
accumulated[3] += 0x3a8f05c5;
accumulated[0] += in_array1[3] << 6;
accumulated[1] += in_array1[0] << 6;
accumulated[2] += in_array1[1] << 6;
accumulated[3] += in_array1[2] << 6;
accumulated[0] += in_array1[2] >> 2;
accumulated[1] += in_array1[3] >> 2;
accumulated[2] += in_array1[0] >> 2;
accumulated[3] += in_array1[1] >> 2;
accumulated[0] = ((accumulated[0] ^ in_array1[1]) * UINT_32HASH_PRIME) >>> 0;
accumulated[1] = ((accumulated[1] ^ in_array1[2]) * UINT_32HASH_PRIME) >>> 0;
accumulated[2] = ((accumulated[2] ^ in_array1[3]) * UINT_32HASH_PRIME) >>> 0;
accumulated[3] = ((accumulated[3] ^ in_array1[0]) * UINT_32HASH_PRIME) >>> 0;
return accumulated;
};
/**
* Takes two guids and generates a new derived guid.
* Note: You should only use this helper function when you need only one combination.
* Otherwise, it is more efficient to work on the uint8 arrays directly.
*
* @param in_guid1 - Input guid
* @param in_guid2 - Input guid
* @param base64 - Use base64 encoding instead of standart guids
* @returns Combined guid
*/
const combineGuids = function(in_guid1: string, in_guid2: string, base64 = false): string {
const firstArray = guidToUint32x4(in_guid1);
const secondArray = guidToUint32x4(in_guid2);
const combined = hashCombine4xUint32(firstArray, secondArray);
return uint32x4ToGUID(combined, base64);
};
// Make sure the RNG is initialized
guidRNG.initialize();
const initializeGUIDGenerator = (...args) => { guidRNG.initialize(...args); };
export const GuidUtils = {
uint32x4ToGUID,
guidToUint32x4,
base64Tobase16,
base16ToBase64,
initializeGUIDGenerator,
generateGUID,
isGUID,
combineGuids,
hashCombine4xUint32,
}; | the_stack |
import { UrbanBot, UrbanMessage, UrbanSyntheticEvent, UrbanParseMode } from '@urban-bot/core';
import express from 'express';
import bodyParser from 'body-parser';
import crypto from 'crypto';
import { GraphAPI } from './GraphAPI';
import { FacebookMessageMeta, FacebookPayload } from './types';
import { formatGenericTemplate, formatReplyButtons } from './format';
const { urlencoded, json } = bodyParser;
export type FACEBOOK = 'FACEBOOK';
export type UrbanNativeEventFacebook<Payload = FacebookPayload> = {
type: FACEBOOK;
payload?: Payload;
};
export type UrbanBotFacebookType<Payload = FacebookPayload> = {
NativeEvent: UrbanNativeEventFacebook<Payload>;
MessageMeta: FacebookMessageMeta;
};
export type FacebookOptions = {
pageAccessToken: string;
// Your App secret can be found in App Dashboard -> Settings -> Basic
appSecret: string;
// A random string that is used for the webhook verification request
verifyToken: string;
pageId?: string;
appId?: string;
// URL where you host this code
webhookUrl?: string;
apiUrl?: string;
apiUrlVersion?: string;
pathnamePrefix?: string;
};
const defaultOptions: Partial<FacebookOptions> = {
apiUrl: 'https://graph.facebook.com',
apiUrlVersion: 'v3.2',
};
export class UrbanBotFacebook implements UrbanBot<UrbanBotFacebookType> {
static TYPE: FACEBOOK = 'FACEBOOK';
type: FACEBOOK = UrbanBotFacebook.TYPE;
defaultParseMode: UrbanParseMode = 'markdown';
commandPrefix = '/';
client: GraphAPI;
options: FacebookOptions;
constructor(options: FacebookOptions) {
if (!('pageAccessToken' in options)) {
throw new Error(`Provide pageAccessToken to @urban-bot/facebook options`);
}
if (!('appSecret' in options)) {
throw new Error(`Provide appSecret to @urban-bot/facebook options`);
}
this.options = { ...defaultOptions, ...options };
this.client = new GraphAPI(this.options);
}
initializeServer(expressApp: express.Express) {
const pathnamePrefix = this.options.pathnamePrefix ?? '';
expressApp.use(
`${pathnamePrefix}/facebook/*`,
urlencoded({
extended: true,
}),
);
expressApp.use(`${pathnamePrefix}/facebook/*`, json({ verify: this.verifyRequestSignature }));
expressApp.get(`${pathnamePrefix}/facebook/webhook`, (req, res) => {
const mode = req.query?.['hub.mode'];
const token = req.query?.['hub.verify_token'];
const challenge = req.query?.['hub.challenge'];
if (mode && token) {
if (mode === 'subscribe' && token === this.options.verifyToken) {
console.log('webhook verified');
res.status(200).send(challenge);
} else {
console.error('webhook not verified');
res.sendStatus(403);
}
}
});
expressApp.post('/facebook/webhook', (req, res) => {
const payload = req.body as FacebookPayload;
this.handleEvent(payload);
res.sendStatus(200);
});
if (this.options.pageId !== undefined) {
console.log('Test your app by messaging:');
console.log('https://m.me/' + this.options.pageId);
}
}
processUpdate(_event: UrbanSyntheticEvent<UrbanBotFacebookType>) {
throw new Error('this method must be overridden');
}
handleEvent(payload: FacebookPayload) {
const { message, sender, postback } = payload.entry[0].messaging[0];
const { id } = sender;
const common = {
chat: { id },
nativeEvent: {
type: UrbanBotFacebook.TYPE,
payload,
},
from: { id },
} as const;
if (postback) {
this.processUpdate({
...common,
type: 'action',
payload: {
actionId: postback.payload,
},
});
return;
}
if (message) {
const { text, attachments } = message;
if (attachments) {
const files = attachments.map(({ type, payload }) => ({
type,
...payload,
}));
const fileEvent = {
...common,
payload: {
text,
files,
},
} as const;
const isAllImages = files.every(({ type }) => type === 'image');
const isAllVideo = files.every(({ type }) => type === 'video');
const isAllAudio = files.every(({ type }) => type === 'audio');
if (isAllImages) {
this.processUpdate({
type: 'image',
...fileEvent,
});
} else if (isAllVideo) {
this.processUpdate({
type: 'video',
...fileEvent,
});
} else if (isAllAudio) {
this.processUpdate({
type: 'audio',
...fileEvent,
});
} else {
this.processUpdate({
...fileEvent,
type: 'file',
});
}
} else {
if (text !== undefined) {
if (text[0] === this.commandPrefix) {
const [command, ...args] = text.split(' ');
this.processUpdate({
...common,
type: 'command',
payload: { command, argument: args.join(' ') },
});
} else {
this.processUpdate({
...common,
type: 'text',
payload: { text },
});
}
}
}
}
}
async sendMessage(message: UrbanMessage): Promise<FacebookMessageMeta> {
const common = {
recipient: {
id: message.chat.id,
},
tag: message.data.tag,
persona_id: message.data.personaId,
} as const;
switch (message.nodeName) {
case 'urban-text': {
const requestBody = {
...common,
message: { text: message.data.text },
};
return this.client.callSendAPI(requestBody);
}
case 'urban-buttons': {
let requestBody;
if (message.data.isReplyButtons) {
requestBody = {
...common,
message: {
text: message.data.title,
quick_replies: formatReplyButtons(message.data.buttons),
},
};
} else {
const subtitle = typeof message.data.subtitle === 'string' ? message.data.subtitle : undefined;
requestBody = {
...common,
message: {
attachment: formatGenericTemplate({
title: message.data.title,
subtitle,
buttons: message.data.buttons,
}),
},
};
}
return this.client.callSendAPI(requestBody);
}
case 'urban-img': {
if (typeof message.data.file !== 'string') {
// TODO add file from file system support
throw new Error('@urban-bot/facebook support image file only as string');
}
if (message.data.isReplyButtons) {
throw new Error("@urban-bot/facebook Don't use isReplyButtons with Image component");
}
const subtitle = typeof message.data.subtitle === 'string' ? message.data.subtitle : undefined;
const requestBody = {
...common,
message: {
attachment: formatGenericTemplate({
title: message.data.title,
subtitle,
buttons: message.data.buttons,
image_url: message.data.file,
}),
},
};
return this.client.callSendAPI(requestBody);
}
case 'urban-audio': {
if (typeof message.data.file !== 'string') {
throw new Error('@urban-bot/facebook support audio file only as string');
}
const requestBody = {
...common,
message: {
attachment: {
type: 'audio',
payload: {
url: message.data.file,
is_reusable: message.data.is_reusable,
},
},
},
};
return this.client.callSendAPI(requestBody);
}
case 'urban-video': {
if (typeof message.data.file !== 'string') {
throw new Error('@urban-bot/facebook support video file only as string');
}
const requestBody = {
...common,
message: {
attachment: {
type: 'video',
payload: {
url: message.data.file,
is_reusable: message.data.is_reusable,
},
},
},
};
return this.client.callSendAPI(requestBody);
}
case 'urban-file': {
if (typeof message.data.file !== 'string') {
throw new Error('@urban-bot/facebook support file only as string');
}
const requestBody = {
...common,
message: {
attachment: {
type: 'file',
payload: {
url: message.data.file,
is_reusable: message.data.is_reusable,
},
},
},
};
return this.client.callSendAPI(requestBody);
}
default: {
throw new Error(
`Tag '${
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(message as any).nodeName
}' is not supported. Please don't use it with facebook bot or add this logic to @urban-bot/facebook.`,
);
}
}
}
verifyRequestSignature = (req: any, _res: any, buf: any) => {
const signature = req?.headers['x-hub-signature'];
if (!signature) {
console.error("Couldn't validate the signature.");
} else {
const elements = signature.split('=');
const signatureHash = elements[1];
const expectedHash = crypto.createHmac('sha1', this.options.appSecret).update(buf).digest('hex');
if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
};
} | the_stack |
import * as React from 'react'
import {
Icon,
Box,
Btn,
Flex,
PrimaryBtn,
Text,
Link,
SPACING_1,
SPACING_2,
SPACING_3,
SPACING_4,
SPACING_5,
ALIGN_CENTER,
ALIGN_STRETCH,
C_BLUE,
COLOR_SUCCESS,
COLOR_WARNING,
OVERLAY_LIGHT_GRAY_50,
FONT_HEADER_DARK,
FONT_SIZE_BODY_2,
FONT_SIZE_BODY_1,
FONT_WEIGHT_SEMIBOLD,
JUSTIFY_CENTER,
JUSTIFY_SPACE_BETWEEN,
JUSTIFY_START,
TEXT_TRANSFORM_CAPITALIZE,
TEXT_TRANSFORM_UPPERCASE,
FONT_STYLE_ITALIC,
DIRECTION_COLUMN,
DISPLAY_INLINE_BLOCK,
} from '@opentrons/components'
import { getPipetteModelSpecs } from '@opentrons/shared-data'
import find from 'lodash/find'
import { PIPETTE_MOUNTS, LEFT, RIGHT } from '../../redux/pipettes'
import { saveAs } from 'file-saver'
import type { Mount } from '../../redux/pipettes/types'
import type { CalibrationPanelProps } from '../../organisms/CalibrationPanels/types'
import {
CHECK_STATUS_OUTSIDE_THRESHOLD,
CHECK_STATUS_IN_THRESHOLD,
} from '../../redux/sessions'
import type {
CalibrationCheckInstrument,
CalibrationCheckComparisonsPerCalibration,
} from '../../redux/sessions/types'
const GOOD_CALIBRATION = 'Good calibration'
const BAD_CALIBRATION = 'Recalibration recommended'
const ROBOT_CALIBRATION_CHECK_SUMMARY_HEADER =
'calibration health check results'
const DECK_CALIBRATION_HEADER = 'robot deck calibration'
const MOUNT = 'mount'
const HOME_AND_EXIT = 'Home robot and exit'
const DOWNLOAD_SUMMARY = 'Download detailed JSON Calibration Check summary'
const PIPETTE_OFFSET_CALIBRATION_HEADER = 'pipette offset calibration'
const TIP_LENGTH_CALIBRATION_HEADER = 'tip length calibration'
const NEED_HELP = 'If problems persist,'
const CONTACT_SUPPORT = 'contact Opentrons support'
const FOR_HELP = 'for help'
const SUPPORT_URL = 'https://support.opentrons.com'
const FOUND = 'Health check found'
const ONE_ISSUE = 'an issue'
const PLURAL_ISSUES = 'issues'
const RECALIBRATE_AS_INDICATED =
'Redo the calibrations indicated below to troubleshoot'
const NOTE = 'Note'
const DO_DECK_FIRST = 'Recalibrate your deck before redoing other calibrations.'
const DECK_INVALIDATES =
'Recalibrating your deck will invalidate Pipette Offsets, and you will need to recalibrate Pipette Offsets after redoing Deck Calibration.'
const NO_PIPETTE = 'No pipette attached'
export function ResultsSummary(
props: CalibrationPanelProps
): JSX.Element | null {
const {
comparisonsByPipette,
instruments,
checkBothPipettes,
cleanUpAndExit,
} = props
if (!comparisonsByPipette || !instruments) {
return null
}
const handleDownloadButtonClick = (): void => {
const now = new Date()
const report = {
comparisonsByPipette,
instruments,
savedAt: now.toISOString(),
}
const data = new Blob([JSON.stringify(report, null, 4)], {
type: 'application/json',
})
saveAs(data, 'OT-2 Robot Calibration Check Report.json')
}
const leftPipette = find(
instruments,
(p: CalibrationCheckInstrument) => p.mount.toLowerCase() === LEFT
)
const rightPipette = find(
instruments,
(p: CalibrationCheckInstrument) => p.mount.toLowerCase() === RIGHT
)
type CalibrationByMount = {
[m in Mount]: {
pipette: CalibrationCheckInstrument | undefined
calibration: CalibrationCheckComparisonsPerCalibration | null
}
}
const calibrationsByMount: CalibrationByMount = {
left: {
pipette: leftPipette,
calibration: leftPipette
? comparisonsByPipette?.[leftPipette.rank] ?? null
: null,
},
right: {
pipette: rightPipette,
calibration: rightPipette
? comparisonsByPipette?.[rightPipette.rank] ?? null
: null,
},
}
const getDeckCalibration = checkBothPipettes
? comparisonsByPipette.second.deck?.status
: comparisonsByPipette.first.deck?.status
const deckCalibrationResult = getDeckCalibration ?? null
const pipetteResultsBad = (
perPipette: CalibrationCheckComparisonsPerCalibration | null
): { offsetBad: boolean; tipLengthBad: boolean } => ({
offsetBad: perPipette?.pipetteOffset?.status
? perPipette.pipetteOffset.status === CHECK_STATUS_OUTSIDE_THRESHOLD
: false,
tipLengthBad: perPipette?.tipLength?.status
? perPipette.tipLength.status === CHECK_STATUS_OUTSIDE_THRESHOLD
: false,
})
return (
<>
<Flex
width="100%"
justifyContent={JUSTIFY_START}
flexDirection={DIRECTION_COLUMN}
>
<Text
css={FONT_HEADER_DARK}
marginTop={SPACING_2}
textTransform={TEXT_TRANSFORM_CAPITALIZE}
>
{ROBOT_CALIBRATION_CHECK_SUMMARY_HEADER}
</Text>
<Box
minHeight={SPACING_2}
marginBottom={SPACING_3}
title="results-note-container"
>
<WarningText
deckCalibrationBad={
deckCalibrationResult
? deckCalibrationResult === CHECK_STATUS_OUTSIDE_THRESHOLD
: false
}
pipettes={{
left: pipetteResultsBad(calibrationsByMount.left.calibration),
right: pipetteResultsBad(calibrationsByMount.right.calibration),
}}
/>
</Box>
</Flex>
<Flex
marginBottom={SPACING_4}
title="deck-calibration-container"
flexDirection={DIRECTION_COLUMN}
>
<Text
marginBottom={SPACING_2}
textTransform={TEXT_TRANSFORM_CAPITALIZE}
fontWeight={FONT_WEIGHT_SEMIBOLD}
fontSize={FONT_SIZE_BODY_2}
>
{DECK_CALIBRATION_HEADER}
</Text>
<RenderResult status={deckCalibrationResult} />
</Flex>
<Flex marginBottom={SPACING_2} justifyContent={JUSTIFY_SPACE_BETWEEN}>
{PIPETTE_MOUNTS.map(m => (
<Box key={m} width="48%" title={`${m}-mount-container`}>
<Text
textTransform={TEXT_TRANSFORM_UPPERCASE}
fontSize={FONT_SIZE_BODY_2}
fontWeight={FONT_WEIGHT_SEMIBOLD}
marginBottom={SPACING_2}
>
{`${m} ${MOUNT}`}
</Text>
<Flex
backgroundColor={OVERLAY_LIGHT_GRAY_50}
padding={SPACING_2}
title={`${m}-mount-results`}
alignItems={ALIGN_STRETCH}
>
{calibrationsByMount[m].pipette &&
calibrationsByMount[m].calibration &&
// @ts-expect-error TODO: ts can't narrow that this isn't nullish
Object.entries(calibrationsByMount[m].calibration).length ? (
<PipetteResult
// @ts-expect-error TODO: ts can't narrow that this isn't nullish
pipetteInfo={calibrationsByMount[m].pipette}
// @ts-expect-error TODO: ts can't narrow that this isn't nullish
pipetteCalibration={calibrationsByMount[m].calibration}
/>
) : (
<Flex
alignItems={ALIGN_CENTER}
justifyContent={JUSTIFY_CENTER}
fontStyle={FONT_STYLE_ITALIC}
fontSize={FONT_SIZE_BODY_1}
flexDirection={DIRECTION_COLUMN}
height="100%"
>
{NO_PIPETTE}
</Flex>
)}
</Flex>
</Box>
))}
</Flex>
<Box>
<Btn
color={C_BLUE}
onClick={handleDownloadButtonClick}
marginBottom={SPACING_5}
fontSize={FONT_SIZE_BODY_2}
title="download-results-button"
>
{DOWNLOAD_SUMMARY}
</Btn>
<Flex
marginTop={SPACING_4}
marginBottom={SPACING_2}
justifyContent={JUSTIFY_CENTER}
>
<PrimaryBtn width="95%" onClick={cleanUpAndExit}>
{HOME_AND_EXIT}
</PrimaryBtn>
</Flex>
</Box>
</>
)
}
interface RenderResultProps {
status: string | null
}
function RenderResult(props: RenderResultProps): JSX.Element | null {
const { status } = props
if (!status) {
return null
} else {
const isGoodCal = status === CHECK_STATUS_IN_THRESHOLD
return (
<Flex>
<Icon
name={isGoodCal ? 'check-circle' : 'alert-circle'}
height="1.25rem"
width="1.25rem"
color={isGoodCal ? COLOR_SUCCESS : COLOR_WARNING}
marginRight="0.75rem"
/>
<Text fontSize={FONT_SIZE_BODY_2}>
{isGoodCal ? GOOD_CALIBRATION : BAD_CALIBRATION}
</Text>
</Flex>
)
}
}
interface PipetteResultProps {
pipetteInfo: CalibrationCheckInstrument
pipetteCalibration: CalibrationCheckComparisonsPerCalibration
}
function PipetteResult(props: PipetteResultProps): JSX.Element {
const { pipetteInfo, pipetteCalibration } = props
const displayName =
getPipetteModelSpecs(pipetteInfo.model)?.displayName || pipetteInfo.model
const tipRackDisplayName = pipetteInfo.tipRackDisplay
return (
<Flex paddingY={SPACING_1} flexDirection={DIRECTION_COLUMN} height="100%">
<Box>
<Text
fontSize={FONT_SIZE_BODY_2}
fontWeight={FONT_WEIGHT_SEMIBOLD}
marginBottom={SPACING_1}
textTransform={TEXT_TRANSFORM_CAPITALIZE}
>
{PIPETTE_OFFSET_CALIBRATION_HEADER}
</Text>
<Text fontSize={FONT_SIZE_BODY_1} marginBottom={SPACING_2}>
{displayName}
</Text>
<RenderResult
status={pipetteCalibration.pipetteOffset?.status ?? null}
/>
</Box>
<Box marginTop={SPACING_4}>
<Text
fontSize={FONT_SIZE_BODY_2}
fontWeight={FONT_WEIGHT_SEMIBOLD}
marginBottom={SPACING_1}
textTransform={TEXT_TRANSFORM_CAPITALIZE}
>
{TIP_LENGTH_CALIBRATION_HEADER}
</Text>
<Text fontSize={FONT_SIZE_BODY_1} marginBottom={SPACING_2}>
{tipRackDisplayName}
</Text>
<RenderResult status={pipetteCalibration.tipLength?.status ?? null} />
</Box>
</Flex>
)
}
function WarningText(props: {
deckCalibrationBad: boolean
pipettes: {
left: { offsetBad: boolean; tipLengthBad: boolean }
right: { offsetBad: boolean; tipLengthBad: boolean }
}
}): JSX.Element | null {
const badCount = [
props.deckCalibrationBad,
props.pipettes.left.offsetBad,
props.pipettes.left.tipLengthBad,
props.pipettes.right.offsetBad,
props.pipettes.right.tipLengthBad,
].reduce((sum, item) => sum + (item === true ? 1 : 0), 0)
return badCount > 0 ? (
<>
<Box marginTop={SPACING_3} fontSize={FONT_SIZE_BODY_2}>
<Text display={DISPLAY_INLINE_BLOCK}>
{`${FOUND}`}
{badCount === 1 ? ONE_ISSUE : PLURAL_ISSUES}.
{`${RECALIBRATE_AS_INDICATED}.`}
</Text>
<Text display={DISPLAY_INLINE_BLOCK}>{NEED_HELP}</Text>
<Link
display={DISPLAY_INLINE_BLOCK}
color={C_BLUE}
external={true}
href={SUPPORT_URL}
>
{CONTACT_SUPPORT}
</Link>
<Text display={DISPLAY_INLINE_BLOCK}>{`${FOR_HELP}.`}</Text>
</Box>
{props.deckCalibrationBad ? (
<Text
fontSize={FONT_SIZE_BODY_1}
marginTop={SPACING_2}
fontStyle={FONT_STYLE_ITALIC}
>{`${NOTE}: ${
badCount > 1 ? DO_DECK_FIRST : ''
} ${DECK_INVALIDATES}`}</Text>
) : null}
</>
) : null
} | the_stack |
module formFor {
/**
* Model validation service.
*/
export class ModelValidator {
private $interpolate_:ng.IInterpolateService;
private formForConfiguration_:FormForConfiguration;
private nestedObjectHelper_:NestedObjectHelper;
private promiseUtils_:PromiseUtils;
/**
* Constructor.
*
* @param $interpolate Injector-supplied $interpolate service
* @param $parse Injecter-supplied $parse service
* @param $q Injector-supplied $q service
* @param formForConfiguration
*/
constructor($interpolate:ng.IInterpolateService,
$parse:ng.IParseService,
$q:ng.IQService,
formForConfiguration:FormForConfiguration) {
this.$interpolate_ = $interpolate;
this.formForConfiguration_ = formForConfiguration;
this.nestedObjectHelper_ = new NestedObjectHelper($parse);
this.promiseUtils_ = new PromiseUtils($q);
}
/**
* Determines if the specified collection is required (requires a minimum number of items).
*
* @param fieldName Name of field containing the collection.
* @param validationRuleSet Map of field names to validation rules
*/
public isCollectionRequired(fieldName:string, validationRuleSet:ValidationRuleSet):boolean {
var validationRules:ValidationRules = this.getRulesForField(fieldName, validationRuleSet);
if (validationRules &&
validationRules.collection &&
validationRules.collection.min) {
if (angular.isObject(validationRules.collection.min)) {
return (<ValidationRuleNumber> validationRules.collection.min).rule > 0;
} else {
return validationRules.collection.min > 0;
}
}
return false;
}
/**
* Determines if the specified field is flagged as required.
*
* @param fieldName Name of field in question.
* @param validationRuleSet Map of field names to validation rules
*/
public isFieldRequired(fieldName:string, validationRuleSet:ValidationRuleSet):boolean {
var validationRules:ValidationRules = this.getRulesForField(fieldName, validationRuleSet);
if (validationRules && validationRules.required) {
if (angular.isObject(validationRules.required)) {
return (<ValidationRuleBoolean> validationRules.required).rule;
} else {
return !!validationRules.required;
}
}
return false;
}
/**
* Validates the model against all rules in the validationRules.
* This method returns a promise to be resolved on successful validation,
* or rejected with a map of field-name to error-message.
*
* @param formData Form-data object model is contained within
* @param validationRuleSet Map of field names to validation rules
* @return Promise to be resolved or rejected based on validation success or failure.
*/
public validateAll(formData:Object, validationRuleSet:ValidationRuleSet):ng.IPromise<string> {
var fieldNames:Array<string> = this.nestedObjectHelper_.flattenObjectKeys(formData);
return this.validateFields(formData, fieldNames, validationRuleSet);
}
/**
* Validate the properties of a collection (but not the items within the collection).
* This method returns a promise to be resolved on successful validation or rejected with an error message.
*
* @param formData Form-data object model is contained within
* @param fieldName Name of collection to validate
* @param validationRuleSet Map of field names to validation rules
* @return Promise to be resolved or rejected based on validation success or failure.
*/
public validateCollection(formData:Object, fieldName:string, validationRuleSet:ValidationRuleSet):ng.IPromise<any> {
var validationRules:ValidationRules = this.getRulesForField(fieldName, validationRuleSet);
var collection:Array<any> = this.nestedObjectHelper_.readAttribute(formData, fieldName);
if (validationRules && validationRules.collection) {
collection = collection || [];
return this.validateCollectionMinLength_(collection, validationRules.collection) ||
this.validateCollectionMaxLength_(collection, validationRules.collection) ||
this.promiseUtils_.resolve();
}
return this.promiseUtils_.resolve();
}
/**
* Validates a value against the related rule-set (within validationRules).
* This method returns a promise to be resolved on successful validation.
* If validation fails the promise will be rejected with an error message.
*
* @param formData Form-data object model is contained within.
* @param fieldName Name of field used to associate the rule-set map with a given value.
* @param validationRuleSet Map of field names to validation rules
* @return Promise to be resolved or rejected based on validation success or failure.
*/
public validateField(formData:Object, fieldName:string, validationRuleSet:ValidationRuleSet):ng.IPromise<any> {
var validationRules:ValidationRules = this.getRulesForField(fieldName, validationRuleSet);
var value:any = this.nestedObjectHelper_.readAttribute(formData, fieldName);
if (validationRules) {
if (value === undefined || value === null) {
value = ""; // Escape falsy values liked null or undefined, but not ones like 0
}
return this.validateFieldRequired_(value, validationRules, formData, fieldName) ||
this.validateFieldMinimum_(value, validationRules) ||
this.validateFieldMinLength_(value, validationRules) ||
this.validateFieldIncrement_(value, validationRules) ||
this.validateFieldMaximum_(value, validationRules) ||
this.validateFieldMaxLength_(value, validationRules) ||
this.validateFieldType_(value, validationRules) ||
this.validateFieldPattern_(value, validationRules) ||
this.validateFieldCustom_(value, formData, validationRules, fieldName) ||
this.promiseUtils_.resolve();
}
return this.promiseUtils_.resolve();
}
/**
* Validates the values in model with the rules defined in the current validationRules.
* This method returns a promise to be resolved on successful validation,
* or rejected with a map of field-name to error-message.
*
* @param formData Form-data object model is contained within
* @param fieldNames White-list set of fields to validate for the given model.
* Values outside of this list will be ignored.
* @param validationRuleSet Map of field names to validation rules
* @return Promise to be resolved or rejected based on validation success or failure.
*/
public validateFields(formData:Object, fieldNames:Array<string>, validationRuleSet:ValidationRuleSet):ng.IPromise<any> {
var deferred:ng.IDeferred<any> = this.promiseUtils_.defer();
var promises:Array<ng.IPromise<any>> = [];
var errorMap:ValidationErrorMap = {};
angular.forEach(fieldNames, (fieldName:string) => {
var validationRules:ValidationRules = this.getRulesForField(fieldName, validationRuleSet);
if (validationRules) {
var promise:ng.IPromise<any>;
if (validationRules.collection) {
promise = this.validateCollection(formData, fieldName, validationRuleSet);
} else {
promise = this.validateField(formData, fieldName, validationRuleSet);
}
promise.then(
angular.noop,
(error) => {
this.nestedObjectHelper_.writeAttribute(errorMap, fieldName, error);
});
promises.push(promise);
}
}, this);
// Wait until all validations have finished before proceeding; bundle up the error messages if any failed.
this.promiseUtils_.waitForAll(promises).then(
deferred.resolve,
() => {
deferred.reject(errorMap);
});
return deferred.promise;
}
// Helper methods ////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Strip array brackets from field names so that model values can be mapped to rules.
* e.g. "foo[0].bar" should be validated against "foo.collection.fields.bar"
*/
public getRulesForField(fieldName:string, validationRuleSet:ValidationRuleSet):ValidationRules {
var expandedFieldName:string = fieldName.replace(/\[[^\]]+\]/g, '.collection.fields');
return this.nestedObjectHelper_.readAttribute(validationRuleSet, expandedFieldName);
}
private getFieldTypeFailureMessage_(validationRules:ValidationRules, failureType:ValidationFailureType):string {
return angular.isObject(validationRules.type) ?
(<ValidationRuleFieldType> validationRules.type).message :
this.formForConfiguration_.getFailedValidationMessage(failureType);
}
/**
* Determining if numeric input has been provided.
* This guards against the fact that `new Number('') == 0`.
* @private
*/
private static isConsideredNumeric_(stringValue:string, numericValue:number):boolean {
return stringValue && !isNaN(numericValue);
}
// Validation helper methods /////////////////////////////////////////////////////////////////////////////////////////
private validateCollectionMinLength_(collection:any, validationRuleCollection:ValidationRuleCollection):any {
if (validationRuleCollection.min) {
var min:number =
angular.isObject(validationRuleCollection.min) ?
(<ValidationRuleNumber> validationRuleCollection.min).rule :
<number> validationRuleCollection.min;
if (collection.length < min) {
var failureMessage:string;
if (angular.isObject(validationRuleCollection.min)) {
failureMessage = (<ValidationRuleNumber> validationRuleCollection.min).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.COLLECTION_MIN_SIZE))({num: min});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateCollectionMaxLength_(collection:any, validationRuleCollection:ValidationRuleCollection):any {
if (validationRuleCollection.max) {
var max:number =
angular.isObject(validationRuleCollection.max) ?
(<ValidationRuleNumber> validationRuleCollection.max).rule :
<number> validationRuleCollection.max;
if (collection.length > max) {
var failureMessage:string;
if (angular.isObject(validationRuleCollection.max)) {
failureMessage = (<ValidationRuleNumber> validationRuleCollection.max).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.COLLECTION_MAX_SIZE))({num: max});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldCustom_(value:any, formData:any, validationRules:ValidationRules, fieldName:any):any {
if (validationRules.custom) {
var defaultErrorMessage:string;
var validationFunction:CustomValidationFunction;
if (angular.isFunction(validationRules.custom)) {
defaultErrorMessage = this.formForConfiguration_.getFailedValidationMessage(ValidationFailureType.CUSTOM);
validationFunction = <(value:any, formData:any, fieldName:any) => boolean> validationRules.custom;
} else {
defaultErrorMessage = (<ValidationRuleCustom> validationRules.custom).message;
validationFunction = (<ValidationRuleCustom> validationRules.custom).rule;
}
// Validations can fail in 3 ways:
// A promise that gets rejected (potentially with an error message)
// An error that gets thrown (potentially with a message)
// A falsy value
try {
var returnValue:any = validationFunction(value, formData, fieldName);
} catch (error) {
return this.promiseUtils_.reject(error.message || defaultErrorMessage);
}
if (angular.isObject(returnValue) && angular.isFunction(returnValue.then)) {
return returnValue.then(
(reason:any) => {
return this.promiseUtils_.resolve(reason);
},
(reason:any) => {
return this.promiseUtils_.reject(reason || defaultErrorMessage);
});
} else if (returnValue) {
return this.promiseUtils_.resolve(returnValue);
} else {
return this.promiseUtils_.reject(defaultErrorMessage);
}
}
return null;
}
private validateFieldIncrement_(value:any, validationRules:ValidationRules):any {
if (validationRules.increment) {
var stringValue:string = value.toString();
var numericValue:number = Number(value);
var increment:number = angular.isObject(validationRules.increment)
? (<ValidationRuleNumber> validationRules.increment).rule
: angular.isFunction(validationRules.increment)
? validationRules.increment.call(this, value)
: <number> validationRules.increment;
if (stringValue && !isNaN(numericValue)) {
// Convert floating point values to integers before comparing to avoid rounding errors
if (validationRules.increment < 1) {
let ratio = validationRules.increment / 1;
numericValue /= ratio;
increment /= ratio;
}
if (numericValue % increment > 0) {
var failureMessage:string;
if (angular.isObject(validationRules.increment)) {
failureMessage = (<ValidationRuleNumber> validationRules.increment).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.INCREMENT))({num: increment});
}
return this.promiseUtils_.reject(failureMessage);
}
}
}
return null;
}
private validateFieldMaximum_(value:any, validationRules:ValidationRules):any {
if (validationRules.maximum || validationRules.maximum === 0) {
var stringValue:string = value.toString();
var numericValue:number = Number(value);
var maximum:number = angular.isObject(validationRules.maximum)
? (<ValidationRuleNumber> validationRules.maximum).rule
: angular.isFunction(validationRules.maximum)
? validationRules.maximum.call(this, value)
: <number> validationRules.maximum;
if (stringValue && !isNaN(numericValue) && numericValue > maximum) {
var failureMessage:string;
if (angular.isObject(validationRules.maximum)) {
failureMessage = (<ValidationRuleNumber> validationRules.maximum).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.MAXIMUM))({num: maximum});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldMaxLength_(value:any, validationRules:ValidationRules):any {
if (validationRules.maxlength) {
var maxlength:number = angular.isObject(validationRules.maxlength) ?
(<ValidationRuleNumber> validationRules.maxlength).rule :
<number> validationRules.maxlength;
if (value.length > maxlength) {
var failureMessage:string;
if (angular.isObject(validationRules.maxlength)) {
failureMessage = (<ValidationRuleNumber> validationRules.maxlength).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.MAX_LENGTH))({num: maxlength});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldMinimum_(value:any, validationRules:ValidationRules):any {
if (validationRules.minimum || validationRules.minimum === 0) {
var stringValue:string = value.toString();
var numericValue:number = Number(value);
var minimum:number = angular.isObject(validationRules.minimum)
? (<ValidationRuleNumber> validationRules.minimum).rule
: angular.isFunction(validationRules.minimum)
? validationRules.minimum.call(this, value)
: <number> validationRules.minimum;
if (stringValue && !isNaN(numericValue) && numericValue < minimum) {
var failureMessage:string;
if (angular.isObject(validationRules.minimum)) {
failureMessage = (<ValidationRuleNumber> validationRules.minimum).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.MINIMUM))({num: minimum});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldMinLength_(value:any, validationRules:ValidationRules):any {
if (validationRules.minlength) {
var minlength:number = angular.isObject(validationRules.minlength) ?
(<ValidationRuleNumber> validationRules.minlength).rule :
<number> validationRules.minlength;
if (value && value.length < minlength) {
var failureMessage:string;
if (angular.isObject(validationRules.minlength)) {
failureMessage = (<ValidationRuleNumber> validationRules.minlength).message;
} else {
failureMessage =
this.$interpolate_(
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.MIN_LENGTH))({num: minlength});
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldRequired_(value:any, validationRules:ValidationRules, formData:any, fieldName:any):any {
if (validationRules.required) {
var required:boolean = angular.isObject(validationRules.required)
? (<ValidationRuleBoolean> validationRules.required).rule
: angular.isFunction(validationRules.required)
? validationRules.required.apply(this, [value, formData, fieldName])
: <boolean> validationRules.required;
// Compare both string and numeric values to avoid rejecting non-empty but falsy values (e.g. 0).
var stringValue:string = value.toString().replace(/\s+$/, ''); // Disallow an all-whitespace string
var numericValue:number = Number(value);
if (required && !stringValue && !numericValue) {
var failureMessage:string;
if (angular.isObject(validationRules.required)) {
failureMessage = (<ValidationRuleBoolean> validationRules.required).message;
} else {
failureMessage =
this.formForConfiguration_.getFailedValidationMessage(
ValidationFailureType.REQUIRED);
}
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldPattern_(value:any, validationRules:ValidationRules):any {
if (validationRules.pattern) {
var isRegExp:boolean = validationRules.pattern instanceof RegExp;
var regExp:RegExp = isRegExp ?
<RegExp> validationRules.pattern :
(<ValidationRuleRegExp> validationRules.pattern).rule;
if (value && !regExp.exec(value)) {
var failureMessage:string = isRegExp ?
this.formForConfiguration_.getFailedValidationMessage(ValidationFailureType.PATTERN) :
(<ValidationRuleRegExp> validationRules.pattern).message;
return this.promiseUtils_.reject(failureMessage);
}
}
return null;
}
private validateFieldType_(value:any, validationRules:ValidationRules):any {
if (validationRules.type) {
// String containing 0+ ValidationRuleFieldType enums
var typesString:any = angular.isObject(validationRules.type) ?
(<ValidationRuleFieldType> validationRules.type).rule :
validationRules.type;
var stringValue:string = value.toString();
var numericValue:number = Number(value);
if (typesString) {
var types:Array<ValidationFieldType> = typesString.split(' ');
for (var i:number = 0, length:number = types.length; i < length; i++) {
var type:ValidationFieldType = types[i];
switch (type) {
case ValidationFieldType.INTEGER:
if (stringValue && (isNaN(numericValue) || numericValue % 1 !== 0)) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_INTEGER));
}
break;
case ValidationFieldType.NUMBER:
if (stringValue && isNaN(numericValue)) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_NUMERIC));
}
break;
case ValidationFieldType.NEGATIVE:
if (ModelValidator.isConsideredNumeric_(stringValue, numericValue) && numericValue >= 0) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_NEGATIVE));
}
break;
case ValidationFieldType.NON_NEGATIVE:
if (ModelValidator.isConsideredNumeric_(stringValue, numericValue) && numericValue < 0) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_NON_NEGATIVE));
}
break;
case ValidationFieldType.POSITIVE:
if (ModelValidator.isConsideredNumeric_(stringValue, numericValue) && numericValue <= 0) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_POSITIVE));
}
break;
case ValidationFieldType.EMAIL:
if (stringValue && !stringValue.match(/^.+@.+\..+$/)) {
return this.promiseUtils_.reject(
this.getFieldTypeFailureMessage_(validationRules, ValidationFailureType.TYPE_EMAIL));
}
break;
}
}
}
}
return null;
}
}
angular.module('formFor').service('ModelValidator',
($interpolate, $parse, $q, FormForConfiguration) =>
new ModelValidator($interpolate, $parse, $q, FormForConfiguration));
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/experimentsMappers";
import * as Parameters from "../models/parameters";
import { FrontDoorManagementClientContext } from "../frontDoorManagementClientContext";
/** Class representing a Experiments. */
export class Experiments {
private readonly client: FrontDoorManagementClientContext;
/**
* Create a Experiments.
* @param {FrontDoorManagementClientContext} client Reference to the service client.
*/
constructor(client: FrontDoorManagementClientContext) {
this.client = client;
}
/**
* @summary Gets a list of Experiments
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param [options] The optional parameters
* @returns Promise<Models.ExperimentsListByProfileResponse>
*/
listByProfile(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsListByProfileResponse>;
/**
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param callback The callback
*/
listByProfile(resourceGroupName: string, profileName: string, callback: msRest.ServiceCallback<Models.ExperimentList>): void;
/**
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param options The optional parameters
* @param callback The callback
*/
listByProfile(resourceGroupName: string, profileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExperimentList>): void;
listByProfile(resourceGroupName: string, profileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExperimentList>, callback?: msRest.ServiceCallback<Models.ExperimentList>): Promise<Models.ExperimentsListByProfileResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
options
},
listByProfileOperationSpec,
callback) as Promise<Models.ExperimentsListByProfileResponse>;
}
/**
* @summary Gets an Experiment by ExperimentName
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param [options] The optional parameters
* @returns Promise<Models.ExperimentsGetResponse>
*/
get(resourceGroupName: string, profileName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsGetResponse>;
/**
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param callback The callback
*/
get(resourceGroupName: string, profileName: string, experimentName: string, callback: msRest.ServiceCallback<Models.Experiment>): void;
/**
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, profileName: string, experimentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Experiment>): void;
get(resourceGroupName: string, profileName: string, experimentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Experiment>, callback?: msRest.ServiceCallback<Models.Experiment>): Promise<Models.ExperimentsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
profileName,
experimentName,
options
},
getOperationSpec,
callback) as Promise<Models.ExperimentsGetResponse>;
}
/**
* @summary Creates or updates an Experiment
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param parameters The Experiment resource
* @param [options] The optional parameters
* @returns Promise<Models.ExperimentsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, profileName: string, experimentName: string, parameters: Models.Experiment, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,profileName,experimentName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ExperimentsCreateOrUpdateResponse>;
}
/**
* Updates an Experiment
* @summary Updates an Experiment by Experiment id
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param parameters The Experiment Update Model
* @param [options] The optional parameters
* @returns Promise<Models.ExperimentsUpdateResponse>
*/
update(resourceGroupName: string, profileName: string, experimentName: string, parameters: Models.ExperimentUpdateModel, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsUpdateResponse> {
return this.beginUpdate(resourceGroupName,profileName,experimentName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ExperimentsUpdateResponse>;
}
/**
* @summary Deletes an Experiment
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, profileName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,profileName,experimentName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* @summary Creates or updates an Experiment
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param parameters The Experiment resource
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, profileName: string, experimentName: string, parameters: Models.Experiment, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
profileName,
experimentName,
parameters,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Updates an Experiment
* @summary Updates an Experiment by Experiment id
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param parameters The Experiment Update Model
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, profileName: string, experimentName: string, parameters: Models.ExperimentUpdateModel, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
profileName,
experimentName,
parameters,
options
},
beginUpdateOperationSpec,
options);
}
/**
* @summary Deletes an Experiment
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName The Profile identifier associated with the Tenant and Partner
* @param experimentName The Experiment identifier associated with the Experiment
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, profileName: string, experimentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
profileName,
experimentName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* @summary Gets a list of Experiments
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ExperimentsListByProfileNextResponse>
*/
listByProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ExperimentsListByProfileNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ExperimentList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ExperimentList>): void;
listByProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ExperimentList>, callback?: msRest.ServiceCallback<Models.ExperimentList>): Promise<Models.ExperimentsListByProfileNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByProfileNextOperationSpec,
callback) as Promise<Models.ExperimentsListByProfileNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByProfileOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.profileName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ExperimentList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.experimentName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Experiment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.experimentName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Experiment,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Experiment
},
201: {
bodyMapper: Mappers.Experiment
},
202: {
bodyMapper: Mappers.Experiment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.experimentName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ExperimentUpdateModel,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Experiment
},
202: {
bodyMapper: Mappers.Experiment
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/NetworkExperimentProfiles/{profileName}/Experiments/{experimentName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.profileName,
Parameters.experimentName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByProfileNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ExperimentList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { Injectable } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { NgxsDataPluginModule } from '@angular-ru/ngxs';
import { Computed, DataAction, StateRepository } from '@angular-ru/ngxs/decorators';
import { NgxsDataSequence } from '@angular-ru/ngxs/internals';
import { NgxsDataRepository, NgxsImmutableDataRepository } from '@angular-ru/ngxs/repositories';
import { NGXS_DATA_EXCEPTIONS } from '@angular-ru/ngxs/tokens';
import { NgxsModule, State, Store } from '@ngxs/store';
import { BehaviorSubject } from 'rxjs';
describe('[TEST]: Computed fields', () => {
it('should be throw when invalid annotated', () => {
let message: string | null = null;
try {
@StateRepository()
@State({ name: 'a', defaults: 'value' })
@Injectable()
class A extends NgxsDataRepository<string> {
@Computed()
public getSnapshot(): string {
return this.ctx.getState();
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([A]), NgxsDataPluginModule.forRoot()]
});
} catch (e: unknown) {
message = (e as Error).message;
}
expect(message).toEqual(
`${NGXS_DATA_EXCEPTIONS.NGXS_COMPUTED_DECORATOR}\nExample: \n@Computed() get getSnapshot() { \n\t .. \n}`
);
});
it('should be correct memoized state', () => {
@StateRepository()
@State({ name: 'b', defaults: 'value' })
@Injectable()
class B extends NgxsDataRepository<string> {
public countSnapshot: number = 0;
@Computed()
public get snapshot(): string {
this.countSnapshot++;
return this.ctx.getState();
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([B]), NgxsDataPluginModule.forRoot()]
});
const b: B = TestBed.inject<B>(B); // sequenceId = 0
expect(b.snapshot).toBe('value');
expect(b.snapshot).toBe('value');
expect(b.snapshot).toBe('value');
expect(b.snapshot).toBe('value');
expect(b.snapshot).toBe('value');
b.setState('hello'); // sequenceId = 1
expect(b.snapshot).toBe('hello');
expect(b.snapshot).toBe('hello');
expect(b.countSnapshot).toBe(2);
b.setState('world'); // sequenceId = 2
expect(b.snapshot).toBe('world');
expect(b.snapshot).toBe('world');
expect(b.snapshot).toBe('world');
expect(b.snapshot).toBe('world');
expect(b.countSnapshot).toBe(3);
});
describe('calculate total', () => {
interface OrderLineModel {
price: number;
amount: number;
}
it('should be correct computed values with NgxsDataRepository', () => {
@StateRepository()
@State<OrderLineModel>({
name: 'orderLine',
defaults: {
price: 0,
amount: 1
}
})
@Injectable()
class OrderLineState extends NgxsDataRepository<OrderLineModel> {
public memoized: number = 0;
public nonMemoized: number = 0;
@Computed()
public get total(): number {
this.memoized++;
return this.snapshot.price * this.snapshot.amount;
}
public get classicTotal(): number {
this.nonMemoized++;
return this.snapshot.price * this.snapshot.amount;
}
@DataAction()
public setPrice(price: number): void {
this.ctx.setState((state) => ({ price, amount: state.amount }));
}
@DataAction()
public setAmount(amount: number): void {
this.ctx.setState((state) => ({ price: state.price, amount }));
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([OrderLineState]), NgxsDataPluginModule.forRoot()]
});
const state: OrderLineState = TestBed.inject<OrderLineState>(OrderLineState);
// noinspection DuplicatedCode
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.memoized).toBe(1);
// noinspection DuplicatedCode
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.nonMemoized).toBe(4);
state.setAmount(5);
state.setPrice(5);
// noinspection DuplicatedCode
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.memoized).toBe(2);
// noinspection DuplicatedCode
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.nonMemoized).toBe(8);
});
it('should be correct computed values with NgxsImmutableDataRepository', () => {
@StateRepository()
@State<OrderLineModel>({
name: 'orderLine',
defaults: {
price: 0,
amount: 1
}
})
@Injectable()
class ImmutableOrderLineState extends NgxsImmutableDataRepository<OrderLineModel> {
public memoized: number = 0;
public nonMemoized: number = 0;
@Computed()
public get total(): number {
this.memoized++;
return this.snapshot.price * this.snapshot.amount;
}
public get classicTotal(): number {
this.nonMemoized++;
return this.snapshot.price * this.snapshot.amount;
}
@DataAction()
public setPrice(price: number): void {
this.ctx.setState((state) => ({ price, amount: state.amount }));
}
@DataAction()
public setAmount(amount: number): void {
this.ctx.setState((state) => ({ price: state.price, amount }));
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([ImmutableOrderLineState]), NgxsDataPluginModule.forRoot()]
});
const state: ImmutableOrderLineState = TestBed.inject<ImmutableOrderLineState>(ImmutableOrderLineState);
// noinspection DuplicatedCode
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.total).toBe(0);
expect(state.memoized).toBe(1);
// noinspection DuplicatedCode
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.classicTotal).toBe(0);
expect(state.nonMemoized).toBe(4);
state.setAmount(5);
state.setPrice(5);
// noinspection DuplicatedCode
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.total).toBe(25);
expect(state.memoized).toBe(2);
// noinspection DuplicatedCode
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.classicTotal).toBe(25);
expect(state.nonMemoized).toBe(8);
});
});
it('should be correct computed when change other states', () => {
abstract class AbstractCommonCounter extends NgxsDataRepository<number> {
@DataAction()
public increment() {
this.ctx.setState((state: number) => state + 1);
}
}
@StateRepository()
@State({
name: 'a',
defaults: 0
})
@Injectable()
class A extends AbstractCommonCounter {}
@StateRepository()
@State({
name: 'b',
defaults: 0
})
@Injectable()
class B extends AbstractCommonCounter {}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([A, B]), NgxsDataPluginModule.forRoot()]
});
const store: Store = TestBed.inject<Store>(Store);
const a: A = TestBed.inject<A>(A);
const b: B = TestBed.inject<B>(B);
expect(store.snapshot()).toEqual({ b: 0, a: 0 });
expect(a.snapshot).toBe(0);
expect(b.snapshot).toBe(0);
a.increment();
a.increment();
a.increment();
b.increment();
expect(store.snapshot()).toEqual({ b: 1, a: 3 });
expect(a.snapshot).toBe(3);
expect(b.snapshot).toBe(1);
});
it('should be correct computed when change other states and inherited state', () => {
@State({
name: 'commonCounter',
defaults: 0
})
@Injectable()
class CommonCounterState extends NgxsDataRepository<number> {
@DataAction()
public increment() {
this.ctx.setState((state: number) => state + 1);
}
}
@StateRepository()
@State({ name: 'a' })
@Injectable()
class A extends CommonCounterState {}
@StateRepository()
@State({ name: 'b' })
@Injectable()
class B extends CommonCounterState {}
// noinspection DuplicatedCode
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([A, B]), NgxsDataPluginModule.forRoot()]
});
const store: Store = TestBed.inject<Store>(Store);
const a: A = TestBed.inject<A>(A);
const b: B = TestBed.inject<B>(B);
expect(store.snapshot()).toEqual({ b: 0, a: 0 });
expect(a.snapshot).toBe(0);
expect(b.snapshot).toBe(0);
a.increment();
a.increment();
a.increment();
b.increment();
expect(store.snapshot()).toEqual({ b: 1, a: 3 });
expect(a.snapshot).toBe(3);
expect(b.snapshot).toBe(1);
a.reset();
b.reset();
b.increment();
b.increment();
b.increment();
a.increment();
expect(store.snapshot()).toEqual({ b: 3, a: 1 });
expect(a.snapshot).toBe(1);
expect(b.snapshot).toBe(3);
expect(a.snapshot === a.getState()).toBeTruthy();
expect(b.snapshot === b.getState()).toBeTruthy();
a.increment();
a.increment();
a.increment();
a.increment();
a.increment();
a.increment();
b.increment();
expect(store.snapshot()).toEqual({ b: 4, a: 7 });
expect(a.snapshot).toBe(7);
expect(b.snapshot).toBe(4);
expect(a.snapshot === a.getState()).toBeTruthy();
expect(b.snapshot === b.getState()).toBeTruthy();
});
it('should be trigger when store changes', () => {
interface Model {
value: number;
}
@StateRepository()
@State({
name: 'b',
defaults: { value: 2 }
})
@Injectable()
class B extends NgxsDataRepository<Model> {}
@StateRepository()
@State({
name: 'a',
defaults: { value: 1 }
})
@Injectable()
class A extends NgxsDataRepository<Model> {
public heavyCount: number = 0;
constructor(private readonly b: B) {
super();
}
@Computed()
public get sum(): number {
this.heavyCount++;
return this.snapshot.value + this.b.snapshot.value;
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([A, B]), NgxsDataPluginModule.forRoot()]
});
const store: Store = TestBed.inject(Store);
const a: A = TestBed.inject(A);
const b: B = TestBed.inject(B);
const stream: NgxsDataSequence = TestBed.inject(NgxsDataSequence);
expect(stream.sequenceValue).toBe(1);
expect(store.snapshot()).toEqual({ b: { value: 2 }, a: { value: 1 } });
expect(a.snapshot).toEqual({ value: 1 });
expect(a.snapshot).toEqual(a.snapshot);
expect(a.snapshot).toEqual(a.snapshot);
expect(a.snapshot).toEqual(a.snapshot);
expect(b.snapshot).toEqual({ value: 2 });
expect(b.snapshot).toEqual(b.snapshot);
expect(b.snapshot).toEqual(b.snapshot);
expect(b.snapshot).toEqual(b.snapshot);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.sum).toBe(3);
expect(a.heavyCount).toBe(1);
store.reset({ a: { value: 5 }, b: { value: 10 } });
expect(stream.sequenceValue).toBe(2);
expect(store.snapshot()).toEqual({ b: { value: 10 }, a: { value: 5 } });
expect(a.snapshot).toEqual({ value: 5 });
expect(a.snapshot).toEqual(a.snapshot);
expect(a.snapshot).toEqual(a.snapshot);
expect(a.snapshot).toEqual(a.snapshot);
expect(b.snapshot).toEqual({ value: 10 });
expect(b.snapshot).toEqual(b.snapshot);
expect(b.snapshot).toEqual(b.snapshot);
expect(b.snapshot).toEqual(b.snapshot);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.sum).toBe(15);
expect(a.heavyCount).toBe(2);
stream.ngOnDestroy();
store.reset({ a: { value: 0 }, b: { value: 0 } });
expect(stream.sequenceValue).toBe(0);
store.reset({ a: { value: 1 }, b: { value: 1 } });
expect(stream.sequenceValue).toBe(0);
});
it('does not recalculate when use state from third-party service', () => {
@Injectable()
class MyFirstCountService {
private values$: BehaviorSubject<number> = new BehaviorSubject(0);
public increment(): void {
this.values$.next(this.getValue() + 1);
}
public getValue(): number {
// eslint-disable-next-line rxjs/no-subject-value
return this.values$.getValue();
}
}
@StateRepository()
@State({
name: 'count',
defaults: 0
})
@Injectable()
class MySecondCountState extends NgxsDataRepository<number> {
constructor(private readonly first: MyFirstCountService) {
super();
}
@Computed()
public get sum(): number {
return this.snapshot + this.first.getValue();
}
@DataAction()
public increment(): void {
this.ctx.setState((state: number) => state + 1);
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([MySecondCountState]), NgxsDataPluginModule.forRoot()],
providers: [MyFirstCountService]
});
const first: MyFirstCountService = TestBed.inject(MyFirstCountService);
const second: MySecondCountState = TestBed.inject(MySecondCountState);
expect(first.getValue()).toBe(0);
expect(second.snapshot).toBe(0);
expect(second.sum).toBe(0);
second.increment();
second.increment();
expect(first.getValue()).toBe(0);
expect(second.snapshot).toBe(2);
expect(second.sum).toBe(2);
first.increment();
first.increment();
first.increment();
// Expect invalid behavior
expect(first.getValue()).toBe(3);
expect(second.snapshot).toBe(2);
expect(second.sum).toBe(2);
});
it('recalculate sum when use state from third-party service', () => {
@Injectable()
class MyFirstCountService {
private values$: BehaviorSubject<number> = new BehaviorSubject(0);
constructor(private readonly sequence: NgxsDataSequence) {}
public increment(): void {
this.values$.next(this.getValue() + 1);
this.sequence.updateSequence();
}
public getValue(): number {
return this.values$.getValue();
}
}
// noinspection DuplicatedCode
@StateRepository()
@State({
name: 'count',
defaults: 0
})
@Injectable()
class MySecondCountState extends NgxsDataRepository<number> {
constructor(private readonly first: MyFirstCountService) {
super();
}
@Computed()
public get sum(): number {
return this.snapshot + this.first.getValue();
}
@DataAction()
public increment(): void {
this.ctx.setState((state: number) => state + 1);
}
}
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([MySecondCountState]), NgxsDataPluginModule.forRoot()],
providers: [MyFirstCountService]
});
const first: MyFirstCountService = TestBed.inject(MyFirstCountService);
const second: MySecondCountState = TestBed.inject(MySecondCountState);
expect(first.getValue()).toBe(0);
expect(second.snapshot).toBe(0);
expect(second.sum).toBe(0);
second.increment();
second.increment();
expect(first.getValue()).toBe(0);
expect(second.snapshot).toBe(2);
expect(second.sum).toBe(2);
first.increment();
first.increment();
first.increment();
// Expect valid behavior
expect(first.getValue()).toBe(3);
expect(second.snapshot).toBe(2);
expect(second.sum).toBe(5);
});
}); | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as moment from 'moment';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the TimeSeriesInsightsClient.
*/
export interface Operations {
/**
* Lists all of the available Time Series Insights related operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Time Series Insights related operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
/**
* Lists all of the available Time Series Insights related operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Time Series Insights related operations.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* Environments
* __NOTE__: An instance of this class is automatically created for an
* instance of the TimeSeriesInsightsClient.
*/
export interface Environments {
/**
* Create or update an environment in the specified subscription and resource
* group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName Name of the environment
*
* @param {object} parameters Parameters for creating an environment resource.
*
* @param {object} parameters.sku The sku determines the capacity of the
* environment, the SLA (in queries-per-minute and total capacity), and the
* billing rate.
*
* @param {string} parameters.sku.name The name of this SKU. Possible values
* include: 'S1', 'S2'
*
* @param {number} parameters.sku.capacity The capacity of the sku. This value
* can be changed to support scale out of environments after they have been
* created.
*
* @param {moment.duration} parameters.dataRetentionTime ISO8601 timespan
* specifying the minimum number of days the environment's events will be
* available for query.
*
* @param {string} [parameters.storageLimitExceededBehavior] The behavior the
* Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read
* from the event source. If "PurgeOldData" is specified, new events will
* continue to be read and old events will be deleted from the environment. The
* default behavior is PurgeOldData. Possible values include: 'PurgeOldData',
* 'PauseIngress'
*
* @param {array} [parameters.partitionKeyProperties] The list of partition
* keys according to which the data in the environment will be ordered.
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentResource>>;
/**
* Create or update an environment in the specified subscription and resource
* group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName Name of the environment
*
* @param {object} parameters Parameters for creating an environment resource.
*
* @param {object} parameters.sku The sku determines the capacity of the
* environment, the SLA (in queries-per-minute and total capacity), and the
* billing rate.
*
* @param {string} parameters.sku.name The name of this SKU. Possible values
* include: 'S1', 'S2'
*
* @param {number} parameters.sku.capacity The capacity of the sku. This value
* can be changed to support scale out of environments after they have been
* created.
*
* @param {moment.duration} parameters.dataRetentionTime ISO8601 timespan
* specifying the minimum number of days the environment's events will be
* available for query.
*
* @param {string} [parameters.storageLimitExceededBehavior] The behavior the
* Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read
* from the event source. If "PurgeOldData" is specified, new events will
* continue to be read and old events will be deleted from the environment. The
* default behavior is PurgeOldData. Possible values include: 'PurgeOldData',
* 'PauseIngress'
*
* @param {array} [parameters.partitionKeyProperties] The list of partition
* keys according to which the data in the environment will be ordered.
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentResource} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentResource>;
createOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, callback: ServiceCallback<models.EnvironmentResource>): void;
createOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentResource>): void;
/**
* Gets the environment with the specified name in the specified subscription
* and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.expand] Setting $expand=status will include the
* status of the internal services of the environment in the Time Series
* Insights service.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, environmentName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentResource>>;
/**
* Gets the environment with the specified name in the specified subscription
* and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.expand] Setting $expand=status will include the
* status of the internal services of the environment in the Time Series
* Insights service.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentResource} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, environmentName: string, options?: { expand? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentResource>;
get(resourceGroupName: string, environmentName: string, callback: ServiceCallback<models.EnvironmentResource>): void;
get(resourceGroupName: string, environmentName: string, options: { expand? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentResource>): void;
/**
* Updates the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} environmentUpdateParameters Request object that contains the
* updated information for the environment.
*
* @param {object} [environmentUpdateParameters.sku] The sku of the
* environment.
*
* @param {string} environmentUpdateParameters.sku.name The name of this SKU.
* Possible values include: 'S1', 'S2'
*
* @param {number} environmentUpdateParameters.sku.capacity The capacity of the
* sku. This value can be changed to support scale out of environments after
* they have been created.
*
* @param {object} [environmentUpdateParameters.tags] Key-value pairs of
* additional properties for the environment.
*
* @param {moment.duration} [environmentUpdateParameters.dataRetentionTime]
* ISO8601 timespan specifying the minimum number of days the environment's
* events will be available for query.
*
* @param {string} [environmentUpdateParameters.storageLimitExceededBehavior]
* The behavior the Time Series Insights service should take when the
* environment's capacity has been exceeded. If "PauseIngress" is specified,
* new events will not be read from the event source. If "PurgeOldData" is
* specified, new events will continue to be read and old events will be
* deleted from the environment. The default behavior is PurgeOldData. Possible
* values include: 'PurgeOldData', 'PauseIngress'
*
* @param {array} [environmentUpdateParameters.partitionKeyProperties] The list
* of event properties which will be used to partition data in the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentResource>>;
/**
* Updates the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} environmentUpdateParameters Request object that contains the
* updated information for the environment.
*
* @param {object} [environmentUpdateParameters.sku] The sku of the
* environment.
*
* @param {string} environmentUpdateParameters.sku.name The name of this SKU.
* Possible values include: 'S1', 'S2'
*
* @param {number} environmentUpdateParameters.sku.capacity The capacity of the
* sku. This value can be changed to support scale out of environments after
* they have been created.
*
* @param {object} [environmentUpdateParameters.tags] Key-value pairs of
* additional properties for the environment.
*
* @param {moment.duration} [environmentUpdateParameters.dataRetentionTime]
* ISO8601 timespan specifying the minimum number of days the environment's
* events will be available for query.
*
* @param {string} [environmentUpdateParameters.storageLimitExceededBehavior]
* The behavior the Time Series Insights service should take when the
* environment's capacity has been exceeded. If "PauseIngress" is specified,
* new events will not be read from the event source. If "PurgeOldData" is
* specified, new events will continue to be read and old events will be
* deleted from the environment. The default behavior is PurgeOldData. Possible
* values include: 'PurgeOldData', 'PauseIngress'
*
* @param {array} [environmentUpdateParameters.partitionKeyProperties] The list
* of event properties which will be used to partition data in the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentResource} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentResource>;
update(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, callback: ServiceCallback<models.EnvironmentResource>): void;
update(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentResource>): void;
/**
* Deletes the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, environmentName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists all the available environments associated with the subscription and
* within the specified resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentListResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentListResponse>>;
/**
* Lists all the available environments associated with the subscription and
* within the specified resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentListResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentListResponse} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentListResponse} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentListResponse>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.EnvironmentListResponse>): void;
listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentListResponse>): void;
/**
* Lists all the available environments within a subscription, irrespective of
* the resource groups.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentListResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentListResponse>>;
/**
* Lists all the available environments within a subscription, irrespective of
* the resource groups.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentListResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentListResponse} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentListResponse} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentListResponse>;
listBySubscription(callback: ServiceCallback<models.EnvironmentListResponse>): void;
listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentListResponse>): void;
/**
* Create or update an environment in the specified subscription and resource
* group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName Name of the environment
*
* @param {object} parameters Parameters for creating an environment resource.
*
* @param {object} parameters.sku The sku determines the capacity of the
* environment, the SLA (in queries-per-minute and total capacity), and the
* billing rate.
*
* @param {string} parameters.sku.name The name of this SKU. Possible values
* include: 'S1', 'S2'
*
* @param {number} parameters.sku.capacity The capacity of the sku. This value
* can be changed to support scale out of environments after they have been
* created.
*
* @param {moment.duration} parameters.dataRetentionTime ISO8601 timespan
* specifying the minimum number of days the environment's events will be
* available for query.
*
* @param {string} [parameters.storageLimitExceededBehavior] The behavior the
* Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read
* from the event source. If "PurgeOldData" is specified, new events will
* continue to be read and old events will be deleted from the environment. The
* default behavior is PurgeOldData. Possible values include: 'PurgeOldData',
* 'PauseIngress'
*
* @param {array} [parameters.partitionKeyProperties] The list of partition
* keys according to which the data in the environment will be ordered.
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentResource>>;
/**
* Create or update an environment in the specified subscription and resource
* group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName Name of the environment
*
* @param {object} parameters Parameters for creating an environment resource.
*
* @param {object} parameters.sku The sku determines the capacity of the
* environment, the SLA (in queries-per-minute and total capacity), and the
* billing rate.
*
* @param {string} parameters.sku.name The name of this SKU. Possible values
* include: 'S1', 'S2'
*
* @param {number} parameters.sku.capacity The capacity of the sku. This value
* can be changed to support scale out of environments after they have been
* created.
*
* @param {moment.duration} parameters.dataRetentionTime ISO8601 timespan
* specifying the minimum number of days the environment's events will be
* available for query.
*
* @param {string} [parameters.storageLimitExceededBehavior] The behavior the
* Time Series Insights service should take when the environment's capacity has
* been exceeded. If "PauseIngress" is specified, new events will not be read
* from the event source. If "PurgeOldData" is specified, new events will
* continue to be read and old events will be deleted from the environment. The
* default behavior is PurgeOldData. Possible values include: 'PurgeOldData',
* 'PauseIngress'
*
* @param {array} [parameters.partitionKeyProperties] The list of partition
* keys according to which the data in the environment will be ordered.
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentResource} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreateOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentResource>;
beginCreateOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, callback: ServiceCallback<models.EnvironmentResource>): void;
beginCreateOrUpdate(resourceGroupName: string, environmentName: string, parameters: models.EnvironmentCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentResource>): void;
/**
* Updates the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} environmentUpdateParameters Request object that contains the
* updated information for the environment.
*
* @param {object} [environmentUpdateParameters.sku] The sku of the
* environment.
*
* @param {string} environmentUpdateParameters.sku.name The name of this SKU.
* Possible values include: 'S1', 'S2'
*
* @param {number} environmentUpdateParameters.sku.capacity The capacity of the
* sku. This value can be changed to support scale out of environments after
* they have been created.
*
* @param {object} [environmentUpdateParameters.tags] Key-value pairs of
* additional properties for the environment.
*
* @param {moment.duration} [environmentUpdateParameters.dataRetentionTime]
* ISO8601 timespan specifying the minimum number of days the environment's
* events will be available for query.
*
* @param {string} [environmentUpdateParameters.storageLimitExceededBehavior]
* The behavior the Time Series Insights service should take when the
* environment's capacity has been exceeded. If "PauseIngress" is specified,
* new events will not be read from the event source. If "PurgeOldData" is
* specified, new events will continue to be read and old events will be
* deleted from the environment. The default behavior is PurgeOldData. Possible
* values include: 'PurgeOldData', 'PauseIngress'
*
* @param {array} [environmentUpdateParameters.partitionKeyProperties] The list
* of event properties which will be used to partition data in the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EnvironmentResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EnvironmentResource>>;
/**
* Updates the environment with the specified name in the specified
* subscription and resource group.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} environmentUpdateParameters Request object that contains the
* updated information for the environment.
*
* @param {object} [environmentUpdateParameters.sku] The sku of the
* environment.
*
* @param {string} environmentUpdateParameters.sku.name The name of this SKU.
* Possible values include: 'S1', 'S2'
*
* @param {number} environmentUpdateParameters.sku.capacity The capacity of the
* sku. This value can be changed to support scale out of environments after
* they have been created.
*
* @param {object} [environmentUpdateParameters.tags] Key-value pairs of
* additional properties for the environment.
*
* @param {moment.duration} [environmentUpdateParameters.dataRetentionTime]
* ISO8601 timespan specifying the minimum number of days the environment's
* events will be available for query.
*
* @param {string} [environmentUpdateParameters.storageLimitExceededBehavior]
* The behavior the Time Series Insights service should take when the
* environment's capacity has been exceeded. If "PauseIngress" is specified,
* new events will not be read from the event source. If "PurgeOldData" is
* specified, new events will continue to be read and old events will be
* deleted from the environment. The default behavior is PurgeOldData. Possible
* values include: 'PurgeOldData', 'PauseIngress'
*
* @param {array} [environmentUpdateParameters.partitionKeyProperties] The list
* of event properties which will be used to partition data in the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EnvironmentResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EnvironmentResource} [result] - The deserialized result object if an error did not occur.
* See {@link EnvironmentResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginUpdate(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EnvironmentResource>;
beginUpdate(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, callback: ServiceCallback<models.EnvironmentResource>): void;
beginUpdate(resourceGroupName: string, environmentName: string, environmentUpdateParameters: models.EnvironmentUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EnvironmentResource>): void;
}
/**
* @class
* EventSources
* __NOTE__: An instance of this class is automatically created for an
* instance of the TimeSeriesInsightsClient.
*/
export interface EventSources {
/**
* Create or update an event source under the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName Name of the event source.
*
* @param {object} parameters Parameters for creating an event source resource.
*
* @param {string} parameters.kind Polymorphic Discriminator
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventSourceResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, eventSourceName: string, parameters: models.EventSourceCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventSourceResource>>;
/**
* Create or update an event source under the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName Name of the event source.
*
* @param {object} parameters Parameters for creating an event source resource.
*
* @param {string} parameters.kind Polymorphic Discriminator
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EventSourceResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EventSourceResource} [result] - The deserialized result object if an error did not occur.
* See {@link EventSourceResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, environmentName: string, eventSourceName: string, parameters: models.EventSourceCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EventSourceResource>;
createOrUpdate(resourceGroupName: string, environmentName: string, eventSourceName: string, parameters: models.EventSourceCreateOrUpdateParameters, callback: ServiceCallback<models.EventSourceResource>): void;
createOrUpdate(resourceGroupName: string, environmentName: string, eventSourceName: string, parameters: models.EventSourceCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventSourceResource>): void;
/**
* Gets the event source with the specified name in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventSourceResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, environmentName: string, eventSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventSourceResource>>;
/**
* Gets the event source with the specified name in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EventSourceResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EventSourceResource} [result] - The deserialized result object if an error did not occur.
* See {@link EventSourceResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, environmentName: string, eventSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EventSourceResource>;
get(resourceGroupName: string, environmentName: string, eventSourceName: string, callback: ServiceCallback<models.EventSourceResource>): void;
get(resourceGroupName: string, environmentName: string, eventSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventSourceResource>): void;
/**
* Updates the event source with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} eventSourceUpdateParameters Request object that contains the
* updated information for the event source.
*
* @param {object} [eventSourceUpdateParameters.tags] Key-value pairs of
* additional properties for the event source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventSourceResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, eventSourceName: string, eventSourceUpdateParameters: models.EventSourceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventSourceResource>>;
/**
* Updates the event source with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} eventSourceUpdateParameters Request object that contains the
* updated information for the event source.
*
* @param {object} [eventSourceUpdateParameters.tags] Key-value pairs of
* additional properties for the event source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EventSourceResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EventSourceResource} [result] - The deserialized result object if an error did not occur.
* See {@link EventSourceResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, environmentName: string, eventSourceName: string, eventSourceUpdateParameters: models.EventSourceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EventSourceResource>;
update(resourceGroupName: string, environmentName: string, eventSourceName: string, eventSourceUpdateParameters: models.EventSourceUpdateParameters, callback: ServiceCallback<models.EventSourceResource>): void;
update(resourceGroupName: string, environmentName: string, eventSourceName: string, eventSourceUpdateParameters: models.EventSourceUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventSourceResource>): void;
/**
* Deletes the event source with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, environmentName: string, eventSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the event source with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} eventSourceName The name of the Time Series Insights event
* source associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, environmentName: string, eventSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, environmentName: string, eventSourceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, environmentName: string, eventSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists all the available event sources associated with the subscription and
* within the specified resource group and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<EventSourceListResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByEnvironmentWithHttpOperationResponse(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EventSourceListResponse>>;
/**
* Lists all the available event sources associated with the subscription and
* within the specified resource group and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {EventSourceListResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {EventSourceListResponse} [result] - The deserialized result object if an error did not occur.
* See {@link EventSourceListResponse} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByEnvironment(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EventSourceListResponse>;
listByEnvironment(resourceGroupName: string, environmentName: string, callback: ServiceCallback<models.EventSourceListResponse>): void;
listByEnvironment(resourceGroupName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EventSourceListResponse>): void;
}
/**
* @class
* ReferenceDataSets
* __NOTE__: An instance of this class is automatically created for an
* instance of the TimeSeriesInsightsClient.
*/
export interface ReferenceDataSets {
/**
* Create or update a reference data set in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName Name of the reference data set.
*
* @param {object} parameters Parameters for creating a reference data set.
*
* @param {array} parameters.keyProperties The list of key properties for the
* reference data set.
*
* @param {string} [parameters.dataStringComparisonBehavior] The reference data
* set key comparison behavior can be set using this property. By default, the
* value is 'Ordinal' - which means case sensitive key comparison will be
* performed while joining reference data with events or while adding new
* reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison
* will be used. Possible values include: 'Ordinal', 'OrdinalIgnoreCase'
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ReferenceDataSetResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, referenceDataSetName: string, parameters: models.ReferenceDataSetCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReferenceDataSetResource>>;
/**
* Create or update a reference data set in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName Name of the reference data set.
*
* @param {object} parameters Parameters for creating a reference data set.
*
* @param {array} parameters.keyProperties The list of key properties for the
* reference data set.
*
* @param {string} [parameters.dataStringComparisonBehavior] The reference data
* set key comparison behavior can be set using this property. By default, the
* value is 'Ordinal' - which means case sensitive key comparison will be
* performed while joining reference data with events or while adding new
* reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison
* will be used. Possible values include: 'Ordinal', 'OrdinalIgnoreCase'
*
* @param {string} parameters.location The location of the resource.
*
* @param {object} [parameters.tags] Key-value pairs of additional properties
* for the resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ReferenceDataSetResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ReferenceDataSetResource} [result] - The deserialized result object if an error did not occur.
* See {@link ReferenceDataSetResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, environmentName: string, referenceDataSetName: string, parameters: models.ReferenceDataSetCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReferenceDataSetResource>;
createOrUpdate(resourceGroupName: string, environmentName: string, referenceDataSetName: string, parameters: models.ReferenceDataSetCreateOrUpdateParameters, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
createOrUpdate(resourceGroupName: string, environmentName: string, referenceDataSetName: string, parameters: models.ReferenceDataSetCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
/**
* Gets the reference data set with the specified name in the specified
* environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ReferenceDataSetResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReferenceDataSetResource>>;
/**
* Gets the reference data set with the specified name in the specified
* environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ReferenceDataSetResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ReferenceDataSetResource} [result] - The deserialized result object if an error did not occur.
* See {@link ReferenceDataSetResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReferenceDataSetResource>;
get(resourceGroupName: string, environmentName: string, referenceDataSetName: string, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
get(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
/**
* Updates the reference data set with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} referenceDataSetUpdateParameters Request object that
* contains the updated information for the reference data set.
*
* @param {object} [referenceDataSetUpdateParameters.tags] Key-value pairs of
* additional properties for the reference data set.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ReferenceDataSetResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, referenceDataSetName: string, referenceDataSetUpdateParameters: models.ReferenceDataSetUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReferenceDataSetResource>>;
/**
* Updates the reference data set with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} referenceDataSetUpdateParameters Request object that
* contains the updated information for the reference data set.
*
* @param {object} [referenceDataSetUpdateParameters.tags] Key-value pairs of
* additional properties for the reference data set.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ReferenceDataSetResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ReferenceDataSetResource} [result] - The deserialized result object if an error did not occur.
* See {@link ReferenceDataSetResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, environmentName: string, referenceDataSetName: string, referenceDataSetUpdateParameters: models.ReferenceDataSetUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReferenceDataSetResource>;
update(resourceGroupName: string, environmentName: string, referenceDataSetName: string, referenceDataSetUpdateParameters: models.ReferenceDataSetUpdateParameters, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
update(resourceGroupName: string, environmentName: string, referenceDataSetName: string, referenceDataSetUpdateParameters: models.ReferenceDataSetUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReferenceDataSetResource>): void;
/**
* Deletes the reference data set with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the reference data set with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} referenceDataSetName The name of the Time Series Insights
* reference data set associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, environmentName: string, referenceDataSetName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, environmentName: string, referenceDataSetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists all the available reference data sets associated with the subscription
* and within the specified resource group and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ReferenceDataSetListResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByEnvironmentWithHttpOperationResponse(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReferenceDataSetListResponse>>;
/**
* Lists all the available reference data sets associated with the subscription
* and within the specified resource group and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ReferenceDataSetListResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ReferenceDataSetListResponse} [result] - The deserialized result object if an error did not occur.
* See {@link ReferenceDataSetListResponse} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByEnvironment(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReferenceDataSetListResponse>;
listByEnvironment(resourceGroupName: string, environmentName: string, callback: ServiceCallback<models.ReferenceDataSetListResponse>): void;
listByEnvironment(resourceGroupName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReferenceDataSetListResponse>): void;
}
/**
* @class
* AccessPolicies
* __NOTE__: An instance of this class is automatically created for an
* instance of the TimeSeriesInsightsClient.
*/
export interface AccessPolicies {
/**
* Create or update an access policy in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName Name of the access policy.
*
* @param {object} parameters Parameters for creating an access policy.
*
* @param {string} [parameters.principalObjectId] The objectId of the principal
* in Azure Active Directory.
*
* @param {string} [parameters.description] An description of the access
* policy.
*
* @param {array} [parameters.roles] The list of roles the principal is
* assigned on the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccessPolicyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, accessPolicyName: string, parameters: models.AccessPolicyCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessPolicyResource>>;
/**
* Create or update an access policy in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName Name of the access policy.
*
* @param {object} parameters Parameters for creating an access policy.
*
* @param {string} [parameters.principalObjectId] The objectId of the principal
* in Azure Active Directory.
*
* @param {string} [parameters.description] An description of the access
* policy.
*
* @param {array} [parameters.roles] The list of roles the principal is
* assigned on the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccessPolicyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccessPolicyResource} [result] - The deserialized result object if an error did not occur.
* See {@link AccessPolicyResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, environmentName: string, accessPolicyName: string, parameters: models.AccessPolicyCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessPolicyResource>;
createOrUpdate(resourceGroupName: string, environmentName: string, accessPolicyName: string, parameters: models.AccessPolicyCreateOrUpdateParameters, callback: ServiceCallback<models.AccessPolicyResource>): void;
createOrUpdate(resourceGroupName: string, environmentName: string, accessPolicyName: string, parameters: models.AccessPolicyCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessPolicyResource>): void;
/**
* Gets the access policy with the specified name in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccessPolicyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, environmentName: string, accessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessPolicyResource>>;
/**
* Gets the access policy with the specified name in the specified environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccessPolicyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccessPolicyResource} [result] - The deserialized result object if an error did not occur.
* See {@link AccessPolicyResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, environmentName: string, accessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessPolicyResource>;
get(resourceGroupName: string, environmentName: string, accessPolicyName: string, callback: ServiceCallback<models.AccessPolicyResource>): void;
get(resourceGroupName: string, environmentName: string, accessPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessPolicyResource>): void;
/**
* Updates the access policy with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} accessPolicyUpdateParameters Request object that contains
* the updated information for the access policy.
*
* @param {string} [accessPolicyUpdateParameters.description] An description of
* the access policy.
*
* @param {array} [accessPolicyUpdateParameters.roles] The list of roles the
* principal is assigned on the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccessPolicyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, environmentName: string, accessPolicyName: string, accessPolicyUpdateParameters: models.AccessPolicyUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessPolicyResource>>;
/**
* Updates the access policy with the specified name in the specified
* subscription, resource group, and environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} accessPolicyUpdateParameters Request object that contains
* the updated information for the access policy.
*
* @param {string} [accessPolicyUpdateParameters.description] An description of
* the access policy.
*
* @param {array} [accessPolicyUpdateParameters.roles] The list of roles the
* principal is assigned on the environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccessPolicyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccessPolicyResource} [result] - The deserialized result object if an error did not occur.
* See {@link AccessPolicyResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, environmentName: string, accessPolicyName: string, accessPolicyUpdateParameters: models.AccessPolicyUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessPolicyResource>;
update(resourceGroupName: string, environmentName: string, accessPolicyName: string, accessPolicyUpdateParameters: models.AccessPolicyUpdateParameters, callback: ServiceCallback<models.AccessPolicyResource>): void;
update(resourceGroupName: string, environmentName: string, accessPolicyName: string, accessPolicyUpdateParameters: models.AccessPolicyUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessPolicyResource>): void;
/**
* Deletes the access policy with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, environmentName: string, accessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the access policy with the specified name in the specified
* subscription, resource group, and environment
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {string} accessPolicyName The name of the Time Series Insights access
* policy associated with the specified environment.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, environmentName: string, accessPolicyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, environmentName: string, accessPolicyName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, environmentName: string, accessPolicyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists all the available access policies associated with the environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<AccessPolicyListResponse>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByEnvironmentWithHttpOperationResponse(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.AccessPolicyListResponse>>;
/**
* Lists all the available access policies associated with the environment.
*
* @param {string} resourceGroupName Name of an Azure Resource group.
*
* @param {string} environmentName The name of the Time Series Insights
* environment associated with the specified resource group.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {AccessPolicyListResponse} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {AccessPolicyListResponse} [result] - The deserialized result object if an error did not occur.
* See {@link AccessPolicyListResponse} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByEnvironment(resourceGroupName: string, environmentName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.AccessPolicyListResponse>;
listByEnvironment(resourceGroupName: string, environmentName: string, callback: ServiceCallback<models.AccessPolicyListResponse>): void;
listByEnvironment(resourceGroupName: string, environmentName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.AccessPolicyListResponse>): void;
} | the_stack |
interface AuthOptions {
clientId: string;
persistentCache: boolean;
redirectUri: string;
}
interface AzureAuthOptions {
/** @param {String} clientId your AzureAuth client identifier */
clientId: string;
/** @param {boolean} [persistentCache] should store token cache between the app starts; defaults to true */
persistentCache?: string;
/** @param {String} [authorityUrl] optional Azure authority if you want to replace default v2 endpoint (`https://login.microsoftonline.com/${tenant}/oauth2/v2.0/`) */
authorityUrl?: string;
/** @param {String} [tenant] uses given tenant in the default authority URL; default is `common` */
tenant?: string;
/** @param {String} [redirectUri] - uses given redirect URI instead of default one:
*
* iOS: {YOUR_BUNDLE_IDENTIFIER}://${YOUR_BUNDLE_IDENTIFIER}/ios/callback
*
* Android: {YOUR_APP_PACKAGE_NAME}://{YOUR_APP_PACKAGE_NAME}/android/callback
*/
redirectUri?: string;
}
interface ClientOptions {
token?: string;
authorityUrl?: string;
baseUrl?: string;
}
interface TokenResponse {
accessToken: string;
tokenType: string;
expiresIn: number;
scope: string;
refreshToken: string;
idToken: string;
}
interface ClientResponse {
status:string,
ok: boolean,
headers: Headers,
blob?: Blob,
json?: object,
text?: string
}
/**
* Helper to perform HTTP requests
* Blob (binary) content types are not supported
*
* Class variables:
* - baseUrl | authorityUrl: base URL the request path is added to
* - token: Auth token if the request needs authorization
*
* One of Url options must be provided
*
* @param options
* @param options.authorityUrl
* @param options.baseUrl
* @param options.token
*/
declare class Client {
constructor(options?: ClientOptions);
baseUrl: string;
bearer: string;
get(path: string, query: string): Promise<void>;
patch(path: string, body: any): Promise<void>;
post(path: string, body: any): Promise<void>;
/**
* Helper function to send HTTP requests
*
* @param {String} method
* @param {String} url
* @param {Object} [body] - request body
*/
request(method: string, url: string, body?: any): Promise<ClientResponse>;
url(path: string, query?: string): string;
}
/**
* Class represent basic token cache item
*
* Note: userId is handled in case insencitive way for token cache keys
*
* @param {Object} tokenResponse
* @param {String} clientId
*/
declare class BaseTokenItem {
constructor(tokenResponse: TokenResponse, clientId: string);
clientId: string;
rawIdToken: string;
userId: string;
userName: string;
tenantId: string;
idTokenExpireOn: number;
toString(): string;
static createAccessTokenKey(
clientId: string,
userId: string,
scope: Scope
): string;
static createRefreshTokenKey(clientId: string, userId: string): string;
static createTokenKeyPrefix(clientId: string, userId: string): string;
static rawObjectFromJson(objStr: string): any;
static scopeFromKey(key: string): Scope | null;
}
/**
* Class represent access token cache item
*
* @namespace TokenCache.AccessTokenItem
*
* @param {Object} tokenResponse
* @param {String} clientId
*/
declare class AccessTokenItem extends BaseTokenItem {
constructor(tokenResponse: TokenResponse, clientId: string);
accessToken: string;
scope: Scope;
expireOn: number;
isExpired(): boolean;
tokenKey(): string;
static fromJson(objStr: string): AccessTokenItem | null;
}
/**
* Class represent refresh token cache item
*
* @param {Object} tokenResponse
* @param {String} clientId
*
*/
declare class RefreshTokenItem extends BaseTokenItem {
constructor(tokenResponse: TokenResponse, clientId: string);
refreshToken: string;
tokenKey(): string;
static fromJson(objStr: string): RefreshTokenItem | null;
}
/**
* Azure AD Auth scope representation class
*
* 1. Remove MS Graph URLs from scope, as it is default for any scope
* 2. Remove eventual commas and double spaces
* 3. Sort
* 4. BASIC SCOPE is always a part of auth requests
*
* @param {string | Array<String> | ''} scope - without parameters represents
*
* BASIC_SCOPE = 'offline_access openid profile'
*
*/
declare class Scope {
constructor(scope?: string | string[]);
basicScope: boolean;
scope: string[];
scopeStr: string;
equals(other: Scope): boolean;
/**
* Compare if the current instance scope intersects with one from parameter
* Only NON basic scopes are compared
*
* @param {Scope} otherScope
*/
isIntersects(otherScope: Scope): boolean;
/**
* Check if otherScope is a subset of baseScope
*
* @param {Array} otherScope
*/
isSubsetOf(otherScope: Scope): boolean;
toString(): string;
static basicScope(): Scope;
}
/**
* Token persistent cache
*
* @param input - init parameters
* @param {String} input.clientId
* @param {Boolean} input.persistent - if true - the RN `AsyncStorage` is used for persistent caching, otherwise only the class instance. (default: true)
*/
declare class TokenCache {
constructor(input: { clientId: string; persistent: boolean });
cache: Record<string, string>;
clientId: string;
persistent: boolean;
getAccessToken(userId: string, scope: Scope): Promise<AccessTokenItem | null>;
getRefreshToken(userId: string): Promise<RefreshTokenItem | null>;
saveAccessToken(tokenResponse: TokenResponse): Promise<AccessTokenItem>;
saveRefreshToken(tokenResponse: TokenResponse): Promise<RefreshTokenItem>;
}
declare class Auth {
constructor(options: AuthOptions);
authorityUrl: string;
cache: TokenCache;
client: Client;
clientId: string;
redirectUri: string;
/**
* Try to obtain token silently without user interaction
*
* @param {String} parameters.userId user login name (e.g. from Id token)
* @param {String} parameters.scope scopes requested for the issued tokens.
*
*/
acquireTokenSilent: (parameters: {
userId: string;
scope: string;
}) => Promise<AccessTokenItem | null>;
/**
* Clear persystent cache - AsyncStorage - for given client ID and user ID or ALL users
*
* @param {String} [userId] ID of user whose tokens will be cleared/deleted
* if ommited - tokens for ALL users and current client will be cleared
*/
clearPersistenCache: (userId?: string) => Promise<void>;
/**
* Exchanges a code obtained via `/authorize` for the access tokens
*
* @param input input used to obtain tokens from a code
* @param {String} input.code code returned by `/authorize`.
* @param {String} input.redirectUri original redirectUri used when calling `/authorize`.
* @param {String} input.scope A space-separated list of scopes.
* The scopes requested in this leg must be equivalent to or a subset of the scopes requested in the first leg
*
* @see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-code#request-an-access-token
*/
exchange(input: {
code: string;
redirectUri: string;
scope: string;
}): Promise<void>;
/**
* Builds the full authorize endpoint url in the Authorization Server (AS) with given parameters.
*
* @param parameters parameters to send to `/authorize`
* @param {String} parameters.responseType type of the response to get from `/authorize`.
* @param {String} parameters.redirectUri where the AS will redirect back after success or failure.
* @param {String} parameters.state random string to prevent CSRF attacks.
* @param {String} parameters.scope a space-separated list of scopes that you want the user to consent to.
* @param {String} parameters.prompt (optional) indicates the type of user interaction that is required.
* The only valid values at this time are 'login', 'none', and 'consent'.
* @returns {String} authorize url with specified parameters to redirect to for AuthZ/AuthN.
*
* @see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-code
*/
loginUrl(parameters?: {
responseType: string;
redirectUri: string;
state: string;
scope: string;
prompt?: string;
}): string;
/**
* Builds the full logout endpoint url in the Authorization Server (AS) with given parameters.
*
* `https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=[URI]&redirect_uri=[URI]`
*
* @returns {String} logout url with default parameter
*/
logoutUrl(): string;
/**
* Return user information using an access token
*
* @param parameters user info parameters
* @param {String} parameters.token user's access token
* @param {String} parameters.path - MS Graph API Path
*
* @see https://developer.microsoft.com/en-us/graph/docs/concepts/overview
* @see https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_get
*/
msGraphRequest(parameters: { token: string; path: string }): Promise<any>;
/**
* Obtain new tokens (access and id) using the Refresh Token obtained during Auth (requesting `offline_access` scope)
*
* @param parameters refresh token parameters
* @param {String} parameters.refreshToken user's issued refresh token
* @param {String} parameters.scope scopes requested for the issued tokens.
* @param {String} [parameters.redirectUri] the same redirect_uri value that was used to acquire the authorization_code.
* @see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-code#refresh-the-access-token
*
*/
refreshTokens: (parameters: {
refreshToken: string;
scope: string;
redirectUri?: string;
}) => Promise<TokenResponse>;
}
declare class WebAuth {
constructor(auth: Client);
/**
* Starts the AuthN/AuthZ transaction against the AS in the in-app browser.
*
* In iOS it will use `SFSafariViewController` and in Android `Chrome Custom Tabs`.
*
* @param {Object} options parameters to send
* @param {String} [options.scope] scopes requested for the issued tokens.
* OpenID Connect scopes are always added to every request. `openid profile offline_access`
* @see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-scopes
* @param {String} [options.prompt] (optional) indicates the type of user interaction that is required.
* The only valid values at this time are 'login', 'none', and 'consent'.
*/
authorize(options: {
prompt?: string;
scope?: string;
}): Promise<BaseTokenItem & Partial<AccessTokenItem>>;
/**
* Removes Azure session
*
* @param {Object} options parameters to send
* @param {Boolean} [options.closeOnLoad] close browser window on 'Loaded' event (works only on iOS)
*/
clearSession(options?: { closeOnLoad: boolean }): Promise<void>;
}
declare class AzureAuth {
constructor(options: AzureAuthOptions);
auth: Auth;
webAuth: WebAuth;
}
export default AzureAuth; | the_stack |
import * as vscode from "vscode";
import { executeCommand, ExpectedDocument, groupTestsByParentName } from "../utils";
suite("./test/suite/commands/select-lines.md", function () {
// Set up document.
let document: vscode.TextDocument,
editor: vscode.TextEditor;
this.beforeAll(async () => {
document = await vscode.workspace.openTextDocument();
editor = await vscode.window.showTextDocument(document);
editor.options.insertSpaces = true;
editor.options.tabSize = 2;
await executeCommand("dance.dev.setSelectionBehavior", { mode: "normal", value: "caret" });
});
this.afterAll(async () => {
await executeCommand("workbench.action.closeActiveEditor");
});
test("1 > whole-buffer", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^ 0
bar
baz
`);
// Perform all operations.
await executeCommand("dance.select.buffer");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:10:1", 6, String.raw`
foo
^^^^ 0
bar
^^^^ 0
baz
^^^ 0
`);
});
test("1 > select-line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^ 0
bar
baz
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:24:1", 6, String.raw`
foo
^^^^ 0
bar
baz
`);
});
test("1 > select-line > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^^^^ 0
bar
baz
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:36:1", 6, String.raw`
foo
bar
^^^^ 0
baz
`);
});
test("1 > extend-line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^ 0
bar
baz
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:48:1", 6, String.raw`
foo
^^^^ 0
bar
baz
`);
});
test("1 > extend-line > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^^^^ 0
bar
baz
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:60:1", 6, String.raw`
foo
^^^^ 0
bar
^^^^ 0
baz
`);
});
test("2 > line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^ 0
friends,
and welcome
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:86:1", 6, String.raw`
hello
world
my
^^^^^ 0
friends,
and welcome
`);
});
test("2 > line-extend", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^ 0
friends,
and welcome
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:100:1", 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^^^ 0
friends,
and welcome
`);
});
test("2 > line-2", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^ 0
friends,
and welcome
`);
// Perform all operations.
await executeCommand("dance.select.line.below", { count: 2 });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:116:1", 6, String.raw`
hello
world
my
friends,
^^^^^^^^^^^^^ 0
and welcome
`);
});
test("2 > line-extend-2", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^ 0
friends,
and welcome
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend", { count: 2 });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:130:1", 6, String.raw`
hello
^^^ 0
world
^^^^^^ 0
my
^^^^^ 0
friends,
^^^^^^^^^^^^^ 0
and welcome
`);
});
test("3 > line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^^ 0
world
my
friend
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:158:1", 6, String.raw`
hello
^^^^^^ 0
world
my
friend
`);
});
test("3 > line-2", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
^^^^ 0
world
my
friend
`);
// Perform all operations.
await executeCommand("dance.select.line.below", { count: 2 });
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:174:1", 6, String.raw`
hello
world
^^^^^^ 0
my
friend
`);
});
test("3 > line-2 > line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
world
^^^^^^ 0
my
friend
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:190:1", 6, String.raw`
hello
world
^ 0
my
friend
`);
});
test("3 > line-2 > line > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
world
^ 0
my
friend
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:206:1", 6, String.raw`
hello
world
my
^^^ 0
friend
`);
});
test("4 > line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
|^^^^^ 0
world
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:230:1", 6, String.raw`
hello
^^^^^^ 0
world
`);
});
test("5 > line-extend", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
|^^^^^ 0
world
^ 0
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:252:1", 6, String.raw`
hello
world
^ 0
`);
});
test("5 > line-extend > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
hello
world
^ 0
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:265:1", 6, String.raw`
hello
world
^^^^^ 0
`);
});
test("6 > line", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
| 0
bar
baz
quux
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:286:1", 6, String.raw`
foo
^^^^ 0
bar
baz
quux
`);
});
test("6 > line > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^^^^ 0
bar
baz
quux
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:299:1", 6, String.raw`
foo
bar
^^^^ 0
baz
quux
`);
});
test("6 > line > x > x", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
bar
^^^^ 0
baz
quux
`);
// Perform all operations.
await executeCommand("dance.select.line.below");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:312:1", 6, String.raw`
foo
bar
baz
^^^^ 0
quux
`);
});
test("6 > line > line-extend", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
^^^^ 0
bar
baz
quux
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:325:1", 6, String.raw`
foo
^^^^ 0
bar
^^^^ 0
baz
quux
`);
});
test("6 > line-extend", async function () {
// Set-up document to be in expected initial state.
await ExpectedDocument.apply(editor, 6, String.raw`
foo
| 0
bar
baz
quux
`);
// Perform all operations.
await executeCommand("dance.select.line.below.extend");
// Ensure document is as expected.
ExpectedDocument.assertEquals(editor, "./test/suite/commands/select-lines.md:339:1", 6, String.raw`
foo
^^^^ 0
bar
baz
quux
`);
});
groupTestsByParentName(this);
}); | the_stack |
import { Store } from 'antd/lib/form/interface';
import { User } from 'components/task-page/user-selector';
import getCore from 'cvat-core-wrapper';
import { ActionUnion, createAction, ThunkAction } from 'utils/redux';
const core = getCore();
export enum OrganizationActionsTypes {
GET_ORGANIZATIONS = 'GET_ORGANIZATIONS',
GET_ORGANIZATIONS_SUCCESS = 'GET_ORGANIZATIONS_SUCCESS',
GET_ORGANIZATIONS_FAILED = 'GET_ORGANIZATIONS_FAILED',
ACTIVATE_ORGANIZATION_SUCCESS = 'ACTIVATE_ORGANIZATION_SUCCESS',
ACTIVATE_ORGANIZATION_FAILED = 'ACTIVATE_ORGANIZATION_FAILED',
CREATE_ORGANIZATION = 'CREATE_ORGANIZATION',
CREATE_ORGANIZATION_SUCCESS = 'CREATE_ORGANIZATION_SUCCESS',
CREATE_ORGANIZATION_FAILED = 'CREATE_ORGANIZATION_FAILED',
UPDATE_ORGANIZATION = 'UPDATE_ORGANIZATION',
UPDATE_ORGANIZATION_SUCCESS = 'UPDATE_ORGANIZATION_SUCCESS',
UPDATE_ORGANIZATION_FAILED = 'UPDATE_ORGANIZATION_FAILED',
REMOVE_ORGANIZATION = 'REMOVE_ORGANIZATION',
REMOVE_ORGANIZATION_SUCCESS = 'REMOVE_ORGANIZATION_SUCCESS',
REMOVE_ORGANIZATION_FAILED = 'REMOVE_ORGANIZATION_FAILED',
INVITE_ORGANIZATION_MEMBERS = 'INVITE_ORGANIZATION_MEMBERS',
INVITE_ORGANIZATION_MEMBERS_FAILED = 'INVITE_ORGANIZATION_MEMBERS_FAILED',
INVITE_ORGANIZATION_MEMBERS_DONE = 'INVITE_ORGANIZATION_MEMBERS_DONE',
INVITE_ORGANIZATION_MEMBER_SUCCESS = 'INVITE_ORGANIZATION_MEMBER_SUCCESS',
INVITE_ORGANIZATION_MEMBER_FAILED = 'INVITE_ORGANIZATION_MEMBER_FAILED',
LEAVE_ORGANIZATION = 'LEAVE_ORGANIZATION',
LEAVE_ORGANIZATION_SUCCESS = 'LEAVE_ORGANIZATION_SUCCESS',
LEAVE_ORGANIZATION_FAILED = 'LEAVE_ORGANIZATION_FAILED',
REMOVE_ORGANIZATION_MEMBER = 'REMOVE_ORGANIZATION_MEMBERS',
REMOVE_ORGANIZATION_MEMBER_SUCCESS = 'REMOVE_ORGANIZATION_MEMBER_SUCCESS',
REMOVE_ORGANIZATION_MEMBER_FAILED = 'REMOVE_ORGANIZATION_MEMBER_FAILED',
UPDATE_ORGANIZATION_MEMBER = 'UPDATE_ORGANIZATION_MEMBER',
UPDATE_ORGANIZATION_MEMBER_SUCCESS = 'UPDATE_ORGANIZATION_MEMBER_SUCCESS',
UPDATE_ORGANIZATION_MEMBER_FAILED = 'UPDATE_ORGANIZATION_MEMBER_FAILED',
}
const organizationActions = {
getOrganizations: () => createAction(OrganizationActionsTypes.GET_ORGANIZATIONS),
getOrganizationsSuccess: (list: any[]) => createAction(
OrganizationActionsTypes.GET_ORGANIZATIONS_SUCCESS, { list },
),
getOrganizationsFailed: (error: any) => createAction(OrganizationActionsTypes.GET_ORGANIZATIONS_FAILED, { error }),
createOrganization: () => createAction(OrganizationActionsTypes.CREATE_ORGANIZATION),
createOrganizationSuccess: (organization: any) => createAction(
OrganizationActionsTypes.CREATE_ORGANIZATION_SUCCESS, { organization },
),
createOrganizationFailed: (slug: string, error: any) => createAction(
OrganizationActionsTypes.CREATE_ORGANIZATION_FAILED, { slug, error },
),
updateOrganization: () => createAction(OrganizationActionsTypes.UPDATE_ORGANIZATION),
updateOrganizationSuccess: (organization: any) => createAction(
OrganizationActionsTypes.UPDATE_ORGANIZATION_SUCCESS, { organization },
),
updateOrganizationFailed: (slug: string, error: any) => createAction(
OrganizationActionsTypes.UPDATE_ORGANIZATION_FAILED, { slug, error },
),
activateOrganizationSuccess: (organization: any | null) => createAction(
OrganizationActionsTypes.ACTIVATE_ORGANIZATION_SUCCESS, { organization },
),
activateOrganizationFailed: (error: any, slug: string | null) => createAction(
OrganizationActionsTypes.ACTIVATE_ORGANIZATION_FAILED, { slug, error },
),
removeOrganization: () => createAction(OrganizationActionsTypes.REMOVE_ORGANIZATION),
removeOrganizationSuccess: (slug: string) => createAction(
OrganizationActionsTypes.REMOVE_ORGANIZATION_SUCCESS, { slug },
),
removeOrganizationFailed: (error: any, slug: string) => createAction(
OrganizationActionsTypes.REMOVE_ORGANIZATION_FAILED, { error, slug },
),
inviteOrganizationMembers: () => createAction(OrganizationActionsTypes.INVITE_ORGANIZATION_MEMBERS),
inviteOrganizationMembersFailed: (error: any) => createAction(
OrganizationActionsTypes.INVITE_ORGANIZATION_MEMBERS_FAILED, { error },
),
inviteOrganizationMembersDone: () => createAction(OrganizationActionsTypes.INVITE_ORGANIZATION_MEMBERS_DONE),
inviteOrganizationMemberSuccess: (email: string) => createAction(
OrganizationActionsTypes.INVITE_ORGANIZATION_MEMBER_SUCCESS, { email },
),
inviteOrganizationMemberFailed: (email: string, error: any) => createAction(
OrganizationActionsTypes.INVITE_ORGANIZATION_MEMBER_FAILED, { email, error },
),
leaveOrganization: () => createAction(OrganizationActionsTypes.LEAVE_ORGANIZATION),
leaveOrganizationSuccess: () => createAction(OrganizationActionsTypes.LEAVE_ORGANIZATION_SUCCESS),
leaveOrganizationFailed: (error: any) => createAction(
OrganizationActionsTypes.LEAVE_ORGANIZATION_FAILED, { error },
),
removeOrganizationMember: () => createAction(OrganizationActionsTypes.REMOVE_ORGANIZATION_MEMBER),
removeOrganizationMemberSuccess: () => createAction(OrganizationActionsTypes.REMOVE_ORGANIZATION_MEMBER_SUCCESS),
removeOrganizationMemberFailed: (username: string, error: any) => createAction(
OrganizationActionsTypes.REMOVE_ORGANIZATION_MEMBER_FAILED, { username, error },
),
updateOrganizationMember: () => createAction(OrganizationActionsTypes.UPDATE_ORGANIZATION_MEMBER),
updateOrganizationMemberSuccess: () => createAction(OrganizationActionsTypes.UPDATE_ORGANIZATION_MEMBER_SUCCESS),
updateOrganizationMemberFailed: (username: string, role: string, error: any) => createAction(
OrganizationActionsTypes.UPDATE_ORGANIZATION_MEMBER_FAILED, { username, role, error },
),
};
export function getOrganizationsAsync(): ThunkAction {
return async function (dispatch) {
dispatch(organizationActions.getOrganizations());
try {
const organizations = await core.organizations.get();
let currentOrganization = null;
try {
// this action is dispatched after user is authentificated
// need to configure organization at cvat-core immediately to get relevant data
const curSlug = localStorage.getItem('currentOrganization');
if (curSlug) {
currentOrganization =
organizations.find((organization: any) => organization.slug === curSlug) || null;
if (currentOrganization) {
await core.organizations.activate(currentOrganization);
} else {
// not valid anymore (for example when organization
// does not exist anymore, or the user has been kicked from it)
localStorage.removeItem('currentOrganization');
}
}
dispatch(organizationActions.activateOrganizationSuccess(currentOrganization));
} catch (error) {
dispatch(
organizationActions.activateOrganizationFailed(error, localStorage.getItem('currentOrganization')),
);
} finally {
dispatch(organizationActions.getOrganizationsSuccess(organizations));
}
} catch (error) {
dispatch(organizationActions.getOrganizationsFailed(error));
}
};
}
export function createOrganizationAsync(
organizationData: Store,
onCreateSuccess?: (createdSlug: string) => void,
): ThunkAction {
return async function (dispatch) {
const { slug } = organizationData;
const organization = new core.classes.Organization(organizationData);
dispatch(organizationActions.createOrganization());
try {
const createdOrganization = await organization.save();
dispatch(organizationActions.createOrganizationSuccess(createdOrganization));
if (onCreateSuccess) onCreateSuccess(createdOrganization.slug);
} catch (error) {
dispatch(organizationActions.createOrganizationFailed(slug, error));
}
};
}
export function updateOrganizationAsync(organization: any): ThunkAction {
return async function (dispatch) {
dispatch(organizationActions.updateOrganization());
try {
const updatedOrganization = await organization.save();
dispatch(organizationActions.updateOrganizationSuccess(updatedOrganization));
} catch (error) {
dispatch(organizationActions.updateOrganizationFailed(organization.slug, error));
}
};
}
export function removeOrganizationAsync(organization: any): ThunkAction {
return async function (dispatch) {
try {
await organization.remove();
localStorage.removeItem('currentOrganization');
dispatch(organizationActions.removeOrganizationSuccess(organization.slug));
} catch (error) {
dispatch(organizationActions.removeOrganizationFailed(error, organization.slug));
}
};
}
export function inviteOrganizationMembersAsync(
organization: any,
members: { email: string; role: string }[],
onFinish: () => void,
): ThunkAction {
return async function (dispatch) {
dispatch(organizationActions.inviteOrganizationMembers());
try {
for (let i = 0; i < members.length; i++) {
const { email, role } = members[i];
organization
.invite(email, role)
.then(() => {
dispatch(organizationActions.inviteOrganizationMemberSuccess(email));
})
.catch((error: any) => {
dispatch(organizationActions.inviteOrganizationMemberFailed(email, error));
})
.finally(() => {
if (i === members.length - 1) {
dispatch(organizationActions.inviteOrganizationMembersDone());
onFinish();
}
});
}
} catch (error) {
dispatch(organizationActions.inviteOrganizationMembersFailed(error));
}
};
}
export function leaveOrganizationAsync(organization: any): ThunkAction {
return async function (dispatch, getState) {
const { user } = getState().auth;
dispatch(organizationActions.leaveOrganization());
try {
await organization.leave(user);
dispatch(organizationActions.leaveOrganizationSuccess());
localStorage.removeItem('currentOrganization');
} catch (error) {
dispatch(organizationActions.leaveOrganizationFailed(error));
}
};
}
export function removeOrganizationMemberAsync(
organization: any,
{ user, id }: { user: User; id: number },
onFinish: () => void,
): ThunkAction {
return async function (dispatch) {
dispatch(organizationActions.removeOrganizationMember());
try {
await organization.deleteMembership(id);
dispatch(organizationActions.removeOrganizationMemberSuccess());
onFinish();
} catch (error) {
dispatch(organizationActions.removeOrganizationMemberFailed(user.username, error));
}
};
}
export function updateOrganizationMemberAsync(
organization: any,
{ user, id }: { user: User; id: number },
role: string,
onFinish: () => void,
): ThunkAction {
return async function (dispatch) {
dispatch(organizationActions.updateOrganizationMember());
try {
await organization.updateMembership(id, role);
dispatch(organizationActions.updateOrganizationMemberSuccess());
onFinish();
} catch (error) {
dispatch(organizationActions.updateOrganizationMemberFailed(user.username, role, error));
}
};
}
export type OrganizationActions = ActionUnion<typeof organizationActions>; | the_stack |
import PodInstance from "../PodInstance";
import PodInstanceStatus from "../../constants/PodInstanceStatus";
import PodFixture from "../../../../../../tests/_fixtures/pods/PodFixture";
const conditions = {
unhealthyConditions: {
lastChanged: "2019-01-01T12:00:00.000Z",
lastUpdated: "2019-01-01T12:00:00.000Z",
name: "healthy",
reason: "health-reported-by-mesos",
value: "false",
},
healthyConditions: {
lastChanged: "2019-01-01T12:00:00.000Z",
lastUpdated: "2019-01-01T12:00:00.000Z",
name: "healthy",
reason: "health-reported-by-mesos",
value: "true",
},
somethingelseConditions: {
lastChanged: "2019-01-01T12:00:00.000Z",
lastUpdated: "2019-01-01T12:00:00.000Z",
name: "something-else",
reason: "health-reported-by-mesos",
value: "true",
},
};
describe("PodInstance", () => {
describe("#constructor", () => {
it("creates instances", () => {
const instanceSpec = PodFixture.instances[0];
const instance = new PodInstance({
...instanceSpec,
});
expect(instance.get()).toEqual(instanceSpec);
});
});
describe("#getAgentAddress", () => {
it("returns the given agent address", () => {
const podInstance = new PodInstance({ agentHostname: "agent-1234" });
expect(podInstance.getAgentAddress()).toEqual("agent-1234");
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getAgentAddress()).toEqual("");
});
});
describe("#getId", () => {
it("returns the given id", () => {
const podInstance = new PodInstance({ id: "instance-id-1234" });
expect(podInstance.getId()).toEqual("instance-id-1234");
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getId()).toEqual("");
});
});
describe("#getName", () => {
it("returns the given name", () => {
const podInstance = new PodInstance({ id: "instance-id-1234" });
expect(podInstance.getName()).toEqual(podInstance.getId());
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getName()).toEqual(podInstance.getId());
});
});
describe("#getAgentRegion", () => {
it("returns the given region", () => {
const podInstance = new PodInstance({ agentRegion: "Region-a" });
expect(podInstance.getAgentRegion()).toEqual("Region-a");
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getAgentRegion()).toEqual("");
});
});
describe("#getAgentZone", () => {
it("returns the given zone", () => {
const podInstance = new PodInstance({ agentZone: "Zone-a" });
expect(podInstance.getAgentZone()).toEqual("Zone-a");
});
it("returns an empty string as default zone", () => {
const podInstance = new PodInstance();
expect(podInstance.getAgentZone()).toEqual("");
});
});
describe("#getStatus", () => {
it("returns FINISHED when all containers are FINISHED", () => {
const podInstance = new PodInstance({
status: "terminal",
containers: [
{
status: "TASK_FINISHED",
},
],
});
// when we are in TERMINAL state, but all containers are FINISHED, then
// we should be considered FINISHED too.
expect(podInstance.getInstanceStatus()).toEqual(
PodInstanceStatus.FINISHED
);
});
});
describe("#getInstanceStatus", () => {
it("detects container in PENDING state", () => {
const podInstance = new PodInstance({
status: "pending",
});
expect(podInstance.getInstanceStatus()).toEqual(PodInstanceStatus.STAGED);
});
it("detects container in STAGING state", () => {
const podInstance = new PodInstance({
status: "staging",
});
expect(podInstance.getInstanceStatus()).toEqual(PodInstanceStatus.STAGED);
});
it("detects container in DEGRADED state", () => {
const podInstance = new PodInstance({
status: "degraded",
});
expect(podInstance.getInstanceStatus()).toEqual(
PodInstanceStatus.UNHEALTHY
);
});
it("detects container in TERMINAL state", () => {
const podInstance = new PodInstance({
status: "terminal",
});
expect(podInstance.getInstanceStatus()).toEqual(PodInstanceStatus.KILLED);
});
it("detects container in STABLE state", () => {
const podInstance = new PodInstance({
status: "stable",
});
// No health checks, returns RUNNING
expect(podInstance.getInstanceStatus()).toEqual(
PodInstanceStatus.RUNNING
);
});
it("detects container in UNHEALTHY state", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.unhealthyConditions],
},
],
});
// Single failing test, returns UNHEALTHY
expect(podInstance.getInstanceStatus()).toEqual(
PodInstanceStatus.UNHEALTHY
);
});
it("detects container in HEALTHY state", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.healthyConditions],
},
],
});
// All tests passing, returns HEALTHY
expect(podInstance.getInstanceStatus()).toEqual(
PodInstanceStatus.HEALTHY
);
});
});
describe("#getLastChanged", () => {
it("returns the given date", () => {
const dateString = "2016-08-31T01:01:01.001";
const podInstance = new PodInstance({ lastChanged: dateString });
expect(podInstance.getLastChanged()).toEqual(new Date(dateString));
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getLastChanged().getTime()).toBeNaN();
});
});
describe("#getLastUpdated", () => {
it("returns the given date", () => {
const dateString = "2016-08-31T01:01:01.001";
const podInstance = new PodInstance({ lastUpdated: dateString });
expect(podInstance.getLastUpdated()).toEqual(new Date(dateString));
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getLastUpdated().getTime()).toBeNaN();
});
});
describe("#getResources", () => {
it("returns the correct resources", () => {
const podInstance = new PodInstance({
resources: { cpus: 0.5, mem: 64 },
});
expect(podInstance.getResources()).toEqual({
cpus: 0.5,
mem: 64,
disk: 0,
gpus: 0,
});
});
it("returns the correct default value", () => {
const podInstance = new PodInstance();
expect(podInstance.getResources()).toEqual({
cpus: 0,
mem: 0,
disk: 0,
gpus: 0,
});
});
});
describe("#hasHealthChecks", () => {
it("returns true if all containers have health checks", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.healthyConditions],
},
{
conditions: [conditions.unhealthyConditions],
},
],
});
expect(podInstance.hasHealthChecks()).toBeTruthy();
});
it("returns true if at least one container has checks", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.healthyConditions],
},
],
});
expect(podInstance.hasHealthChecks()).toEqual(true);
});
it("returns true if instance state is not STABLE", () => {
const podInstance = new PodInstance({
status: "degraded",
containers: [
{
endpoints: [
{ name: "nginx", healthy: true },
{ name: "marathon", healthy: true },
],
},
{
endpoints: [
{ name: "nginx", healthy: true },
{ name: "marathon", healthy: true },
],
},
],
});
// It returns true in order to display the `unhelathy` state
expect(podInstance.hasHealthChecks()).toBeTruthy();
});
it("returns true if even one container is failing", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.healthyConditions],
},
{
conditions: [conditions.unhealthyConditions],
},
],
});
expect(podInstance.hasHealthChecks()).toBeTruthy();
});
it("returns false if there are no containers", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [],
});
expect(podInstance.hasHealthChecks()).toBeFalsy();
});
});
describe("#isHealthy", () => {
it("returns true if all containers are healthy", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.healthyConditions],
},
{
conditions: [conditions.healthyConditions],
},
],
});
expect(podInstance.isHealthy()).toBeTruthy();
});
it("returns true even if containers have no checks", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.somethingelseConditions],
},
],
});
expect(podInstance.isHealthy()).toBeTruthy();
});
it("returns false if at least 1 container is unhealthy", () => {
const podInstance = new PodInstance({
status: "degraded",
containers: [
{
conditions: [conditions.healthyConditions],
},
{
conditions: [conditions.unhealthyConditions],
},
],
});
expect(podInstance.isHealthy()).toBeFalsy();
});
it("returns false on unhealthy container even on udnef", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [
{
conditions: [conditions.unhealthyConditions],
},
],
});
expect(podInstance.isHealthy()).toBeFalsy();
});
it("returns true if there are no containers", () => {
const podInstance = new PodInstance({
status: "stable",
containers: [],
});
expect(podInstance.isHealthy()).toBeTruthy();
});
});
describe("#isRunning", () => {
it("returns true when status is STABLE", () => {
const podInstance = new PodInstance({ status: "stable" });
expect(podInstance.isRunning()).toBeTruthy();
});
it("returns true when status is DEGRADED", () => {
const podInstance = new PodInstance({ status: "degraded" });
expect(podInstance.isRunning()).toBeTruthy();
});
it("returns false if not DEGRADED or STABLE", () => {
const podInstance = new PodInstance({ status: "terminal" });
expect(podInstance.isRunning()).toBeFalsy();
});
});
describe("#isStaging", () => {
it("returns true when status is PENDING", () => {
const podInstance = new PodInstance({ status: "pending" });
expect(podInstance.isStaging()).toBeTruthy();
});
it("returns true when status is STAGING", () => {
const podInstance = new PodInstance({ status: "staging" });
expect(podInstance.isStaging()).toBeTruthy();
});
it("returns false if not STAGING or PENDING", () => {
const podInstance = new PodInstance({ status: "terminal" });
expect(podInstance.isStaging()).toBeFalsy();
});
});
describe("#isTerminating", () => {
it("returns true when status is TERMINAL", () => {
const podInstance = new PodInstance({ status: "terminal" });
expect(podInstance.isTerminating()).toBeTruthy();
});
it("returns false if not TERMINAL", () => {
const podInstance = new PodInstance({ status: "running" });
expect(podInstance.isTerminating()).toBeFalsy();
});
});
describe("#getIpAddresses", () => {
it("returns an array of IP Addresses", () => {
const podInstance = new PodInstance({
networks: [{ addresses: ["9.0.0.1"] }],
});
expect(podInstance.getIpAddresses()).toEqual(["9.0.0.1"]);
});
it("supports multiple networks", () => {
const podInstance = new PodInstance({
networks: [
{ addresses: ["9.0.0.1"] },
{ addresses: ["9.0.0.10", "9.0.0.11"] },
],
});
expect(podInstance.getIpAddresses()).toEqual([
"9.0.0.1",
"9.0.0.10",
"9.0.0.11",
]);
});
it("returns an empty array", () => {
const podInstance = new PodInstance({});
expect(podInstance.getIpAddresses()).toEqual([]);
});
});
}); | the_stack |
import {
Component,
OnInit,
OnChanges,
EventEmitter,
Input,
Output
} from "@angular/core";
import { queryList } from "../shared/queryList";
declare var $: any;
@Component({
selector: "query-blocks",
templateUrl: "./app/queryBlocks/queryBlocks.component.html",
inputs: [
"detectChange",
"editorHookHelp",
"saveQuery",
"setProp",
"setDocSample"
]
})
export class QueryBlocksComponent implements OnInit, OnChanges {
public queryList: any = queryList;
public queryFormat: any = {
internal: {
field: "",
query: "",
selectedField: "",
selectedQuery: "",
input: "",
analyzeTest: "",
type: ""
},
bool: {
boolparam: 0,
parent_id: 0,
id: 0,
internal: [],
minimum_should_match: "",
path: "",
type: "",
xid: 0,
parent_type: "",
score_mode: ""
}
};
public editorHookHelp: any;
public joiningQuery: any = [""];
public joiningQueryParam: any = 0;
public popoverInfo: any = {
stream: {
trigger: "hover",
placement: "top",
content:
"Shows an interactive stream of results, useful when your data is changing quickly.",
container: "body"
},
historic: {
trigger: "hover",
placement: "top",
content:
"Shows historical results, useful when your data is not changing quickly.",
container: "body"
}
};
@Input() isAppbaseApp: boolean;
@Input() responseMode: string;
@Input() mapping: any;
@Input() types: any;
@Input() selectedTypes: any;
@Input() result: any;
@Input() query_info: any;
@Input() savedQueryList: any;
@Input() finalUrl: string;
@Input() urlShare: any;
@Input() config: any;
@Input() version: number;
@Output() saveQuery = new EventEmitter<any>();
@Output() setProp = new EventEmitter<any>();
@Output() setDocSample = new EventEmitter<any>();
ngOnInit() {
this.handleEditable();
this.joiningQuery = this.result.joiningQuery;
}
ngOnChanges(nextProps) {
this.joiningQuery = this.result.joiningQuery;
if (
(nextProps &&
(nextProps.isAppbaseApp && nextProps.isAppbaseApp.currentValue)) ||
(nextProps.selectedTypes && nextProps.selectedTypes.currentValue.length)
) {
this.setPopover();
}
}
// Add the boolean query
// get the default format for query and internal query
// set the format and push into result array
addBoolQuery(parent_id: number) {
if (this.selectedTypes) {
var queryObj = JSON.parse(JSON.stringify(this.queryFormat.bool));
var internalObj = JSON.parse(JSON.stringify(this.queryFormat.internal));
queryObj.internal.push(internalObj);
queryObj.id = this.result.queryId;
queryObj.parent_id = parent_id;
this.result.queryId += 1;
this.result.resultQuery.result.push(queryObj);
this.buildQuery();
} else {
alert("Select type first.");
}
}
removeQuery() {
this.result.resultQuery.result = [];
this.buildQuery();
}
addSortBlock() {
let sortObj = {
selectedField: "",
order: "asc",
availableOptionalParams: []
};
this.result.sort.push(sortObj);
}
removeSortBlock() {
this.result.sort = [];
this.buildQuery();
}
// add internal query
addQuery(boolQuery) {
var self = this;
var queryObj = JSON.parse(JSON.stringify(self.queryFormat.internal));
boolQuery.internal.push(queryObj);
this.buildQuery();
}
// builquery - this function handles everything to build the query
buildQuery() {
var self = this;
var results = this.result.resultQuery.result;
var es_final = {};
if (results.length) {
var finalresult = {};
if (results.length > 1) {
es_final["query"] = {
bool: finalresult
};
} else {
if (results[0].availableQuery && results[0].internal.length > 1) {
es_final["query"] = {
bool: finalresult
};
} else {
if (self.queryList["boolQuery"][results[0]["boolparam"]] === "must") {
es_final["query"] = finalresult;
} else {
es_final["query"] = {
bool: finalresult
};
}
}
}
results.forEach(function(result) {
result.availableQuery = self.buildInsideQuery(result);
});
var isBoolPresent = true;
results.forEach(function(result0) {
results.forEach(function(result1) {
if (result1.parent_id == result0.id) {
var current_query = {
bool: {}
};
var currentBool = self.queryList["boolQuery"][result1["boolparam"]];
current_query["bool"][currentBool] = result1.availableQuery;
if (currentBool === "should") {
current_query["bool"]["minimum_should_match"] =
result1.minimum_should_match;
}
if (self.joiningQuery[self.joiningQueryParam] === "nested") {
current_query["bool"]["nested"]["path"] = result1.path;
current_query["bool"]["nested"]["score_mode"] =
result1.score_mode;
isBoolPresent = false;
}
result0.availableQuery.push(current_query);
}
});
});
results.forEach(function(result) {
if (result.parent_id === 0) {
var currentBool = self.queryList["boolQuery"][result["boolparam"]];
if (
self.joiningQuery &&
self.joiningQuery[self.joiningQueryParam] === "nested"
) {
finalresult["nested"] = {
path: result.path,
score_mode: result.score_mode,
query: {
bool: {
[currentBool]: result.availableQuery
}
}
};
isBoolPresent = false;
} else if (
self.joiningQuery &&
self.joiningQuery[self.joiningQueryParam] === "has_child"
) {
finalresult[currentBool] = {
has_child: {
type: result.type,
score_mode: result.score_mode,
query: result.availableQuery
}
};
} else if (
self.joiningQuery &&
self.joiningQuery[self.joiningQueryParam] === "has_parent"
) {
finalresult[currentBool] = {
has_parent: {
parent_type: result.parent_type,
query: result.availableQuery
}
};
} else if (
self.joiningQuery &&
self.joiningQuery[self.joiningQueryParam] === "parent_id"
) {
finalresult[currentBool] = {
parent_id: {
type: result.type,
id: result.xid
}
};
} else {
if (result.internal.length > 1 || currentBool !== "must") {
finalresult[currentBool] = result.availableQuery;
} else {
if (results.length > 1) {
finalresult[currentBool] = result.availableQuery;
} else {
finalresult = result.availableQuery[0];
es_final["query"] = finalresult;
}
}
}
if (currentBool === "should") {
finalresult["minimum_should_match"] = result.minimum_should_match;
} else {
// condition required to reset when someone changes back from should to another bool type
if (finalresult.hasOwnProperty("minimum_should_match")) {
delete finalresult["minimum_should_match"];
}
}
}
});
if (!isBoolPresent) {
es_final["query"] = es_final["query"]["bool"];
}
} else {
es_final["query"] = {
match_all: {}
};
}
// apply sort
if (self.result.sort) {
self.result.sort.map(sortObj => {
if (sortObj.selectedField) {
if (!es_final.hasOwnProperty("sort")) {
es_final["sort"] = [];
}
let obj = {};
if (sortObj._geo_distance) {
obj = {
["_geo_distance"]: {
[sortObj.selectedField]: {
lat: sortObj._geo_distance.lat,
lon: sortObj._geo_distance.lon
},
order: sortObj.order,
distance_type: sortObj._geo_distance.distance_type,
unit: sortObj._geo_distance.unit || "m"
}
};
if (sortObj.mode) {
obj["_geo_distance"]["mode"] = sortObj.mode;
}
} else {
obj = {
[sortObj.selectedField]: {
order: sortObj.order
}
};
if (sortObj.mode) {
obj[sortObj.selectedField]["mode"] = sortObj.mode;
}
if (sortObj.missing) {
obj[sortObj.selectedField]["missing"] = sortObj.missing;
}
}
es_final["sort"].push(obj);
}
});
}
this.result.resultQuery.final = JSON.stringify(es_final, null, 2);
try {
this.editorHookHelp.setValue(self.result.resultQuery.final);
} catch (e) {
console.log(e);
}
//set input state
try {
this.urlShare.inputs["result"] = this.result;
this.urlShare.createUrl();
} catch (e) {
console.log(e);
}
}
buildInsideQuery(result) {
var objChain = [];
result.internal.forEach(
function(val0) {
var childExists = false;
val0.appliedQuery = this.createQuery(val0, childExists);
}.bind(this)
);
result.internal.forEach(function(val) {
objChain.push(val.appliedQuery);
});
return objChain;
}
buildSubQuery() {
var result = this.result.resultQuery.result[0];
result.forEach(
function(val0) {
if (val0.parent_id != 0) {
result.forEach(
function(val1) {
if (val0.parent_id == val1.id) {
val1.appliedQuery["bool"]["must"].push(val0.appliedQuery);
}
}.bind(this)
);
}
}.bind(this)
);
}
// Createquery until query is selected
createQuery(val, childExists) {
var queryParam = {
query: "*",
field: "*",
queryFlag: true,
fieldFlag: true
};
if (val.analyzeTest === "" || val.type === "" || val.query === "") {
queryParam.queryFlag = false;
}
if (val.field === "") {
queryParam.fieldFlag = false;
}
if (queryParam.queryFlag) {
return val.appliedQuery;
} else {
if (queryParam.fieldFlag) {
queryParam.field = val.selectedField;
}
var sampleobj = this.setQueryFormat(
queryParam.query,
queryParam.field,
val
);
return sampleobj;
}
}
setQueryFormat(query, field, val) {
var sampleobj = {};
sampleobj[query] = {};
sampleobj[query][field] = val.input;
return sampleobj;
}
toggleBoolQuery() {
if (
this.result.resultQuery.result.length < 1 &&
this.selectedTypes.length > 0
) {
this.addBoolQuery(0);
} else {
this.removeQuery();
}
}
toggleSortQuery() {
if (this.result.sort) {
console.log("coming");
if (this.result.sort.length < 1 && this.selectedTypes.length > 0) {
this.addSortBlock();
} else {
this.removeSortBlock();
}
} else {
this.result.sort = [];
this.addSortBlock();
}
}
// handle the body click event for editable
// close all the select2 whene clicking outside of editable-element
handleEditable() {
$("body").on("click", function(e) {
var target = $(e.target);
if (
target.hasClass(".editable-pack") ||
target.parents(".editable-pack").length
) {
} else {
$(".editable-pack").removeClass("on");
}
});
}
// open save query modal
openModal() {
$("#saveQueryModal").modal("show");
}
setPropIn(propObj: any) {
this.setProp.emit(propObj);
}
setDocSampleEve(link) {
this.setDocSample.emit(link);
}
setJoiningQueryEve(obj) {
this.joiningQueryParam = obj.param;
this.result.resultQuery.availableFields = obj.allFields;
this.buildQuery();
}
setPopover() {
setTimeout(() => {
$(".responseMode .stream").popover(this.popoverInfo.stream);
$(".responseMode .historic").popover(this.popoverInfo.historic);
}, 1000);
}
changeMode(mode) {
this.responseMode = mode;
const propInfo = {
name: "responseMode",
value: mode
};
this.setProp.emit(propInfo);
}
} | the_stack |
import { Utility } from "@hpcc-js/common";
import * as Comms from "./Comms";
function nestedRowFix(row) {
if (row.Row && row.Row instanceof Array) {
return row.Row.map(nestedRowFix);
} else if (row instanceof Object) {
for (const key in row) {
row[key] = nestedRowFix(row[key]);
}
}
return row;
}
// Basic Comms ---
let enableBasicCommsCache = false;
let basicCommsCache = {};
function BasicComms() {
Comms.Basic.call(this);
}
BasicComms.prototype = Object.create(Comms.Basic.prototype);
BasicComms.prototype.jsonp = function (url, request) {
const requestStr = JSON.stringify(request);
if (enableBasicCommsCache && basicCommsCache[url] && basicCommsCache[url][requestStr]) {
return Promise.resolve(basicCommsCache[url][requestStr]);
}
return Comms.Basic.prototype.jsonp.apply(this, arguments).then(function (response) {
if (enableBasicCommsCache) {
if (!basicCommsCache[url]) {
basicCommsCache[url] = {};
}
basicCommsCache[url][requestStr] = response;
}
return response;
});
};
// WsWorkunits ---
function WsWorkunits(baseUrl) {
BasicComms.call(this);
this.url(baseUrl + "WsWorkunits/");
}
WsWorkunits.prototype = Object.create(BasicComms.prototype);
WsWorkunits.prototype.wuQuery = function (options) {
const url = this.getUrl({
pathname: "WsWorkunits/WUQuery.json"
});
const request = {
Wuid: "",
Type: "",
Cluster: "",
RoxieCluster: "",
Owner: "",
State: "",
StartDate: "",
EndDate: "",
ECL: "",
Jobname: "",
LogicalFile: "",
LogicalFileSearchType: "",
/*
ApplicationValues>
ApplicationValue>
Application: "",
Name: "",
Value: "",
/ApplicationValue>
/ApplicationValues>
*/
After: "",
Before: "",
Count: "",
PageSize: 100,
PageStartFrom: 0,
PageEndAt: "",
LastNDays: "",
Sortby: "",
Descending: 0,
CacheHint: ""
};
for (const key in options) {
request[key] = options[key];
}
return this.jsonp(url, request).then(function (response) {
if (response.WUQueryResponse && response.WUQueryResponse.Workunits) {
return response.WUQueryResponse.Workunits.ECLWorkunit;
}
return [];
});
};
// Workunit ---
function Workunit(baseUrl, wuid) {
BasicComms.call(this);
this.url(baseUrl + "WsWorkunits/");
this._wuid = wuid;
}
Workunit.prototype = Object.create(BasicComms.prototype);
Workunit.prototype.wuInfo = function (options) {
const url = this.getUrl({
pathname: "WsWorkunits/WUInfo.json"
});
const request = {
Wuid: this._wuid,
TruncateEclTo64k: true,
IncludeExceptions: false,
IncludeGraphs: false,
IncludeSourceFiles: false,
IncludeResults: false,
IncludeResultsViewNames: false,
IncludeVariables: false,
IncludeTimers: false,
IncludeResourceURLs: false,
IncludeDebugValues: false,
IncludeApplicationValues: false,
IncludeWorkflows: false,
IncludeXmlSchemas: false,
SuppressResultSchemas: true
};
for (const key in options) {
request[key] = options[key];
}
return this.jsonp(url, request).then(function (response) {
if (enableBasicCommsCache) {
const retVal = { WUInfoResponse: { Workunit: {} } };
for (const key in options) {
const includeKey = key.substring(7);
retVal.WUInfoResponse.Workunit[includeKey] = response.WUInfoResponse.Workunit[includeKey];
}
basicCommsCache[url][JSON.stringify(request)] = retVal;
}
return response;
});
};
Workunit.prototype.wuUpdate = function (options) {
const url = this.getUrl({
pathname: "WsWorkunits/WUUpdate.json"
});
const request = {
Wuid: this._wuid
};
for (const key in options) {
request[key] = options[key];
}
return this.post(url, request);
};
Workunit.prototype.appData = function (appID, key, _) {
if (arguments.length === 2) {
return this.wuInfo({
IncludeApplicationValues: true
}).then(function (response) {
let persistString;
if (response.WUInfoResponse && response.WUInfoResponse.Workunit && response.WUInfoResponse.Workunit.ApplicationValues && response.WUInfoResponse.Workunit.ApplicationValues.ApplicationValue) {
response.WUInfoResponse.Workunit.ApplicationValues.ApplicationValue.filter(function (row) {
return row.Application === appID && row.Name === key;
}).forEach(function (row) {
persistString = row.Value;
});
}
return persistString;
});
} else if (arguments.length === 3) {
return this.wuUpdate({
"ApplicationValues.ApplicationValue.0.Application": appID,
"ApplicationValues.ApplicationValue.0.Name": key,
"ApplicationValues.ApplicationValue.0.Value": _,
"ApplicationValues.ApplicationValue.itemcount": 1
});
}
};
Workunit.prototype.results = function () {
const context = this;
return this.wuInfo({
IncludeResults: true
}).then(function (response) {
let retVal = [];
if (Utility.exists("WUInfoResponse.Workunit.Results.ECLResult", response)) {
retVal = response.WUInfoResponse.Workunit.Results.ECLResult.map(function (result) {
return new WUResult(context.getUrl({ pathname: "WsWorkunits/" }), context._wuid, result.Name);
});
}
return retVal;
});
};
Workunit.prototype.result = function (dataSource, resultName) {
dataSource = dataSource || this._wuid;
return createResult(dataSource, resultName);
};
// Workunit Result ---
function WUResult(baseUrl, wuid, name) {
BasicComms.call(this);
this.url(baseUrl + "WUResult.json");
this._wuid = wuid;
this._name = name;
this._xmlSchema = null;
}
WUResult.prototype = Object.create(BasicComms.prototype);
WUResult.prototype.wuid = function (_) {
if (!arguments.length) return this._wuid;
this._wuid = _;
return this;
};
WUResult.prototype.name = function (_) {
if (!arguments.length) return this._name;
this._name = _;
return this;
};
WUResult.prototype.query = function (options, filter) {
options = options || {};
filter = filter || {};
const request = {
Wuid: this._wuid,
ResultName: this._name,
SuppressXmlSchema: true,
Start: 0,
Count: -1
};
for (const key in options) {
request[key] = options[key];
}
let filterIdx = 0;
for (const fKey in filter) {
request["FilterBy.NamedValue." + filterIdx + ".Name"] = fKey;
request["FilterBy.NamedValue." + filterIdx + ".Value"] = filter[fKey];
++filterIdx;
}
if (filterIdx) {
request["FilterBy.NamedValue.itemcount"] = filterIdx;
}
const context = this;
return this.jsonp(this.url(), request).then(function (response) {
if (response.WUResultResponse &&
response.WUResultResponse.Result &&
response.WUResultResponse.Result[context._name]) {
if (enableBasicCommsCache) {
basicCommsCache[context.url()][JSON.stringify(request)] = {
WUResultResponse: {
Result: response.WUResultResponse.Result
}
};
}
context._xmlSchema = response.WUResultResponse.Result.XmlSchema;
return nestedRowFix(response.WUResultResponse.Result[context._name]);
}
return [];
});
};
// Logical File ---
function LogicalFile(baseUrl, logicalName) {
BasicComms.call(this);
this.url(baseUrl + "WUResult.json");
this._logicalName = logicalName;
this._xmlSchema = null;
}
LogicalFile.prototype = Object.create(BasicComms.prototype);
LogicalFile.prototype.query = function (options, filter) {
options = options || {};
filter = filter || {};
const request = {
Cluster: "hthor", // TODO: Should not be needed ---
LogicalName: this._logicalName,
SuppressXmlSchema: this._xmlSchema !== null,
Start: 0,
Count: -1
};
for (const key in options) {
request[key] = options[key];
}
let filterIdx = 0;
for (const fKey in filter) {
request["FilterBy.NamedValue." + filterIdx + ".Name"] = fKey;
request["FilterBy.NamedValue." + filterIdx + ".Value"] = filter[fKey];
++filterIdx;
}
if (filterIdx) {
request["FilterBy.NamedValue.itemcount"] = filterIdx;
}
const context = this;
return this.jsonp(this.url(), request).then(function (response) {
if (response.WUResultResponse &&
response.WUResultResponse.Result &&
response.WUResultResponse.Result.Row) {
context._xmlSchema = response.WUResultResponse.Result.XmlSchema;
return nestedRowFix(response.WUResultResponse.Result.Row);
}
return [];
});
};
// Roxie Query ---
function RoxieQuery(baseUrl, resultName) {
BasicComms.call(this);
const urlParts = baseUrl.split("/");
let queryName = urlParts.pop();
if (queryName.toLowerCase() === "json") {
queryName = urlParts.pop();
}
this._queryName = queryName;
this._resultName = resultName;
this.url(urlParts.join("/") + "/" + queryName + "/json");
}
RoxieQuery.prototype = Object.create(BasicComms.prototype);
function trimRight(str) {
if (str && str.replace) {
return str.replace(/ +$/, "");
}
return str;
}
function postFilter(results, filter) {
return results.filter(function (row) {
for (const key in filter) {
if (row[key] !== undefined && trimRight(filter[key]) !== trimRight(row[key])) {
return false;
}
}
return true;
});
}
function locateRoxieResponse(response) {
// v5 and v6 compatible ---
for (const key in response) {
if (response[key].Row && response[key].Row instanceof Array) {
return response;
}
const retVal = locateRoxieResponse(response[key]);
if (retVal) {
return retVal;
}
}
return null;
}
RoxieQuery.prototype.query = function (options, filter) {
options = options || {};
filter = filter || {};
const request = {
};
for (const key in options) {
request[key] = options[key];
}
for (const fKey in filter) {
request[fKey] = filter[fKey];
}
const context = this;
return this.jsonp(this.url(), request).then(function (response) {
response = locateRoxieResponse(response);
if (response) {
if (context._resultName) {
if (response && response[context._resultName] && response[context._resultName].Row) {
return nestedRowFix(postFilter(response[context._resultName].Row, filter));
}
} else {
for (const key in response) {
if (response[key].Row) {
return nestedRowFix(postFilter(response[key].Row, filter));
}
}
}
}
return [];
});
};
export function createResult(_espUrl, dataSource, resultName?) {
const espUrl = new Comms.ESPUrl()
.url(_espUrl)
;
if (dataSource.indexOf("http") === 0) {
return new RoxieQuery(dataSource, resultName);
} else if (dataSource.indexOf("~") === 0 || dataSource.indexOf("::") >= 0) {
return new LogicalFile(espUrl.getUrl({ pathname: "WsWorkunits/" }), dataSource);
} else if (dataSource) {
return new WUResult(espUrl.getUrl({ pathname: "WsWorkunits/" }), dataSource, resultName);
}
return null;
}
export function enableCache(_?: any): any | undefined {
if (!arguments.length) return enableBasicCommsCache;
enableBasicCommsCache = _;
if (!_) {
basicCommsCache = {};
}
}
export function cache(_?: any): any | undefined {
if (!arguments.length) return basicCommsCache;
basicCommsCache = _;
}
export function createConnection(url) {
url = url || document.URL;
const testURL = new Comms.ESPUrl()
.url(url)
;
if (testURL.isWsWorkunits()) {
const espConnection = Comms.createESPConnection(url);
if (espConnection instanceof Comms.WsWorkunits && espConnection.wuid()) {
return new Workunit(espConnection.getUrl({ pathname: "" }), espConnection.wuid())
.url(url)
;
}
}
return null;
}
export function flattenResult(result, mappings) {
const retVal = {
columns: [],
data: []
};
if (result && result.length) {
const colIdx = {};
if (mappings && mappings.length) {
mappings.forEach(function (mapping) {
colIdx[mapping.value.toLowerCase()] = retVal.columns.length;
retVal.columns.push(mapping.key);
});
} else {
for (const key in result[0]) {
colIdx[key.toLowerCase()] = retVal.columns.length;
retVal.columns.push(key);
}
}
result.forEach(function (row, rowIdx) {
const rowArr = [];
for (const key in row) {
if (colIdx[key.toLowerCase()] !== undefined) {
rowArr[colIdx[key.toLowerCase()]] = row[key];
}
}
retVal.data.push(rowArr);
});
}
return retVal;
} | the_stack |
namespace pxt.py {
///
/// VARIABLE SCOPE ANALYSIS
///
interface VarRead {
kind: "read",
node: ts.Identifier,
varName: string
}
type VarDeclNodeType = ts.VariableDeclaration | ts.ParameterDeclaration
| ts.FunctionExpression | ts.FunctionDeclaration | ts.ArrowFunction
| ts.MethodDeclaration
interface VarDecl {
kind: "decl",
node: VarDeclNodeType,
varName: string
}
type VarAssignNodeType = ts.AssignmentExpression<ts.AssignmentOperatorToken>
| ts.PostfixUnaryExpression | ts.PrefixUnaryExpression
interface VarAssign {
kind: "assign",
node: VarAssignNodeType,
varName: string
}
function isAssignmentExpression(s: ts.Node): s is ts.AssignmentExpression<ts.AssignmentOperatorToken> {
// why is this not built in...
const AssignmentOperators: ts.AssignmentOperator[] = [
ts.SyntaxKind.EqualsToken, ts.SyntaxKind.PlusEqualsToken,
ts.SyntaxKind.MinusEqualsToken, ts.SyntaxKind.AsteriskEqualsToken,
ts.SyntaxKind.AsteriskAsteriskEqualsToken, ts.SyntaxKind.SlashEqualsToken,
ts.SyntaxKind.PercentEqualsToken, ts.SyntaxKind.LessThanLessThanEqualsToken,
ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
ts.SyntaxKind.AmpersandEqualsToken, ts.SyntaxKind.BarEqualsToken,
ts.SyntaxKind.CaretEqualsToken
]
return ts.isBinaryExpression(s)
&& AssignmentOperators.some(o => s.operatorToken.kind === o)
}
type VarUse = VarRead | VarAssign
type VarRef = VarRead | VarDecl | VarAssign
interface VarScope {
readonly refs: VarRef[],
readonly children: VarScope[],
owner: ts.FunctionLikeDeclaration | undefined
}
function computeVarScopes(node: ts.Node): VarScope {
const EMPTY: VarScope = { refs: [], children: [], owner: undefined }
return walk(node)
function walk(s: ts.Node | undefined): VarScope {
if (!s)
return EMPTY
// ignore these subtrees because identifiers
// in here are not variable usages
if (ts.isPropertyAccessOrQualifiedName(s))
return EMPTY
// variable usage
if (ts.isIdentifier(s)) {
return {
refs: [{
kind: "read",
node: s,
varName: s.text
}],
children: [],
owner: undefined
}
}
// variable decleration
if (ts.isVariableDeclaration(s) || ts.isParameter(s)) {
const init = walk(s.initializer)
return {
refs: [...init.refs, {
kind: "decl",
node: s,
varName: s.name.getText()
}],
children: init.children,
owner: undefined
}
}
// variable assignment
if (ts.isPrefixUnaryExpression(s) || ts.isPostfixUnaryExpression(s)) {
const operandUse = walk(s.operand)
const varName = s.operand.getText()
const assign: VarScope = {
refs: [{
kind: "assign",
node: s,
varName,
}],
children: [],
owner: undefined
}
return merge(operandUse, assign)
}
if (isAssignmentExpression(s)) {
const rightUse = walk(s.right)
let leftUse: VarScope | undefined;
if (s.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {
leftUse = walk(s.left)
}
const varName = s.left.getText()
const assign: VarScope = {
refs: [{
kind: "assign",
node: s,
varName,
}],
children: [],
owner: undefined
}
return merge(leftUse, merge(rightUse, assign))
}
// new scope
if (ts.isFunctionExpression(s)
|| ts.isArrowFunction(s)
|| ts.isFunctionDeclaration(s)
|| ts.isMethodDeclaration(s)) {
const fnName = s.name?.getText()
let fnDecl: VarDecl | undefined = undefined;
if (fnName) {
fnDecl = {
kind: "decl",
node: s,
varName: fnName
}
}
const params = s.parameters
.map(p => walk(p))
.reduce(merge, EMPTY)
const body = walk(s.body)
const child = merge(params, body)
child.owner = s
return {
refs: fnDecl ? [fnDecl] : [],
children: [child],
owner: undefined
}
}
// keep walking
return s.getChildren()
.map(walk)
.reduce(merge, EMPTY)
}
function merge(p: VarScope | undefined, n: VarScope | undefined): VarScope {
if (!p || !n)
return p || n || EMPTY
return {
refs: [...p.refs, ...n.refs],
children: [...p.children, ...n.children],
owner: p.owner || n.owner
}
}
}
interface VarUsages {
globalUsage: VarUse[],
nonlocalUsage: VarUse[],
localUsage: VarUse[],
environmentUsage: VarUse[],
children: VarUsages[],
owner: ts.FunctionLikeDeclaration | undefined
}
function getExplicitGlobals(u: VarUsages): VarAssign[] {
return [...u.globalUsage, ...u.environmentUsage]
.filter(r => r.kind === "assign")
.map(r => r as VarAssign)
}
function getExplicitNonlocals(u: VarUsages): VarAssign[] {
return u.nonlocalUsage
.filter(r => r.kind === "assign")
.map(r => r as VarAssign)
}
type Decls = { [key: string]: VarDecl }
function computeVarUsage(s: VarScope, globals?: Decls, nonlocals: Decls[] = []): VarUsages {
const globalUsage: VarUse[] = []
const nonlocalUsage: VarUse[] = []
const localUsage: VarUse[] = []
const environmentUsage: VarUse[] = []
const locals: Decls = {}
for (const r of s.refs) {
if (r.kind === "read" || r.kind === "assign") {
if (locals[r.varName])
localUsage.push(r)
else if (lookupNonlocal(r))
nonlocalUsage.push(r)
else if (globals && globals[r.varName])
globalUsage.push(r)
else
environmentUsage.push(r)
} else {
locals[r.varName] = r
}
}
const nextGlobals = globals || locals
const nextNonlocals = globals ? [...nonlocals, locals] : []
const children = s.children
.map(s => computeVarUsage(s, nextGlobals, nextNonlocals))
return {
globalUsage,
nonlocalUsage,
localUsage,
environmentUsage,
children,
owner: s.owner
}
function lookupNonlocal(use: VarUse): VarDecl | undefined {
return nonlocals
.map(d => d[use.varName])
.reduce((p, n) => n || p, undefined)
}
}
export interface ScopeVariableLookup {
getExplicitGlobals(fn: ts.FunctionLikeDeclaration): ts.Identifier[];
getExplicitNonlocals(fn: ts.FunctionLikeDeclaration): ts.Identifier[];
}
export function computeScopeVariableLookup(n: ts.Node): ScopeVariableLookup {
const scopeInfo = computeVarScopes(n)
const usageInfo = computeVarUsage(scopeInfo)
const globalsByFn = new Map()
const nonlocalsByFn = new Map()
walk(usageInfo)
return {
getExplicitGlobals: (fn) => globalsByFn.get(fn) || [],
getExplicitNonlocals: (fn) => nonlocalsByFn.get(fn) || [],
}
function toId(a: VarAssign): ts.Identifier | undefined {
let i = (a.node as ts.PrefixUnaryExpression | ts.PostfixUnaryExpression).operand
|| (a.node as ts.BinaryExpression).left
return ts.isIdentifier(i) ? i : undefined
}
function toIds(ns: VarAssign[]): ts.Identifier[] {
return ns
.map(toId)
.filter(i => !!i)
.map(i => i as ts.Identifier)
.reduce((p, n) => p.find(r => r.text === n.text) ? p : [...p, n], [] as ts.Identifier[])
}
function walk(s: VarUsages) {
const gs = toIds(getExplicitGlobals(s))
globalsByFn.set(s.owner, gs)
const ls = toIds(getExplicitNonlocals(s))
nonlocalsByFn.set(s.owner, ls)
s.children.forEach(walk)
}
}
// printing
function toStringVarRef(i: VarRef): string {
return `${i.kind}:${i.varName}`
}
function toStringVarScopes(s: VarScope): string {
function internalToStringVarScopes(s: VarScope): string[] {
const refs = s.refs.map(toStringVarRef).join(", ")
const children = s.children
.map(internalToStringVarScopes)
.map(c => c.map(indent1))
.map(c => ["{", ...c, "}"])
.reduce((p, n) => [...p, ...n], [])
return [
refs,
...children
]
}
return internalToStringVarScopes(s).join("\n")
}
function toStringVarUsage(s: VarUsages): string {
function internalToStringVarUsage(s: VarUsages): string[] {
const gs = s.globalUsage.map(toStringVarRef).join(', ')
const ns = s.nonlocalUsage.map(toStringVarRef).join(', ')
const ls = s.localUsage.map(toStringVarRef).join(', ')
const es = s.environmentUsage.map(toStringVarRef).join(', ')
const children = s.children
.map(internalToStringVarUsage)
.map(c => c.map(indent1))
.map(c => ["{", ...c, "}"])
.reduce((p, n) => [...p, ...n], [])
return [
gs ? "global " + gs : "",
ns ? "nonlocal " + ns : "",
ls ? "local " + ls : "",
es ? "env " + es : "",
...children
].filter(i => !!i)
}
return internalToStringVarUsage(s).join("\n")
}
// for debugging
export function toStringVariableScopes(n: ts.Node) {
const varScopes = computeVarScopes(n)
const varUsage = computeVarUsage(varScopes)
return toStringVarScopes(varScopes) + "\n\n\n" + toStringVarUsage(varUsage)
}
} | the_stack |
import {MultiClassClassificationModels} from '../../Models';
import React, {useCallback, useEffect, useState, useRef} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {
Canvas,
CanvasRenderingContext2D,
Image,
ImageUtil,
media,
MobileModel,
Module,
Tensor,
torch,
torchvision,
} from 'react-native-pytorch-core';
// Must be specified as hex to be parsed correctly.
const COLOR_CANVAS_BACKGROUND = '#4F25C6';
const COLOR_TRAIL_STROKE = '#FFFFFF';
type TrailPoint = {
x: number;
y: number;
};
type MNISTResult = {
num: number;
score: number;
};
let model0: Module | null = null;
async function getModel() {
if (model0 != null) {
return model0;
}
const filePath = await MobileModel.download(
MultiClassClassificationModels[0].model,
);
model0 = await torch.jit._loadForMobile(filePath);
return model0;
}
const HEX_RGB_RE = /^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
function hexRgbToBytes(hexRgb: string): number[] {
const match = HEX_RGB_RE.exec(hexRgb);
if (!match) {
throw `Invalid color hex string: ${hexRgb}`;
}
return match.slice(1).map(s => parseInt(s, 16));
}
/*
Tensor input is expected to have shape CHW and range [0, 1].
This is a vectorized version of looping over every pixel:
d0 = colorCartesianDistance(pixelColor, backgroundColor)
d1 = colorCartesianDistance(pixelColor, foregroundColor)
value = d0 / (d0 + d1)
Where, for 3-channel data:
colorCartesianDistance = function([r0, g0, b0], [r1, g1, b1]) => (
Math.sqrt((r0 - r1) * (r0 - r1) + (g0 - g1) * (g0 - g1) + (b0 - b1) * (b0 - b1))
);
*/
function maximizeContrast(
tensor: Tensor,
backgroundTensor: Tensor,
foregroundTensor: Tensor,
): Tensor {
const d0Diff = tensor.sub(backgroundTensor);
const d0 = d0Diff.mul(d0Diff).sum(0, {keepdim: true}).sqrt();
const d1Diff = tensor.sub(foregroundTensor);
const d1 = d1Diff.mul(d1Diff).sum(0, {keepdim: true}).sqrt();
return d0.div(d0.add(d1));
}
/**
* The React hook provides MNIST model inference on an input image.
*/
function useMNISTModel() {
const processImage = useCallback(async (image: Image) => {
// Runs model inference on input image
const blob = media.toBlob(image);
const imageTensor = torch.fromBlob(blob, [
image.getHeight(),
image.getWidth(),
3,
]);
const grayscale = torchvision.transforms.grayscale();
const resize = torchvision.transforms.resize(28);
const normalize = torchvision.transforms.normalize([0.1307], [0.3081]);
const bgColorGrayscale = grayscale(
torch
.tensor([[hexRgbToBytes(COLOR_CANVAS_BACKGROUND)]])
.permute([2, 0, 1])
.div(255),
);
const fgColorGrayscale = grayscale(
torch
.tensor([[hexRgbToBytes(COLOR_TRAIL_STROKE)]])
.permute([2, 0, 1])
.div(255),
);
let tensor = imageTensor.permute([2, 0, 1]).div(255);
tensor = resize(tensor);
tensor = grayscale(tensor);
tensor = maximizeContrast(tensor, bgColorGrayscale, fgColorGrayscale);
tensor = normalize(tensor);
tensor = tensor.unsqueeze(0);
const model = await getModel();
const output = await model.forward<Tensor, Tensor[]>(tensor);
const softmax = output[0].squeeze(0).softmax(-1);
const sortedScore: MNISTResult[] = [];
softmax
.data()
.forEach((score, index) => sortedScore.push({score: score, num: index}));
return sortedScore.sort((a, b) => b.score - a.score);
}, []);
return {
processImage,
};
}
/**
* The React hook provides MNIST inference using the image data extracted from
* a canvas.
*
* @param canvasSize The size of the square canvas
*/
function useMNISTCanvasInference(canvasSize: number) {
const [result, setResult] = useState<MNISTResult[]>();
const isRunningInferenceRef = useRef(false);
const {processImage} = useMNISTModel();
const classify = useCallback(
async (ctx: CanvasRenderingContext2D, forceRun: boolean = false) => {
// Return immediately if canvas is size 0 or if an inference is
// already in-flight. Ignore in-flight inference if `forceRun` is set to
// true.
if (canvasSize === 0 || (isRunningInferenceRef.current && !forceRun)) {
return;
}
// Set inference running if not force run
if (!forceRun) {
isRunningInferenceRef.current = true;
}
// Get image data center crop
const imageData = await ctx.getImageData(0, 0, canvasSize, canvasSize);
// Convert image data to image.
const image: Image = await ImageUtil.fromImageData(imageData);
// Release image data to free memory
imageData.release();
// Run MNIST inference on the image
const processedResult = await processImage(image);
// Release image to free memory
image.release();
// Set result state to force re-render of component that uses this hook
setResult(processedResult);
// If not force run, add a little timeout to give device time to process
// other things
if (!forceRun) {
setTimeout(() => {
isRunningInferenceRef.current = false;
}, 100);
}
},
[isRunningInferenceRef, canvasSize, processImage, setResult],
);
return {
result,
classify,
};
}
type NumberLabelSet = {
english: string;
chinese: string;
asciiSymbol: string;
spanish: string;
};
const numLabels: NumberLabelSet[] = [
{
english: 'zero',
chinese: '零',
asciiSymbol: '🄌',
spanish: 'cero',
},
{
english: 'one',
chinese: '一',
asciiSymbol: '➊',
spanish: 'uno',
},
{
english: 'two',
chinese: '二',
asciiSymbol: '➋',
spanish: 'dos',
},
{
english: 'three',
chinese: '三',
asciiSymbol: '➌',
spanish: 'tres',
},
{
english: 'four',
chinese: '四',
asciiSymbol: '➍',
spanish: 'cuatro',
},
{
english: 'five',
chinese: '五',
asciiSymbol: '➎',
spanish: 'cinco',
},
{
english: 'six',
chinese: '六',
asciiSymbol: '➏',
spanish: 'seis',
},
{
english: 'seven',
chinese: '七',
asciiSymbol: '➐',
spanish: 'siete',
},
{
english: 'eight',
chinese: '八',
asciiSymbol: '➑',
spanish: 'ocho',
},
{
english: 'nine',
chinese: '九',
asciiSymbol: '➒',
spanish: 'nueve',
},
];
// This is an example of creating a simple animation using Animator utility class
export default function MNIST() {
const [canvasSize, setCanvasSize] = useState<number>(0);
// `ctx` is drawing context to draw shapes
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
const {classify, result} = useMNISTCanvasInference(canvasSize);
const trailRef = useRef<TrailPoint[]>([]);
const [drawingDone, setDrawingDone] = useState(false);
const animationHandleRef = useRef<number | null>(null);
const draw = useCallback(() => {
if (animationHandleRef.current != null) return;
if (ctx != null) {
animationHandleRef.current = requestAnimationFrame(() => {
const trail = trailRef.current;
if (trail != null) {
// fill background by drawing a rect
ctx.fillStyle = COLOR_CANVAS_BACKGROUND;
ctx.fillRect(0, 0, canvasSize, canvasSize);
// Draw the trail
ctx.strokeStyle = COLOR_TRAIL_STROKE;
ctx.lineWidth = 30;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.miterLimit = 1;
if (trail.length > 0) {
ctx.beginPath();
ctx.moveTo(trail[0].x, trail[0].y);
for (let i = 1; i < trail.length; i++) {
ctx.lineTo(trail[i].x, trail[i].y);
}
}
ctx.stroke();
// Need to include this at the end, for now.
ctx.invalidate();
animationHandleRef.current = null;
}
});
}
}, [animationHandleRef, canvasSize, ctx, trailRef]);
// handlers for touch events
const handleMove = useCallback(
async event => {
const position: TrailPoint = {
x: event.nativeEvent.locationX,
y: event.nativeEvent.locationY,
};
const trail = trailRef.current;
if (trail.length > 0) {
const lastPosition = trail[trail.length - 1];
const dx = position.x - lastPosition.x;
const dy = position.y - lastPosition.y;
// add a point to trail if distance from last point > 5
if (dx * dx + dy * dy > 25) {
trail.push(position);
}
} else {
trail.push(position);
}
draw();
},
[trailRef, draw],
);
const handleStart = useCallback(() => {
setDrawingDone(false);
trailRef.current = [];
}, [trailRef, setDrawingDone]);
const handleEnd = useCallback(() => {
setDrawingDone(true);
if (ctx != null) classify(ctx, true);
}, [setDrawingDone, classify, ctx]);
useEffect(() => {
draw();
}, [draw]);
return (
<View
style={styles.container}
onLayout={event => {
const {layout} = event.nativeEvent;
setCanvasSize(Math.min(layout?.width || 0, layout?.height || 0));
}}>
<View style={styles.instruction}>
<Text style={styles.label}>Write a number</Text>
<Text style={styles.label}>
Let's see if the AI model will get it right
</Text>
</View>
<Canvas
style={{
height: canvasSize,
width: canvasSize,
}}
onContext2D={setCtx}
onTouchMove={handleMove}
onTouchStart={handleStart}
onTouchEnd={handleEnd}
/>
{drawingDone && (
<View style={[styles.resultView]} pointerEvents="none">
<Text style={[styles.label, styles.secondary]}>
{result &&
`${numLabels[result[0].num].asciiSymbol} it looks like ${
numLabels[result[0].num].english
}`}
</Text>
<Text style={[styles.label, styles.secondary]}>
{result &&
`${numLabels[result[1].num].asciiSymbol} or it might be ${
numLabels[result[1].num].english
}`}
</Text>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
height: '100%',
width: '100%',
backgroundColor: '#090909',
justifyContent: 'center',
alignItems: 'center',
},
resultView: {
position: 'absolute',
bottom: 0,
alignSelf: 'flex-start',
flexDirection: 'column',
padding: 15,
},
instruction: {
position: 'absolute',
top: 0,
alignSelf: 'flex-start',
flexDirection: 'column',
padding: 15,
},
label: {
fontSize: 16,
color: '#ffffff',
},
secondary: {
color: '#ffffff99',
},
}); | the_stack |
import ITreeInitializedInfo from "./ITreeInitializedInfo";
import AttributeManager from "../Base/AttributeManager";
import Utility from "../Base/Utility";
import Constants from "../Base/Constants";
import GomlParser from "./GomlParser";
import XMLReader from "../Base/XMLReader";
import GrimoireInterface from "../Interface/GrimoireInterface";
import EEObject from "../Base/EEObject";
import Component from "./Component";
import NodeDeclaration from "./NodeDeclaration";
import NodeUtility from "./NodeUtility";
import Attribute from "./Attribute";
import NSDictionary from "../Base/NSDictionary";
import NSIdentity from "../Base/NSIdentity";
import Ensure from "../Base/Ensure";
import MessageException from "../Base/MessageException";
import { Name, GomlInterface, Nullable, Ctor } from "../Base/Types";
class GomlNode extends EEObject {
public element: Element; // Dom Element
public nodeDeclaration: NodeDeclaration;
public children: GomlNode[] = [];
public componentsElement: Element; // <.components>
private _parent: Nullable<GomlNode> = null;
private _root: Nullable<GomlNode> = null;
private _components: Component[];
private _tree: GomlInterface = GrimoireInterface([this]);
private _companion: NSDictionary<any> = new NSDictionary<any>();
private _attributeManager: AttributeManager;
private _isActive = false;
private _messageCache: { [message: string]: Component[] } = {};
private _deleted = false;
private _mounted = false;
private _enabled = true;
private _defaultValueResolved = false;
private _initializedInfo: Nullable<ITreeInitializedInfo> = null;
/**
* Get actual goml node from element of xml tree.
* @param {Element} elem [description]
* @return {GomlNode} [description]
*/
public static fromElement(elem: Element): GomlNode {
const id = elem.getAttribute(Constants.x_gr_id);
if (id) {
return GrimoireInterface.nodeDictionary[id];
} else {
throw new Error("element has not 'x-gr-id'");
}
}
/**
* Tag name.
*/
public get name(): NSIdentity {
return this.nodeDeclaration.name;
}
/**
* GomlInterface that this node is bound to.
* throw exception if this node is not mounted.
* @return {GomlInterface} [description]
*/
public get tree(): GomlInterface {
if (!this.mounted) {
throw new Error("this node is not mounted");
}
return this._tree;
}
/**
* indicate this node is already deleted.
* if this node is deleted once, this node will not be mounted.
* @return {boolean} [description]
*/
public get deleted(): boolean {
return this._deleted;
}
/**
* indicate this node is enabled in tree.
* This value must be false when ancestor of this node is disabled.
* @return {boolean} [description]
*/
public get isActive(): boolean {
return this._isActive;
}
/**
* indicate this node is enabled.
* this node never recieve any message if this node is not enabled.
* @return {boolean} [description]
*/
public get enabled(): boolean {
return this._enabled;
}
public set enabled(value) {
this.setAttribute("enabled", value);
}
/**
* the shared object by all nodes in tree.
* @return {NSDictionary<any>} [description]
*/
public get companion(): NSDictionary<any> {
return this._companion;
}
/**
* parent node of this node.
* if this node is root, return null.
* @return {GomlNode} [description]
*/
public get parent(): Nullable<GomlNode> {
return this._parent;
}
/**
* return true if this node has some child nodes.
* @return {boolean} [description]
*/
public get hasChildren(): boolean {
return this.children.length > 0;
}
/**
* indicate mounted status.
* this property to be true when treeroot registered to GrimoireInterface.
* to be false when this node detachd from the tree.
* @return {boolean} Whether this node is mounted or not.
*/
public get mounted(): boolean {
return this._mounted;
}
/**
* create new instance.
* @param {NodeDeclaration} recipe 作成するノードのDeclaration
* @param {Element} element 対応するDomElement
* @return {[type]} [description]
*/
constructor(recipe: NodeDeclaration, element?: Nullable<Element>) {
super();
if (!recipe) {
throw new Error("recipe must not be null");
}
if (!recipe.resolvedDependency) {
recipe.resolveDependency();
}
this.nodeDeclaration = recipe;
this.element = element ? element : document.createElementNS(recipe.name.ns.qualifiedName, recipe.name.name);
this.componentsElement = document.createElement("COMPONENTS");
this._root = this;
this._components = [];
this._attributeManager = new AttributeManager(recipe.name.name);
this.element.setAttribute(Constants.x_gr_id, this.id);
const defaultComponentNames = recipe.defaultComponentsActual;
// instanciate default components
defaultComponentNames.forEach(id => {
this.addComponent(id, null, true);
});
// register to GrimoireInterface.
GrimoireInterface.nodeDictionary[this.id] = this;
}
/**
* search from children node by class property.
* return all nodes has same class as given.
* @param {string} className [description]
* @return {GomlNode[]} [description]
*/
public getChildrenByClass(className: string): GomlNode[] {
const nodes = this.element.getElementsByClassName(className);
const array = new Array(nodes.length);
for (let i = 0; i < nodes.length; i++) {
array[i] = GomlNode.fromElement(nodes.item(i));
}
return array;
}
/**
* Query children from current node.
* @param {string} query [description]
* @return GomlNode[] [description]
*/
public queryChildren(query: string): GomlNode[] {
const nodes = this.element.querySelectorAll(query);
const array = new Array(nodes.length);
for (let i = 0; i < nodes.length; i++) {
array[i] = GomlNode.fromElement(nodes.item(i));
}
return array;
}
/**
* search from children node by name property.
* return all nodes has same name as given.
* @param {string} nodeName [description]
* @return {GomlNode[]} [description]
*/
public getChildrenByNodeName(nodeName: string): GomlNode[] {
const nodes = this.element.getElementsByTagName(nodeName);
const array = new Array(nodes.length);
for (let i = 0; i < nodes.length; i++) {
array[i] = GomlNode.fromElement(nodes.item(i));
}
return array;
}
public remove(): void {
this.children.forEach((c) => {
c.remove();
});
this._sendMessageForced("$$dispose");
this.removeAllListeners();
delete GrimoireInterface.nodeDictionary[this.id];
if (this._parent) {
this._parent.detachChild(this);
} else {
this.setMounted(false);
if (this.element.parentNode) {
this.element.parentNode.removeChild(this.element);
}
}
this._deleted = true;
}
/**
* send message to this node.
* invoke component method has same name as message if this node isActive.
* @param {string} message [description]
* @param {any} args [description]
* @return {boolean} is this node active.
*/
public sendMessage(message: string, args?: any): boolean {
if (!this.isActive) {
return false;
}
message = Ensure.tobeMessage(message);
this._sendMessage(message, args);
return true;
}
/**
* sendMessage recursively for children.
* @param {number} range depth for recursive call.0 for only this node.1 for only children.
* @param {string} name [description]
* @param {any} args [description]
*/
public broadcastMessage(range: number, name: string, args?: any): void;
public broadcastMessage(name: string, args?: any): void;
public broadcastMessage(arg1: number | string, arg2?: any, arg3?: any): void {
if (!this.enabled || !this.mounted) {
return;
}
if (typeof arg1 === "number") {
const range = arg1;
const message = Ensure.tobeMessage(<string>arg2);
const args = arg3;
this._broadcastMessage(message, args, range);
} else {
const message = Ensure.tobeMessage(arg1);
const args = arg2;
this._broadcastMessage(message, args, -1);
}
}
public append(tag: string): GomlNode[] {
const elems = XMLReader.parseXML(tag);
let ret: GomlNode[] = [];
elems.forEach(elem => {
let child = GomlParser.parse(elem);
this.addChild(child);
ret.push(child);
});
return ret;
}
/**
* add new instance created by given name and attributes for this node as child.
* @param {string | NSIdentity} nodeName [description]
* @param {any }} attributes [description]
*/
public addChildByName(nodeName: Name, attributes: { [attrName: string]: any }): GomlNode {
const nodeDec = GrimoireInterface.nodeDeclarations.get(nodeName);
const node = new GomlNode(nodeDec);
if (attributes) {
for (let key in attributes) {
node.setAttribute(key, attributes[key]);
}
}
this.addChild(node);
return node;
}
/**
* Add child for this node.
* @param {GomlNode} child child node to add.
* @param {number} index index for insert.なければ末尾に追加
* @param {[type]} elementSync=true trueのときはElementのツリーを同期させる。(Elementからパースするときはfalseにする)
*/
public addChild(child: GomlNode, index?: number | null, elementSync = true): void {
if (child._deleted) {
throw new Error("deleted node never use.");
}
if (index != null && typeof index !== "number") {
throw new Error("insert index should be number or null or undefined.");
}
// add process.
const insertIndex = index == null ? this.children.length : index;
this.children.splice(insertIndex, 0, child);
child._parent = this;
child._tree = this._tree;
child._companion = this._companion;
// sync html
if (elementSync) {
let referenceElement = (this.element as any)[NodeUtility.getNodeListIndexByElementIndex(this.element, insertIndex)];
this.element.insertBefore(child.element, referenceElement);
}
// mounting
if (this.mounted) {
child.setMounted(true);
}
// send initializedInfo if needed
if (this._initializedInfo) {
child.sendInitializedMessage(this._initializedInfo);
}
}
public callRecursively<T>(func: (g: GomlNode) => T): T[] {
return this._callRecursively(func, (n) => n.children);
}
/**
* delete child node.
* @param {GomlNode} child Target node to be inserted.
*/
public removeChild(child: GomlNode): void {
const node = this.detachChild(child);
if (node) {
node.remove();
}
}
/**
* detach given node from this node if target is child of this node.
* return null if target is not child of this node.
* @param {GomlNode} child [description]
* @return {GomlNode} detached node.
*/
public detachChild(target: GomlNode): Nullable<GomlNode> {
// search child.
const index = this.children.indexOf(target);
if (index === -1) {
return null;
}
target.setMounted(false);
target._parent = null;
this.children.splice(index, 1);
// html sync
this.element.removeChild(target.element);
return target;
}
/**
* detach this node from parent.
*/
public detach(): void {
if (this.parent) {
this.parent.detachChild(this);
} else {
throw new Error("root Node cannot be detached.");
}
}
public getAttribute(attrName: Name): any {
return this._attributeManager.getAttribute(attrName);
}
public getAttributeRaw(attrName: Name): Attribute {
return this._attributeManager.getAttributeRaw(attrName);
}
public setAttribute(attrName: Name, value: any, ignoireFreeze = false): void {
let attrIds = this._attributeManager.guess(attrName);
if (attrIds.length === 0) { // such attribute is not exists. set to Attribute buffer.
this._attributeManager.setAttribute(typeof attrName === "string" ? attrName : attrName.fqn, value);
}
for (let i = 0; i < attrIds.length; i++) {
let id = attrIds[i];
if (!ignoireFreeze && this.isFreezeAttribute(id.fqn)) {
throw new Error(`attribute ${id.fqn} can not set. Attribute is frozen. `);
}
this._attributeManager.setAttribute(id.fqn, value);
}
}
/**
* Internal use!
* Add new attribute. In most of case, users no need to call this method.
* Use __addAttribute in Component should be used instead.
*/
public addAttribute(attr: Attribute): Attribute {
return this._attributeManager.addAttribute(attr);
}
/**
* Internal use!
* Update mounted status and emit events
* @param {boolean} mounted Mounted status.
*/
public setMounted(mounted: boolean): void {
if (this._mounted === mounted) {
return;
}
if (mounted) {
this._mount();
for (let i = 0; i < this.children.length; i++) {
this.children[i].setMounted(mounted);
}
} else {
for (let i = 0; i < this.children.length; i++) {
this.children[i].setMounted(mounted);
}
this._sendMessageForced("unmount");
this._isActive = false;
this._tree = GrimoireInterface([this]);
this._companion = new NSDictionary<any>();
this._mounted = mounted;
}
}
/**
* Get index of this node from parent.
* @return {number} number of index.
*/
public get index(): number {
if (!this._parent) {
return -1;
}
return this._parent.children.indexOf(this);
}
/**
* remove attribute from this node.
* @param {Attribute} attr [description]
*/
public removeAttribute(attr: Attribute): boolean {
return this._attributeManager.removeAttribute(attr);
}
/**
* attach component to this node.
* @param {Component} component [description]
*/
public addComponent(component: Name | (new () => Component), attributes?: { [key: string]: any } | null, isDefaultComponent = false): Component {
component = Ensure.tobeComponentIdentity(component);
const declaration = GrimoireInterface.componentDeclarations.get(component);
if (!declaration) {
throw new Error(`component '${Ensure.tobeNSIdentity(component).fqn}' is not defined.`);
}
const instance = declaration.generateInstance();
attributes = attributes || {};
for (let key in attributes) {
instance.setAttribute(key, attributes[key]);
}
this._addComponentDirectly(instance, isDefaultComponent);
return instance;
}
/**
* Internal use!
* Should not operate by users or plugin developpers
* @param {Component} component [description]
* @param {boolean} isDefaultComponent [description]
*/
public _addComponentDirectly(component: Component, isDefaultComponent: boolean): void {
if (component.node || component.disposed) {
throw new Error("component never change attached node");
}
// resetting cache
this._messageCache = {}; // TODO: optimize.
component.isDefaultComponent = !!isDefaultComponent;
component.node = this;
let referenceElement = (this.componentsElement as any)[NodeUtility.getNodeListIndexByElementIndex(this.componentsElement, this._components.length)];
this.componentsElement.insertBefore(component.element, referenceElement);
// bind this for message reciever.
let propNames: string[] = [];
let o = component;
while (o) {
propNames = propNames.concat(Object.getOwnPropertyNames(o));
o = Object.getPrototypeOf(o);
}
propNames.filter(name => name.startsWith("$") && typeof (<any>component)[name] === "function").forEach(method => {
(<any>component)["$" + method] = (<any>component)[method].bind(component);
});
this._components.push(component);
// attributes should be exposed on node
component.attributes.forEach(p => this.addAttribute(p));
if (this._defaultValueResolved) {
component.attributes.forEach(p => p.resolveDefaultValue(NodeUtility.getAttributes(this.element)));
}
if (this._mounted) {
component.resolveDefaultAttributes(null); // here must be optional component.should not use node element attributes.
this._sendMessageForcedTo(component, "awake");
this._sendMessageForcedTo(component, "mount");
}
// sending `initialized` message if needed.
if (this._initializedInfo) {
component.initialized(this._initializedInfo);
}
}
public removeComponents(component: Name | (new () => Component)): boolean {
let result = false;
const removeTargets = [];
component = Ensure.tobeComponentIdentity(component);
for (let i = 0; i < this._components.length; i++) {
const c = this._components[i];
if (c.name.fqn === component.fqn) {
removeTargets.push(c);
}
}
removeTargets.forEach(c => {
let b = this.removeComponent(c);
result = result || b;
});
return result;
}
public removeComponent(component: Component): boolean {
const index = this._components.indexOf(component);
if (index !== -1) {
this._sendMessageForcedTo(component, "unmount");
this._sendMessageForcedTo(component, "dispose");
this.componentsElement.removeChild(component.element);
this._components.splice(index, 1);
this._messageCache = {}; // TODO:optimize.
delete component.node;
component.disposed = true;
delete GrimoireInterface.componentDictionary[component.id];
return true;
}
return false;
}
public getComponents<T>(filter?: Name | Ctor<T>): T[] {
if (!filter) {
return this._components as any as T[];
} else {
const ctor = Ensure.tobeComponentConstructor(filter);
if (!ctor) {
return [];
}
return this._components.filter(c => c instanceof ctor) as any as T[];
}
}
/**
* search component by name from this node.
* @param {Name} name [description]
* @return {Component} component found first.
*/
public getComponent<T>(name: Name | Ctor<T>): T {
// 事情により<T extends Component>とはできない。
// これはref/Node/Componentによって参照されるのが外部ライブラリにおけるコンポーネントであるが、
// src/Node/Componentがこのプロジェクトにおけるコンポーネントのため、別のコンポーネントとみなされ、型の制約をみたさなくなるからである。
if (!name) {
throw new Error("name must not be null or undefined");
} else if (typeof name === "function") {
return this._components.find(c => c instanceof name) as any as T || null;
} else {
const ctor = Ensure.tobeComponentConstructor(name);
if (!ctor) {
throw new Error(`component ${name} is not exist`);
}
return this.getComponent<T>(ctor as any as Ctor<T>);
}
}
public getComponentsInChildren<T>(name: Name | Ctor<T>): T[] {
if (name == null) {
throw new Error("getComponentsInChildren recieve null or undefined");
}
return this.callRecursively(node => node.getComponent<T>(name)).filter(c => !!c);
}
/**
* search component in ancectors of this node.
* return component that found first.
* return null if component not found.
* @param {[type]} name==null [description]
* @return {[type]} [description]
*/
public getComponentInAncestor<T>(name: Name | Ctor<T>): Nullable<T> {
if (name == null) {
throw new Error("getComponentInAncestor recieve null or undefined");
}
if (this.parent) {
return this.parent._getComponentInAncestor(name);
}
return null;
}
public sendInitializedMessage(info: ITreeInitializedInfo) {
if (this._initializedInfo === info) {
return;
}
let components = this._components.concat(); // copy
for (let i = 0; i < components.length; i++) {
components[i].initialized(info);
}
this._initializedInfo = info;
let children = this.children.concat();
children.forEach(child => {
child.sendInitializedMessage(info);
});
}
/**
* resolve default attribute value for all component.
* すべてのコンポーネントの属性をエレメントかデフォルト値で初期化
*/
public resolveAttributesValue(): void {
this._defaultValueResolved = true;
const attrs = NodeUtility.getAttributes(this.element);
for (let key in attrs) {
if (key === Constants.x_gr_id) {
continue;
}
if (this.isFreezeAttribute(key)) {
throw new Error(`attribute ${key} can not change from GOML. Attribute is frozen. `);
}
}
this._components.forEach((component) => {
component.resolveDefaultAttributes(attrs);
});
}
public isFreezeAttribute(attributeName: string): boolean {
return !!this.nodeDeclaration.freezeAttributes.toArray().find(name => attributeName === name.fqn);
}
public notifyActivenessUpdate(activeness: boolean): void {
if (this.isActive !== activeness) {
this._isActive = activeness;
this.children.forEach(child => {
child.notifyActivenessUpdate(activeness && child.enabled);
});
}
}
public watch(attrName: Name, watcher: ((newValue: any, oldValue: any, attr: Attribute) => void), immediate = false) {
this._attributeManager.watch(attrName, watcher, immediate);
}
public toString(): string {
let name = this.name.fqn;
let id = this.getAttribute("id");
if (id !== null) {
name += ` id: ${id}`;
}
let classValue = this.getAttribute("class");
if (classValue !== null) {
name += ` class: ${classValue}`;
}
return name;
}
/**
* Get detailed node structure with highlighting node.
* @return {string} [description]
*/
public toStructualString(message = ""): string {
if (this.parent) {
return "\n" + this.parent._openTreeString() + this._currentSiblingsString(this._layer * 2, `<${this.toString()}/>`, true, message) + this.parent._closeTreeString();
} else {
return "\n" + this._currentSiblingsString(0, `<${this.toString()}/>`, true, message);
}
}
/**
* Fetch layer of this node. Root must be 1.
* @return {number} [description]
*/
private get _layer(): number {
if (!this.parent) {
return 1;
} else {
return this.parent._layer + 1;
}
}
private _openTreeString(): string {
let spaces = "";
for (let i = 0; i < this._layer * 2; i++) {
spaces += " ";
}
let ancestor = "";
let abbr = "";
if (this.parent) {
ancestor = this.parent._openTreeString();
if (this.index !== 0) {
abbr = `${spaces}...\n`;
}
}
return `${ancestor}${abbr}${spaces}<${this.toString()}>\n`;
}
private _closeTreeString(): string {
let spaces = "";
for (let i = 0; i < this._layer * 2; i++) {
spaces += " ";
}
let ancestor = "";
let abbr = "";
if (this.parent) {
ancestor = this.parent._closeTreeString();
if (this.index !== this.parent.children.length - 1) {
abbr = `${spaces}...\n`;
}
}
return `${spaces}</${this.name.fqn}>\n${abbr}${ancestor}`;
}
/**
* Generate display string for siblings of this node.
*/
private _currentSiblingsString(spaceCount: number, current: string, emphasis = false, message = ""): string {
let spaces = "";
for (let i = 0; i < spaceCount; i++) {
spaces += " ";
}
let emphasisStr = "";
if (emphasis) {
emphasisStr = `${spaces}`;
for (let i = 0; i < current.length; i++) {
emphasisStr += "^";
}
}
let targets: string[] = [];
if (!this.parent) {
targets.push(`${spaces}${current}`);
if (emphasis) {
targets.push(emphasisStr + message);
}
} else {
let putDots = false;
for (let i = 0; i < this.parent.children.length; i++) {
if (i === this.index) {
targets.push(`${spaces}${current}・・・(${i})`);
if (emphasis) {
targets.push(emphasisStr + message);
}
putDots = false;
} else if ((i > 0 && this.index - 1 > i) || (i > this.index + 1 && this.parent.children.length - 1 > i)) {
if (!putDots) {
targets.push(`${spaces}...`);
putDots = true;
}
} else {
targets.push(`${spaces}<${this.parent.children[i].toString()}/>・・・(${i})`);
}
}
}
return targets.join("\n") + "\n";
}
private _sendMessage(message: string, args?: any): void {
if (this._messageCache[message] === void 0) {
this._messageCache[message] = this._components.filter(c => typeof (c as any)[message] === "function");
}
const targetList = this._messageCache[message];
for (let i = 0; i < targetList.length; i++) {
if (targetList[i].disposed) {
continue;
}
this._sendMessageToComponent(targetList[i], message, args);
}
}
private _broadcastMessage(message: string, args: any, range: number): void {
// message is already ensured.-1 to unlimited range.
if (!this.isActive) {
return;
}
this._sendMessage(message, args);
if (range === 0) {
return;
}
const nextRange = range - 1;
for (let i = 0; i < this.children.length; i++) {
this.children[i]._broadcastMessage(message, args, nextRange);
}
}
private _getComponentInAncestor<T>(name: Name | (new () => T)): Nullable<T> {
const ret = this.getComponent(name);
if (ret) {
return ret;
}
if (this.parent) {
return this.parent._getComponentInAncestor(name);
}
return null;
}
/**
* コンポーネントにメッセージを送る。送信したらバッファからは削除される.
* @param {Component} targetComponent 対象コンポーネント
* @param {string} message メッセージ
* @param {boolean} forced trueでコンポーネントのenableを無視して送信
* @param {boolean} toBuffer trueで送信失敗したらバッファに追加
* @param {any} args [description]
* @return {boolean} 送信したか
*/
private _sendMessageToComponent(targetComponent: Component, message: string, args?: any): boolean {
if (!targetComponent.enabled) {
return false;
}
let method = (targetComponent as any)[message];
if (typeof method === "function") {
try {
method(args);
} catch (e) {
const wrappedError = new MessageException(this, targetComponent, message.substr(1), e);
this.emit("messageerror", wrappedError);
if (!wrappedError.handled) {
GrimoireInterface.emit("messageerror", wrappedError);
if (!wrappedError.handled) {
throw wrappedError;
}
}
}
return true;
}
return false;
}
private _sendMessageForced(message: string): void {
let componentsBuffer = this._components.concat();
for (let i = 0; i < componentsBuffer.length; i++) {
let target = componentsBuffer[i];
if (target.disposed) {
continue;
}
this._sendMessageForcedTo(target, message);
}
}
/**
* for system messages.
* @param {Component} target [description]
* @param {string} message [description]
*/
private _sendMessageForcedTo(target: Component, message: string): void {
message = Ensure.tobeMessage(message);
let method = (target as any)[message];
if (typeof method === "function") {
method();
}
}
/**
* sending mount and awake message if needed to all components.
*/
private _mount(): void {
this._mounted = true;
let componentsBuffer = this._components.concat();
for (let i = 0; i < componentsBuffer.length; i++) {
let target = componentsBuffer[i];
if (target.disposed) {
continue;
}
target.awake();
this._sendMessageForcedTo(target, "$$mount");
}
}
private _callRecursively<T>(func: (g: GomlNode) => T, nextGenerator: (n: GomlNode) => GomlNode[]): T[] {
const val = func(this);
const nexts = nextGenerator(this);
const nextVals = nexts.map(c => c.callRecursively(func));
const list = Utility.flat(nextVals);
list.unshift(val);
return list;
}
}
export default GomlNode; | the_stack |
import * as ctx from "../utils/getContext"
declare global {
interface NexusGen extends NexusGenTypes {}
}
export interface NexusGenInputs {
CharacterWhereInput: { // input type
comics?: string[] | null; // [ID!]
events?: string[] | null; // [ID!]
id?: number | null; // Int
modifiedSince?: string | null; // String
name?: string | null; // String
nameStartsWith?: string | null; // String
series?: string[] | null; // [ID!]
stories?: string[] | null; // [ID!]
}
ComicWhereInput: { // input type
characters?: string[] | null; // [ID!]
collaborators?: string[] | null; // [ID!]
creators?: string[] | null; // [ID!]
dateDescriptor?: NexusGenEnums['DateDescriptor'] | null; // DateDescriptor
dateRange?: number | null; // Int
diamondCode?: string | null; // String
digitalId?: number | null; // Int
ean?: string | null; // String
events?: string[] | null; // [ID!]
format?: NexusGenEnums['ComicFormat'] | null; // ComicFormat
formatType?: NexusGenEnums['ComicFormatType'] | null; // ComicFormatType
hasDigitalIssue?: boolean | null; // Boolean
isbn?: string | null; // String
issn?: string | null; // String
modifiedSince?: any | null; // DateTime
noVariants?: boolean | null; // Boolean
series?: string[] | null; // [ID!]
sharedAppearances?: string[] | null; // [ID!]
stories?: string[] | null; // [ID!]
upc?: string | null; // String
}
CreatorWhereInput: { // input type
comics?: string[] | null; // [ID!]
events?: string[] | null; // [ID!]
firstName?: string | null; // String
firstNameStartsWith?: string | null; // String
lastName?: string | null; // String
lastNameStartsWith?: string | null; // String
middleName?: string | null; // String
middleNameStartsWith?: string | null; // String
modifiedSince?: any | null; // DateTime
nameStartsWith?: string | null; // String
series?: string[] | null; // [ID!]
stories?: string[] | null; // [ID!]
suffix?: string | null; // String
}
EventsWhereInput: { // input type
characters?: string[] | null; // [ID!]
comics?: string[] | null; // [ID!]
creators?: string[] | null; // [ID!]
modifiedSince?: any | null; // DateTime
name?: string | null; // String
nameStartsWith?: string | null; // String
series?: string[] | null; // [ID!]
}
SeriesWhereInput: { // input type
characters?: string[] | null; // [ID!]
comics?: string[] | null; // [ID!]
contains?: NexusGenEnums['ComicFormat'] | null; // ComicFormat
creators?: string[] | null; // [ID!]
events?: string[] | null; // [ID!]
modifiedSince?: any | null; // DateTime
seriesType?: NexusGenEnums['SeriesType'] | null; // SeriesType
startYear?: number | null; // Int
stories?: string[] | null; // [ID!]
title?: string | null; // String
titleStartsWith?: string | null; // String
}
StoriesWhereInput: { // input type
characters?: string[] | null; // [ID!]
comics?: string[] | null; // [ID!]
creators?: string[] | null; // [ID!]
events?: string[] | null; // [ID!]
modifiedSince?: any | null; // DateTime
series?: string[] | null; // [ID!]
}
}
export interface NexusGenEnums {
CharacterOrderBy: "modified_asc" | "modified_desc" | "name_asc" | "name_desc"
ComicFormat: "comic" | "digest" | "digital_comic" | "graphic_novel" | "hardcover" | "infinite_comic" | "magazine" | "trade_paperback"
ComicFormatType: "collection" | "comic"
ComicOrderBy: "focDate_asc" | "focDate_desc" | "issueNumber_asc" | "issueNumber_desc" | "modified_asc" | "modified_desc" | "onSaleDate_asc" | "onSaleDate_desc" | "title_asc" | "title_desc"
CreatorOrderBy: "firstName_asc" | "firstName_desc" | "lastName_asc" | "lastName_desc" | "middleName_asc" | "middleName_desc" | "modified_asc" | "modified_desc" | "suffix_asc" | "suffix_desc"
DateDescriptor: "lastWeek" | "nextWeek" | "thisMonth" | "thisWeek"
EventsOrderBy: "modified_asc" | "modified_desc" | "name_asc" | "name_desc" | "startDate_asc" | "startDate_desc"
SeriesOrderBy: "modified_asc" | "modified_desc" | "startYear_asc" | "startYear_desc" | "title_asc" | "title_desc"
SeriesType: "collection" | "limited" | "one_shot" | "ongoing"
StoriesOrderBy: "id_asc" | "id_desc" | "modified_asc" | "modified_desc"
}
export interface NexusGenRootTypes {
Character: { // root type
comics?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description?: string | null; // String
events?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id?: string | null; // ID
modified?: string | null; // String
name?: string | null; // String
resourceURI?: string | null; // String
series?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
stories?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail?: string | null; // String
urls?: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Comic: { // root type
characters?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
collectedIssues?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
collections?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
dates?: NexusGenRootTypes['ComicDate'][] | null; // [ComicDate!]
description?: string | null; // String
diamondCode?: string | null; // String
digitalId?: number | null; // Int
ean?: string | null; // String
events?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
format?: string | null; // String
id?: string | null; // ID
images?: NexusGenRootTypes['ComicImage'][] | null; // [ComicImage!]
isbn?: string | null; // String
issn?: string | null; // String
issueNumber?: number | null; // Int
modified?: string | null; // String
prices?: NexusGenRootTypes['ComicPrice'][] | null; // [ComicPrice!]
resourceURI?: string | null; // String
series?: NexusGenRootTypes['Summary'] | null; // Summary
stories?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
textObjects?: NexusGenRootTypes['TextObject'][] | null; // [TextObject!]
thumbnail?: string | null; // String
title?: string | null; // String
upc?: string | null; // String
urls?: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
variantDescription?: string | null; // String
variants?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
}
ComicDate: { // root type
date?: string | null; // String
type?: string | null; // String
}
ComicImage: { // root type
extension?: string | null; // String
path?: string | null; // String
}
ComicPrice: { // root type
price?: number | null; // Int
type?: string | null; // String
}
Creator: { // root type
comics?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
events?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
firstName?: string | null; // String
fullName?: string | null; // String
id?: string | null; // ID
lastName?: string | null; // String
middleName?: string | null; // String
modified?: string | null; // String
resourceURI?: string | null; // String
series?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
stories?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
suffix?: string | null; // String
thumbnail?: string | null; // String
urls?: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Event: { // root type
characters?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description?: string | null; // String
end?: string | null; // String
id?: string | null; // ID
modified?: string | null; // String
next?: NexusGenRootTypes['Summary'] | null; // Summary
previous?: NexusGenRootTypes['Summary'] | null; // Summary
resourceURI?: string | null; // String
series?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
start?: string | null; // String
stories?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail?: string | null; // String
title?: string | null; // String
urls?: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
MarvelUrl: { // root type
type?: string | null; // String
url?: string | null; // String
}
Query: {};
Series: { // root type
characters?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description?: string | null; // String
endYear?: number | null; // Int
events?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id?: string | null; // ID
modified?: string | null; // String
next?: NexusGenRootTypes['Summary'] | null; // Summary
previous?: NexusGenRootTypes['Summary'] | null; // Summary
rating?: string | null; // String
resourceURI?: string | null; // String
startYear?: number | null; // Int
stories?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail?: string | null; // String
title?: string | null; // String
urls?: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Story: { // root type
characters?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description?: string | null; // String
events?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id?: string | null; // ID
modified?: string | null; // String
originalIssue?: NexusGenRootTypes['Summary'] | null; // Summary
resourceURI?: string | null; // String
series?: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail?: string | null; // String
title?: string | null; // String
type?: string | null; // String
}
Summary: { // root type
name?: string | null; // String
resourceURI?: string | null; // String
role?: string | null; // String
type?: string | null; // String
}
TextObject: { // root type
language?: string | null; // String
text?: string | null; // String
type?: string | null; // String
}
MarvelNode: NexusGenRootTypes['Character'] | NexusGenRootTypes['Comic'] | NexusGenRootTypes['Creator'] | NexusGenRootTypes['Event'] | NexusGenRootTypes['Series'] | NexusGenRootTypes['Story'];
String: string;
Int: number;
Float: number;
Boolean: boolean;
ID: string;
DateTime: any;
}
export interface NexusGenAllTypes extends NexusGenRootTypes {
CharacterWhereInput: NexusGenInputs['CharacterWhereInput'];
ComicWhereInput: NexusGenInputs['ComicWhereInput'];
CreatorWhereInput: NexusGenInputs['CreatorWhereInput'];
EventsWhereInput: NexusGenInputs['EventsWhereInput'];
SeriesWhereInput: NexusGenInputs['SeriesWhereInput'];
StoriesWhereInput: NexusGenInputs['StoriesWhereInput'];
CharacterOrderBy: NexusGenEnums['CharacterOrderBy'];
ComicFormat: NexusGenEnums['ComicFormat'];
ComicFormatType: NexusGenEnums['ComicFormatType'];
ComicOrderBy: NexusGenEnums['ComicOrderBy'];
CreatorOrderBy: NexusGenEnums['CreatorOrderBy'];
DateDescriptor: NexusGenEnums['DateDescriptor'];
EventsOrderBy: NexusGenEnums['EventsOrderBy'];
SeriesOrderBy: NexusGenEnums['SeriesOrderBy'];
SeriesType: NexusGenEnums['SeriesType'];
StoriesOrderBy: NexusGenEnums['StoriesOrderBy'];
}
export interface NexusGenFieldTypes {
Character: { // field return type
comics: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description: string | null; // String
events: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id: string | null; // ID
modified: string | null; // String
name: string | null; // String
resourceURI: string | null; // String
series: NexusGenRootTypes['Summary'][] | null; // [Summary!]
stories: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail: string | null; // String
urls: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Comic: { // field return type
characters: NexusGenRootTypes['Summary'][] | null; // [Summary!]
collectedIssues: NexusGenRootTypes['Summary'][] | null; // [Summary!]
collections: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators: NexusGenRootTypes['Summary'][] | null; // [Summary!]
dates: NexusGenRootTypes['ComicDate'][] | null; // [ComicDate!]
description: string | null; // String
diamondCode: string | null; // String
digitalId: number | null; // Int
ean: string | null; // String
events: NexusGenRootTypes['Summary'][] | null; // [Summary!]
format: string | null; // String
id: string | null; // ID
images: NexusGenRootTypes['ComicImage'][] | null; // [ComicImage!]
isbn: string | null; // String
issn: string | null; // String
issueNumber: number | null; // Int
modified: string | null; // String
prices: NexusGenRootTypes['ComicPrice'][] | null; // [ComicPrice!]
resourceURI: string | null; // String
series: NexusGenRootTypes['Summary'] | null; // Summary
stories: NexusGenRootTypes['Summary'][] | null; // [Summary!]
textObjects: NexusGenRootTypes['TextObject'][] | null; // [TextObject!]
thumbnail: string | null; // String
title: string | null; // String
upc: string | null; // String
urls: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
variantDescription: string | null; // String
variants: NexusGenRootTypes['Summary'][] | null; // [Summary!]
}
ComicDate: { // field return type
date: string | null; // String
type: string | null; // String
}
ComicImage: { // field return type
extension: string | null; // String
path: string | null; // String
}
ComicPrice: { // field return type
price: number | null; // Int
type: string | null; // String
}
Creator: { // field return type
comics: NexusGenRootTypes['Summary'][] | null; // [Summary!]
events: NexusGenRootTypes['Summary'][] | null; // [Summary!]
firstName: string | null; // String
fullName: string | null; // String
id: string | null; // ID
lastName: string | null; // String
middleName: string | null; // String
modified: string | null; // String
resourceURI: string | null; // String
series: NexusGenRootTypes['Summary'][] | null; // [Summary!]
stories: NexusGenRootTypes['Summary'][] | null; // [Summary!]
suffix: string | null; // String
thumbnail: string | null; // String
urls: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Event: { // field return type
characters: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description: string | null; // String
end: string | null; // String
id: string | null; // ID
modified: string | null; // String
next: NexusGenRootTypes['Summary'] | null; // Summary
previous: NexusGenRootTypes['Summary'] | null; // Summary
resourceURI: string | null; // String
series: NexusGenRootTypes['Summary'][] | null; // [Summary!]
start: string | null; // String
stories: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail: string | null; // String
title: string | null; // String
urls: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
MarvelUrl: { // field return type
type: string | null; // String
url: string | null; // String
}
Query: { // field return type
characters: NexusGenRootTypes['Character'][] | null; // [Character!]
comics: NexusGenRootTypes['Comic'][] | null; // [Comic!]
creators: NexusGenRootTypes['Creator'][] | null; // [Creator!]
engineInfo: string | null; // String
events: NexusGenRootTypes['Event'][] | null; // [Event!]
getCharacter: NexusGenRootTypes['Character'] | null; // Character
getComic: NexusGenRootTypes['Comic'] | null; // Comic
getCreator: NexusGenRootTypes['Creator'] | null; // Creator
getEvent: NexusGenRootTypes['Event'] | null; // Event
getSeries: NexusGenRootTypes['Series'] | null; // Series
getStory: NexusGenRootTypes['Story'] | null; // Story
series: NexusGenRootTypes['Series'][] | null; // [Series!]
stories: NexusGenRootTypes['Story'][] | null; // [Story!]
}
Series: { // field return type
characters: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description: string | null; // String
endYear: number | null; // Int
events: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id: string | null; // ID
modified: string | null; // String
next: NexusGenRootTypes['Summary'] | null; // Summary
previous: NexusGenRootTypes['Summary'] | null; // Summary
rating: string | null; // String
resourceURI: string | null; // String
startYear: number | null; // Int
stories: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail: string | null; // String
title: string | null; // String
urls: NexusGenRootTypes['MarvelUrl'][] | null; // [MarvelUrl!]
}
Story: { // field return type
characters: NexusGenRootTypes['Summary'][] | null; // [Summary!]
comics: NexusGenRootTypes['Summary'][] | null; // [Summary!]
creators: NexusGenRootTypes['Summary'][] | null; // [Summary!]
description: string | null; // String
events: NexusGenRootTypes['Summary'][] | null; // [Summary!]
id: string | null; // ID
modified: string | null; // String
originalIssue: NexusGenRootTypes['Summary'] | null; // Summary
resourceURI: string | null; // String
series: NexusGenRootTypes['Summary'][] | null; // [Summary!]
thumbnail: string | null; // String
title: string | null; // String
type: string | null; // String
}
Summary: { // field return type
name: string | null; // String
resourceURI: string | null; // String
role: string | null; // String
type: string | null; // String
}
TextObject: { // field return type
language: string | null; // String
text: string | null; // String
type: string | null; // String
}
MarvelNode: { // field return type
id: string | null; // ID
modified: string | null; // String
resourceURI: string | null; // String
thumbnail: string | null; // String
}
}
export interface NexusGenArgTypes {
Query: {
characters: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['CharacterOrderBy'] | null; // CharacterOrderBy
where?: NexusGenInputs['CharacterWhereInput'] | null; // CharacterWhereInput
}
comics: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['ComicOrderBy'] | null; // ComicOrderBy
where?: NexusGenInputs['ComicWhereInput'] | null; // ComicWhereInput
}
creators: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['CreatorOrderBy'] | null; // CreatorOrderBy
where?: NexusGenInputs['CreatorWhereInput'] | null; // CreatorWhereInput
}
events: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['EventsOrderBy'] | null; // EventsOrderBy
where?: NexusGenInputs['EventsWhereInput'] | null; // EventsWhereInput
}
getCharacter: { // args
where?: NexusGenInputs['CharacterWhereInput'] | null; // CharacterWhereInput
}
getComic: { // args
where?: NexusGenInputs['ComicWhereInput'] | null; // ComicWhereInput
}
getCreator: { // args
where?: NexusGenInputs['CreatorWhereInput'] | null; // CreatorWhereInput
}
getEvent: { // args
where?: NexusGenInputs['EventsWhereInput'] | null; // EventsWhereInput
}
getSeries: { // args
where?: NexusGenInputs['SeriesWhereInput'] | null; // SeriesWhereInput
}
getStory: { // args
where?: NexusGenInputs['StoriesWhereInput'] | null; // StoriesWhereInput
}
series: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['SeriesOrderBy'] | null; // SeriesOrderBy
where?: NexusGenInputs['SeriesWhereInput'] | null; // SeriesWhereInput
}
stories: { // args
limit?: number | null; // Int
offset?: number | null; // Int
orderBy?: NexusGenEnums['StoriesOrderBy'] | null; // StoriesOrderBy
where?: NexusGenInputs['StoriesWhereInput'] | null; // StoriesWhereInput
}
}
}
export interface NexusGenAbstractResolveReturnTypes {
MarvelNode: "Character" | "Comic" | "Creator" | "Event" | "Series" | "Story"
}
export interface NexusGenInheritedFields {}
export type NexusGenObjectNames = "Character" | "Comic" | "ComicDate" | "ComicImage" | "ComicPrice" | "Creator" | "Event" | "MarvelUrl" | "Query" | "Series" | "Story" | "Summary" | "TextObject";
export type NexusGenInputNames = "CharacterWhereInput" | "ComicWhereInput" | "CreatorWhereInput" | "EventsWhereInput" | "SeriesWhereInput" | "StoriesWhereInput";
export type NexusGenEnumNames = "CharacterOrderBy" | "ComicFormat" | "ComicFormatType" | "ComicOrderBy" | "CreatorOrderBy" | "DateDescriptor" | "EventsOrderBy" | "SeriesOrderBy" | "SeriesType" | "StoriesOrderBy";
export type NexusGenInterfaceNames = "MarvelNode";
export type NexusGenScalarNames = "Boolean" | "DateTime" | "Float" | "ID" | "Int" | "String";
export type NexusGenUnionNames = never;
export interface NexusGenTypes {
context: ctx.Context;
inputTypes: NexusGenInputs;
rootTypes: NexusGenRootTypes;
argTypes: NexusGenArgTypes;
fieldTypes: NexusGenFieldTypes;
allTypes: NexusGenAllTypes;
inheritedFields: NexusGenInheritedFields;
objectNames: NexusGenObjectNames;
inputNames: NexusGenInputNames;
enumNames: NexusGenEnumNames;
interfaceNames: NexusGenInterfaceNames;
scalarNames: NexusGenScalarNames;
unionNames: NexusGenUnionNames;
allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames'];
allOutputTypes: NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames'];
allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes']
abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames'];
abstractResolveReturn: NexusGenAbstractResolveReturnTypes;
} | the_stack |
import { TeamSpeakServer } from "../node/Server"
import { ApiKeyScope, ClientType, Codec } from "./enum"
import { TeamSpeakQuery } from "../transport/TeamSpeakQuery"
export interface ClientSetServerQueryLogin extends TeamSpeakQuery.ResponseEntry {
clientLoginPassword: string
}
export interface ClientFind extends TeamSpeakQuery.ResponseEntry {
clid: string
clientNickname: string
}
export interface ApiKeyAdd extends TeamSpeakQuery.ResponseEntry {
apikey: string
id: string
sid: string
cldbid: string
scope: ApiKeyScope
timeLeft: number
}
export type ApiKeyList = ApiKeyEntry[]
export interface ApiKeyEntry extends TeamSpeakQuery.ResponseEntry {
count: number
id: string
sid: number
cldbid: number
scope: ApiKeyScope
timeLeft: number
createdAt: number
expiresAt: number
}
export interface QueryErrorMessage extends TeamSpeakQuery.ResponseEntry {
id: string
msg: string
extraMsg?: string
failedPermid?: number
}
export type ClientList = ClientEntry[]
export interface ClientEntry extends TeamSpeakQuery.ResponseEntry {
clid: string
cid: string
clientDatabaseId: string
clientNickname: string
clientType: number
clientAway: number
clientAwayMessage: string
clientFlagTalking: boolean
clientInputMuted: boolean
clientOutputMuted: boolean
clientInputHardware: boolean
clientOutputHardware: boolean
clientTalkPower: number
clientIsTalker: boolean
clientIsPrioritySpeaker: boolean
clientIsRecording: boolean
clientIsChannelCommander: number
clientUniqueIdentifier: string
clientServergroups: string[]
clientChannelGroupId: string
clientChannelGroupInheritedChannelId: number
clientVersion: string
clientPlatform: string
clientIdleTime: number
clientCreated: number
clientLastconnected: number
clientCountry: string|undefined
clientEstimatedLocation: string|undefined
connectionClientIp: string
clientBadges: string
}
export type ChannelList = ChannelEntry[]
export interface ChannelEntry extends TeamSpeakQuery.ResponseEntry {
cid: string
pid: string
channelOrder: number
channelName: string
channelTopic: string
channelFlagDefault: boolean
channelFlagPassword: boolean
channelFlagPermanent: boolean
channelFlagSemiPermanent: boolean
channelCodec: Codec
channelCodecQuality: number
channelNeededTalkPower: number
channelIconId: string
secondsEmpty: number
totalClientsFamily: number
channelMaxclients: number
channelMaxfamilyclients: number
totalClients: number
channelNeededSubscribePower: number
/** only in server version >= 3.11.x */
channelBannerGfxUrl: string
/** only in server version >= 3.11.x */
channelBannerMode: number
}
export type ServerGroupList = ServerGroupEntry[]
export interface ServerGroupEntry extends TeamSpeakQuery.ResponseEntry {
sgid: string
name: string
type: number
iconid: string
savedb: number
sortid: number
namemode: number
nModifyp: number
nMemberAddp: number
nMemberRemovep: number
}
export interface ServerGroupsByClientId extends TeamSpeakQuery.ResponseEntry {
name: string
sgid: string
cldbid: string
}
export type ChannelClientPermIdList = ChannelClientPermIdEntry[]
export interface ChannelClientPermIdEntry extends TeamSpeakQuery.ResponseEntry {
cid: string
cldbid: string
permid: number
permvalue: number
permnegated: boolean
permskip: boolean
}
export type ChannelClientPermSidList = ChannelClientPermSidEntry[]
export interface ChannelClientPermSidEntry extends TeamSpeakQuery.ResponseEntry {
cid: string
cldbid: string
permsid: string
permvalue: number
permnegated: boolean
permskip: boolean
}
export type ChannelGroupList = ChannelGroupEntry[]
export interface ChannelGroupEntry extends TeamSpeakQuery.ResponseEntry {
cgid: string
name: string
type: number
iconid: string
savedb: number
sortid: number
namemode: number
nModifyp: number
nMemberAddp: number
nMemberRemovep: number
}
export type ServerList = ServerEntry[]
export interface ServerEntry extends TeamSpeakQuery.ResponseEntry {
virtualserverId: string
virtualserverPort: number
virtualserverStatus: string
virtualserverClientsonline: number
virtualserverQueryclientsonline: number
virtualserverMaxclients: number
virtualserverUptime: number
virtualserverName: string
virtualserverAutostart: number
virtualserverMachineId: string
virtualserverUniqueIdentifier: string
}
export interface ServerCreate {
token: string,
server: TeamSpeakServer
}
export interface QueryLoginAdd extends TeamSpeakQuery.ResponseEntry {
cldbid: string
sid: string
clientLoginName: string
clientLoginPassword: string
}
export type QueryLoginList = QueryLoginEntry[]
export interface QueryLoginEntry extends TeamSpeakQuery.ResponseEntry {
cldbid: string
sid: string
clientLoginName: string
}
export interface Version extends TeamSpeakQuery.ResponseEntry {
version: string
build: number
platform: string
}
export interface HostInfo extends TeamSpeakQuery.ResponseEntry {
instanceUptime: number
hostTimestampUtc: number
virtualserversRunningTotal: number
virtualserversTotalMaxclients: number
virtualserversTotalClientsOnline: number
virtualserversTotalChannelsOnline: number
connectionFiletransferBandwidthSent: number
connectionFiletransferBandwidthReceived: number
connectionFiletransferBytesSentTotal: number
connectionFiletransferBytesReceivedTotal: number
connectionPacketsSentTotal: number
connectionBytesSentTotal: number
connectionPacketsReceivedTotal: number
connectionBytesReceivedTotal: number
connectionBandwidthSentLastSecondTotal: number
connectionBandwidthSentLastMinuteTotal: number
connectionBandwidthReceivedLastSecondTotal: number
connectionBandwidthReceivedLastMinuteTotal: number
}
export interface InstanceInfo extends TeamSpeakQuery.ResponseEntry {
serverinstanceDatabaseVersion: number
serverinstanceFiletransferPort: number
serverinstanceMaxDownloadTotalBandwidth: number
serverinstanceMaxUploadTotalBandwidth: number
serverinstanceGuestServerqueryGroup: number
serverinstanceServerqueryFloodCommands: number
serverinstanceServerqueryFloodBanTime: number
serverinstanceTemplateServeradminGroup: number
serverinstanceTemplateServerdefaultGroup: string
serverinstanceTemplateChanneladminGroup: string
serverinstanceTemplateChanneldefaultGroup: string
serverinstancePermissionsVersion: number
serverinstancePendingConnectionsPerIp: number
serverinstanceServerqueryMaxConnectionsPerIp: number
}
export type BindingList = BindingEntry[]
export interface BindingEntry extends TeamSpeakQuery.ResponseEntry {
ip: string
}
export interface Whoami extends TeamSpeakQuery.ResponseEntry {
virtualserverStatus: string
virtualserverUniqueIdentifier: string
virtualserverPort: number
virtualserverId: string
clientId: string
clientChannelId: string
clientNickname: string
clientDatabaseId: string
clientLoginName: string
clientUniqueIdentifier: string
clientOriginServerId: string
}
export interface ServerInfo extends TeamSpeakQuery.ResponseEntry {
virtualserverUniqueIdentifier: string
virtualserverName: string
virtualserverWelcomemessage: string
virtualserverMaxclients: number
virtualserverPassword: string
virtualserverCreated: number
virtualserverCodecEncryptionMode: number
virtualserverHostmessage: string
virtualserverHostmessageMode: number
virtualserverFilebase: string
virtualserverDefaultServerGroup: string
virtualserverDefaultChannelGroup: string
virtualserverFlagPassword: boolean
virtualserverDefaultChannelAdminGroup: string
virtualserverMaxDownloadTotalBandwidth: number
virtualserverMaxUploadTotalBandwidth: number
virtualserverHostbannerUrl: string
virtualserverHostbannerGfxUrl: string
virtualserverHostbannerGfxInterval: number
virtualserverComplainAutobanCount: number
virtualserverComplainAutobanTime: number
virtualserverComplainRemoveTime: number
virtualserverMinClientsInChannelBeforeForcedSilence: number
virtualserverPrioritySpeakerDimmModificator: number
virtualserverAntifloodPointsTickReduce: number
virtualserverAntifloodPointsNeededCommandBlock: number
virtualserverAntifloodPointsNeededIpBlock: number
virtualserverHostbuttonTooltip: string
virtualserverHostbuttonUrl: string
virtualserverHostbuttonGfxUrl: string
virtualserverDownloadQuota: number
virtualserverUploadQuota: number
virtualserverNeededIdentitySecurityLevel: number
virtualserverLogClient: number
virtualserverLogQuery: number
virtualserverLogChannel: number
virtualserverLogPermissions: number
virtualserverLogServer: number
virtualserverLogFiletransfer: number
virtualserverMinClientVersion: number
virtualserverNamePhonetic: string
virtualserverIconId: string
virtualserverReservedSlots: number
virtualserverWeblistEnabled: number
virtualserverHostbannerMode: number
virtualserverChannelTempDeleteDelayDefault: number
virtualserverMinAndroidVersion: number
virtualserverMinIosVersion: number
virtualserverNickname: string
virtualserverAntifloodPointsNeededPluginBlock: number
virtualserverStatus: string
virtualserverTotalPing: number
virtualserverTotalPacketlossTotal: number
virtualserverChannelsonline: number
virtualserverTotalBytesUploaded: number
virtualserverTotalBytesDownloaded: number
virtualserverClientsonline: number
virtualserverQueryclientsonline: number
connectionFiletransferBandwidthSent: number
connectionFiletransferBandwidthReceived: number
connectionFiletransferBytesSentTotal: number
connectionFiletransferBytesReceivedTotal: number
connectionPacketsSentSpeech: number
connectionBytesSentSpeech: number
connectionPacketsReceivedSpeech: number
connectionBytesReceivedSpeech: number
connectionPacketsSentKeepalive: number
connectionBytesSentKeepalive: number
connectionPacketsReceivedKeepalive: number
connectionBytesReceivedKeepalive: number
connectionPacketsSentControl: number
connectionBytesSentControl: number
connectionPacketsReceivedControl: number
connectionBytesReceivedControl: number
connectionPacketsSentTotal: number
connectionBytesSentTotal: number
connectionPacketsReceivedTotal: number
connectionBytesReceivedTotal: number
connectionBandwidthSentLastSecondTotal: number
connectionBandwidthSentLastMinuteTotal: number
connectionBandwidthReceivedLastSecondTotal: number
connectionBandwidthReceivedLastMinuteTotal: number
}
export interface ServerIdGetByPort extends TeamSpeakQuery.ResponseEntry {
serverId: string
}
export interface ServerRequestConnectionInfo extends TeamSpeakQuery.ResponseEntry {
connectionFiletransferBandwidthSent: number
connectionFiletransferBandwidthReceived: number
connectionFiletransferBytesSentTotal: number
connectionFiletransferBytesReceivedTotal: number
connectionPacketsSentTotal: number
connectionBytesSentTotal: number
connectionPacketsReceivedTotal: number
connectionBytesReceivedTotal: number
connectionBandwidthSentLastSecondTotal: number
connectionBandwidthSentLastMinuteTotal: number
connectionBandwidthReceivedLastSecondTotal: number
connectionBandwidthReceivedLastMinuteTotal: number
connectionConnectedTime: number
connectionPacketlossTotal: number
connectionPing: number
}
export type ServerGroupClientList = ServerGroupClientEntry[]
export interface ServerGroupClientEntry extends TeamSpeakQuery.ResponseEntry {
cldbid: string
clientNickname: string
clientUniqueIdentifier: string
}
export interface ServerGroupCopy extends TeamSpeakQuery.ResponseEntry {
/** only available when a new group gets created */
sgid?: string
}
export interface ChannelGroupCopy extends TeamSpeakQuery.ResponseEntry {
/** only available when a new group gets created */
cgid?: string
}
export type ServerTempPasswordList = ServerTempPasswordEntry[]
export interface ServerTempPasswordEntry extends TeamSpeakQuery.ResponseEntry {
nickname: string
uid: string
desc: string
pwClear: string
start: number
end: number
tcid: string
}
export type ChannelGroupClientList = ChannelGroupClientEntry[]
export interface ChannelGroupClientEntry extends TeamSpeakQuery.ResponseEntry {
cid?: string
cldbid?: string
cgid?: string
}
export type PermList = PermEntry[]
export interface PermEntry extends TeamSpeakQuery.ResponseEntry {
permid?: number
permsid?: string
permvalue: number
permnegated: boolean
permskip: boolean
}
export interface ChannelFind extends TeamSpeakQuery.ResponseEntry {
cid: string
channelName: string
}
export interface ChannelInfo extends TeamSpeakQuery.ResponseEntry {
pid: string
channelName: string
channelTopic: string
channelDescription: string
channelPassword: string
channelCodec: number
channelCodecQuality: number
channelMaxclients: number
channelMaxfamilyclients: number
channelOrder: number
channelFlagPermanent: boolean
channelFlagSemiPermanent: boolean
channelFlagDefault: boolean
channelFlagPassword: boolean
channelCodecLatencyFactor: number
channelCodecIsUnencrypted: number
channelSecuritySalt: string
channelDeleteDelay: number
channelFlagMaxclientsUnlimited: boolean
channelFlagMaxfamilyclientsUnlimited: boolean
channelFlagMaxfamilyclientsInherited: boolean
channelFilepath: string
channelNeededTalkPower: number
channelForcedSilence: number
channelNamePhonetic: string
channelIconId: string
channelBannerGfxUrl: string
channelBannerMode: number
secondsEmpty: number
}
export type ClientGetIds = ClientGetIdEntry[]
export interface ClientGetIdEntry extends TeamSpeakQuery.ResponseEntry {
cluid: string
clid: string
name: string
}
export interface ClientGetDbidFromUid extends TeamSpeakQuery.ResponseEntry {
cluid: string
cldbid: string
}
export interface ClientGetNameFromUid extends TeamSpeakQuery.ResponseEntry {
cluid: string
cldbid: string
name: string
}
export interface ClientGetUidFromClid extends TeamSpeakQuery.ResponseEntry {
clid: string
cluid: string
nickname: string
}
export interface ClientGetNameFromDbid extends TeamSpeakQuery.ResponseEntry {
cluid: string
cldbid: string
name: string
}
export interface ClientInfo extends TeamSpeakQuery.ResponseEntry {
cid: string
clientIdleTime: number
clientUniqueIdentifier: string
clientNickname: string
clientVersion: string
clientPlatform: string
clientInputMuted: number
clientOutputMuted: number
clientOutputonlyMuted: number
clientInputHardware: number
clientOutputHardware: number
clientDefaultChannel: string
clientMetaData: string
clientIsRecording: boolean
clientVersionSign: string
clientSecurityHash: string
clientLoginName: string
clientDatabaseId: number
clientChannelGroupId: string
clientServergroups: string[]
clientCreated: number
clientLastconnected: number
clientTotalconnections: number
clientAway: boolean
clientAwayMessage: string|undefined
clientType: ClientType
clientFlagAvatar: string
clientTalkPower: number
clientTalkRequest: boolean
clientTalkRequestMsg: string
clientDescription: string
clientIsTalker: boolean
clientMonthBytesUploaded: number
clientMonthBytesDownloaded: number
clientTotalBytesUploaded: number
clientTotalBytesDownloaded: number
clientIsPrioritySpeaker: boolean
clientNicknamePhonetic: string
clientNeededServerqueryViewPower: number
clientDefaultToken: string
clientIconId: string
clientIsChannelCommander: boolean
clientCountry: string
clientChannelGroupInheritedChannelId: string
clientBadges: string
clientMyteamspeakId: string
clientIntegrations: string
clientMyteamspeakAvatar: string
clientSignedBadges: string
clientBase64HashClientUID: string
connectionFiletransferBandwidthSent: number
connectionFiletransferBandwidthReceived: number
connectionPacketsSentTotal: number
connectionBytesSentTotal: number
connectionPacketsReceivedTotal: number
connectionBytesReceivedTotal: number
connectionBandwidthSentLastSecondTotal: number
connectionBandwidthSentLastMinuteTotal: number
connectionBandwidthReceivedLastSecondTotal: number
connectionBandwidthReceivedLastMinuteTotal: number
connectionConnectedTime: number
connectionClientIp: string
}
export type ClientDBList = ClientDBEntry[]
export interface ClientDBEntry extends TeamSpeakQuery.ResponseEntry {
count: number
cldbid: string
clientUniqueIdentifier: string
clientNickname: string
clientCreated: number
clientLastconnected: number
clientTotalconnections: number
clientDescription: string
clientLastip: string
clientLoginName: string
}
export interface ClientDBInfo extends TeamSpeakQuery.ResponseEntry {
clientUniqueIdentifier: string
clientNickname: string
clientDatabaseId: string
clientCreated: number
clientLastconnected: number
clientTotalconnections: number
clientFlagAvatar: string
clientDescription: string
clientMonthBytesUploaded: number
clientMonthBytesDownloaded: number
clientTotalBytesUploaded: number
clientTotalBytesDownloaded: number
clientBase64HashClientUID: string
clientLastip: string
}
export interface CustomSearch extends TeamSpeakQuery.ResponseEntry {
cldbid: string
ident: string
value: string
}
export interface CustomInfo extends TeamSpeakQuery.ResponseEntry {
cldbid: string
ident: string
value: string
}
export interface TokenCustomSet extends TeamSpeakQuery.ResponseEntry {
ident: string
value: string
}
export type PermOverview = PermOverviewEntry[]
export interface PermOverviewEntry extends TeamSpeakQuery.ResponseEntry {
t: number
id: number
id2: number
/** perm */
p: number
/** value */
v: number
/** negate */
n: number
/** skip */
s: number
}
export type PermissionList = PermissionEntry[]
export interface PermissionEntry extends TeamSpeakQuery.ResponseEntry {
permid: number
permname: string
permdesc: string
}
export interface PermIdGetByName extends TeamSpeakQuery.ResponseEntry {
permsid: string
permid: number
}
export interface PermGet extends TeamSpeakQuery.ResponseEntry {
permsid: string
permid: number
permvalue: number
}
export interface PermFind extends TeamSpeakQuery.ResponseEntry {
t: number
id1: number
id2: number
p: number
}
export interface Token extends TeamSpeakQuery.ResponseEntry {
token: string
}
export type PrivilegeKeyList = PrivilegeKeyEntry[]
export interface PrivilegeKeyEntry extends TeamSpeakQuery.ResponseEntry {
token: string
tokenType: number
tokenId1: number
tokenId2: number
tokenCreated: number
tokenDescription: string
/** only in server version >= 3.11.x */
tokenCustomset: TokenCustomSet[]
}
export type MessageList = MessageEntry[]
export interface MessageEntry extends TeamSpeakQuery.ResponseEntry {
msgid: string
cluid: string
subject: string
timestamp: number
flagRead: boolean
}
export interface MessageGet extends TeamSpeakQuery.ResponseEntry {
msgid: string
cluid: string
subject: string
message: string
timestamp: number
}
export type ComplainList = ComplainEntry[]
export interface ComplainEntry extends TeamSpeakQuery.ResponseEntry {
tcldbid: string
tname: string
fcldbid: string
fname: string
message: string
timestamp: number
}
export interface BanAdd extends TeamSpeakQuery.ResponseEntry {
banid: string
}
export type BanList = BanEntry[]
export interface BanEntry extends TeamSpeakQuery.ResponseEntry {
banid: string
ip: string
name: string
uid: string
mytsid: string
lastnickname: string
created: number
duration: number
invokername: string
invokercldbid: string
invokeruid: string
reason: string
enforcements: number
}
export interface LogView extends TeamSpeakQuery.ResponseEntry {
lastPos: number
fileSize: number
l: string
}
export interface ClientDBFind extends TeamSpeakQuery.ResponseEntry {
cldbid: string
}
export type FTList = FileTransferEntry[]
export interface FileTransferEntry extends TeamSpeakQuery.ResponseEntry {
clid: string
path: string
name: string
size: number
sizedone: number
clientftfid: number
serverftfid: number
sender: number
status: number
currentSpeed: number
averageSpeed: number
runtime: number
}
export type FTGetFileList = FTGetFileEntry[]
export interface FTGetFileEntry extends TeamSpeakQuery.ResponseEntry {
cid: string
path: string
name: string
size: number
datetime: number
/** 1=file 0=folder */
type: number
}
export interface FTGetFileInfo extends TeamSpeakQuery.ResponseEntry {
cid: string
name: string
size: number
datetime: number
}
export interface FTInitUpload extends TeamSpeakQuery.ResponseEntry {
clientftfid: number
/** exists when an error occured */
status?: number
/** exists when an error occured */
msg?: string
/** exists when an error occured */
size?: number
/** exists when file is uploadable */
serverftfid?: number
/** exists when file is uploadable */
ftkey?: string
/** exists when file is uploadable */
port?: number
/** exists when file is uploadable */
seekpos?: number
/** exists when file is uploadable */
proto?: number
}
export interface FTInitDownload extends TeamSpeakQuery.ResponseEntry {
clientftfid: number
size: number
/** exists when an error occured */
status?: number
/** exists when an error occured */
msg?: string
/** exists when file is downloadable */
serverftfid?: number
/** exists when file is downloadable */
ftkey?: string
/** exists when file is downloadable */
port?: number
/** exists when file is downloadable */
proto?: number
}
export interface SnapshotCreate extends TeamSpeakQuery.ResponseEntry {
version: number,
/** only exists when a password has been set otherwise it will be undefined */
salt?: string,
snapshot: string
} | the_stack |
import * as Configuration from "./Configuration";
import * as IC from "./ICProcess";
import * as Messages from "./Messages";
import * as Meta from "./Meta";
import * as Streams from "./Streams";
import * as StringEncoding from "./StringEncoding";
import * as Root from "./AmbrosiaRoot";
import * as Utils from "./Utils/Utils-Index";
/** [Internal] An embedded "Ambrosia-enabled app" used for developing/testing ambrosia-node. */
export function startTest(): void
{
// TODO: This is just a placeholder while we work on developing AppState.upgrade().
class AppStateVNext extends Root.AmbrosiaAppState
{
counter: number;
last: Date; // New to AppStateVNext
constructor(restoredAppState?: AppStateVNext)
{
super(restoredAppState);
if (restoredAppState)
{
// Re-initialize application state from restoredAppState
// WARNING: You MUST reinstantiate all members that are (or contain) class references because restoredAppState is data-only
this.counter = restoredAppState.counter;
this.last = restoredAppState.last;
}
else
{
// Initialize application state
this.counter = 0;
this.last = new Date(0);
}
}
static fromPriorAppState(oldAppState: AppState): AppStateVNext
{
const appState: AppStateVNext = new AppStateVNext();
// Upgrading, so transform (as needed) the supplied old state, and - if needed - [re]initialize the new state
appState.counter = oldAppState.counter;
appState.last = new Date(Date.now());
return (appState);
}
}
class AppState extends Root.AmbrosiaAppState
{
counter: number = 0;
padding: Uint8Array;
constructor(restoredAppState?: AppState)
{
super(restoredAppState);
if (restoredAppState)
{
this.counter = restoredAppState.counter;
this.padding = restoredAppState.padding;
}
else
{
this.padding = new Uint8Array(1 * 1024 * 1024);
this.padding[0] = 123;
this.padding[this.padding.length - 1] = 170;
}
}
// We must override convert() to support upgrade: convert() is called by AmbrosiaAppState.upgrade(), which we should call when
// we receive an AppEventType.UpgradeState, eg. let _newAppState: AppStateVNext = _appState.upgrade<AppStateVNext>(AppStateVNext);
override convert(): AppStateVNext
{
return (AppStateVNext.fromPriorAppState(this));
}
}
let _tempFolder: string = "C:/Bits";
let _canAcceptKeyStrokes: boolean = false;
let _isStopping: boolean = false;
function stopICTest()
{
if (!_isStopping)
{
_isStopping = true;
Utils.consoleInputStop();
IC.stop();
}
}
function reportVersion(version: string)
{
Utils.log(`JS Language Binding Version: ${version}`, "[App]");
}
function greetingsMethod(name: string)
{
Utils.log(`Greetings, ${name}!`, "[App]");
}
let _maxPerfIteration: number = -1; // The total number of messages that will be sent in a perf test
/** This method responds to incoming Ambrosia messages (RPCs and AppEvents). */
function messageDispatcher(message: Messages.DispatchedMessage): void
{
// WARNING! Rules for Message Handling:
//
// Rule 1: Messages must be handled - to completion - in the order received. For application (RPC) messages only, if there are messages that are known to
// be commutative then this rule can be relaxed - but only for RPC messages.
// Reason: Using Ambrosia requires applications to have deterministic execution. Further, system messages (like TakeCheckpoint) from the IC rely on being
// handled in the order they are sent to the app. This means being extremely careful about using non-synchronous code (like awaitable operations
// or callbacks) inside message handlers: the safest path is to always only use synchronous code.
//
// Rule 2: Before a TakeCheckpoint message can be handled, all handlers for previously received messages must have completed (ie. finished executing).
// If Rule #1 is followed, the app is automatically in compliance with Rule #2.
// Reason: Unless your application has a way to capture (and rehydrate) runtime execution state (specifically the message handler stack) in the serialized
// application state (checkpoint), recovery of the checkpoint will not be able to complete the in-flight message handlers. But if there are no
// in-flight handlers at the time the checkpoint is taken (because they all completed), then the problem of how to complete them during recovery is moot.
dispatcher(message);
}
/**
* Synchronous Ambrosia message dispatcher.
*
* **WARNING:** Avoid using any asynchronous features (async/await, promises, callbacks, timers, events, etc.). See "Rules for Message Handling" above.
*/
function dispatcher(message: Messages.DispatchedMessage): void
{
const loggingPrefix: string = "Dispatcher";
// Special case: This is a very high-frequency message [used during perf-testing], so we handle it immediately
if (message.type === Messages.DispatchedMessageType.RPC)
{
let rpc: Messages.IncomingRPC = message as Messages.IncomingRPC;
if (rpc.methodID === 200)
{
// Fork perf test
let buffer: Buffer = Buffer.from(rpc.getRawParams().buffer); // Use the ArrayBuffer to create a view [so no data is copied]
let iteration: number = buffer.readInt32LE(8); // We always need to read this [it changes with every message]
if (_maxPerfIteration === -1)
{
_maxPerfIteration = buffer.readInt32LE(12); // This is only sent with the first message
}
else
{
if (iteration === _maxPerfIteration)
{
let startTime: number = Number(buffer.readBigInt64LE(0)); // This is only sent with the last message
let elapsedMs: number = Date.now() - startTime;
let requestsPerSecond: number = (_maxPerfIteration / elapsedMs) * 1000;
Utils.log(`startTime: ${Utils.getTime(startTime)}, iteration: ${iteration}, elapsedMs: ${elapsedMs}, RPS = ${requestsPerSecond.toFixed(2)}`, null, Utils.LoggingLevel.Minimal);
}
else
{
// if (iteration % 5000 === 0)
// {
// Utils.log(`Received message #${iteration}`, null, Utils.LoggingLevel.Minimal);
// }
}
}
return;
}
}
try
{
switch (message.type)
{
case Messages.DispatchedMessageType.RPC:
let rpc: Messages.IncomingRPC = message as Messages.IncomingRPC;
if (Utils.canLog(Utils.LoggingLevel.Verbose)) // We add this check because this is a high-volume code path, and rpc.makeDisplayParams() is expensive
{
Utils.log(`Received ${Messages.RPCType[rpc.rpcType]} RPC call for ${rpc.methodID === IC.POST_METHOD_ID ? `post method '${IC.getPostMethodName(rpc)}' (version ${IC.getPostMethodVersion(rpc)})` : `method ID ${rpc.methodID}`} with params ${rpc.makeDisplayParams()}`, loggingPrefix);
}
switch (rpc.methodID)
{
// Note: To get to this point, the post method has been verified as published
case IC.POST_METHOD_ID:
try
{
let methodName: string = IC.getPostMethodName(rpc);
let methodVersion: number = IC.getPostMethodVersion(rpc); // Use this to do version-specific method behavior
switch (methodName)
{
case "ComputePI":
let digits: { count: number } = IC.getPostMethodArg(rpc, "digits?") ?? { count: 10 };
let pi: number = Number.parseFloat(Math.PI.toFixed(digits.count));
IC.postResult<number>(rpc, pi);
break;
case "joinNames":
let namesSet: Set<string> = IC.getPostMethodArg(rpc, "namesSet");
let namesArray: string[] = IC.getPostMethodArg(rpc, "namesArray");
IC.postResult<string>(rpc, [...namesSet, ...namesArray].map(v => v || "null").join(","));
break;
case "postTimeoutTest":
let resultDelayInMs: number = IC.getPostMethodArg(rpc, "resultDelayInMs?") ?? -1;
if (resultDelayInMs > 0)
{
// Simulate a delay at the destination instance [although this an imperfect simulation since it delays the send, not the receive]
setTimeout(() => IC.postResult<void>(rpc), resultDelayInMs);
}
else
{
// To [perfectly] simulate an infinite "delay" at the destination we simply don't call IC.postResult()
}
break;
default:
let errorMsg: string = `Post method '${methodName}' is not implemented`;
Utils.log(`(${errorMsg})`, loggingPrefix)
IC.postError(rpc, new Error(errorMsg));
break;
}
}
catch (error: unknown)
{
const err: Error = Utils.makeError(error);
Utils.log(err);
IC.postError(rpc, err);
}
break;
case 3:
let name: string = rpc.getJsonParam("name");
greetingsMethod(name);
break;
case 33:
let opName: string = rpc.getJsonParam("opName");
switch (opName)
{
case "attachToBadInstance":
// This is to help investigate bug #187
IC.callFork("serverTen", 3, { name: "Foo!" });
break;
case "sendLargeMessage":
const sizeInKB: number = parseInt(rpc.getJsonParam("sizeInKB"));
IC.echo_Post("x".repeat(1024 * sizeInKB), "sendLargeMessage");
break;
case "requestCheckpoint":
IC.requestCheckpoint();
break;
case "reportVersion":
IC.callFork(config.icInstanceName, 204, StringEncoding.toUTF8Bytes(Root.languageBindingVersion()));
break;
case "implicitBatch":
IC.callFork(config.icInstanceName, 3, { name: "BatchedMsg1" });
IC.callFork(config.icInstanceName, 3, { name: "BatchedMsg2" });
break;
case "explicitBatch":
IC.queueFork(config.icInstanceName, 3, { name: "John" });
IC.queueFork(config.icInstanceName, 3, { name: "Paul" });
IC.queueFork(config.icInstanceName, 3, { name: "George" });
IC.queueFork(config.icInstanceName, 3, { name: "Ringo" });
IC.flushQueue();
break;
case "runForkPerfTest":
// To get the best performance:
// 1) Set the 'outputLoggingLevel' to 'Minimal', and 'outputLogDestination' to 'File'.
// 2) The dispatcher() function should NOT be async.
// 3) Messages should be batched using RPCBatch.
// 4) The IC binary must be a release build (not debug).
// 5) Run the test OUTSIDE of the debugger.
if (Configuration.loadedConfig().lbOptions.outputLoggingLevel !== Utils.LoggingLevel.Minimal)
{
Utils.log("Incorrect configuration for test: 'outputLoggingLevel' must be 'Minimal'");
break;
}
const maxIteration: number = 1000000;
const batchSize: number = 10000;
Utils.log(`Starting Fork performance test [${maxIteration.toLocaleString()} messages in batches of ${batchSize.toLocaleString()}]...`, null, Utils.LoggingLevel.Minimal);
let startTime: number = Date.now();
let buffer: Buffer = Buffer.alloc(16);
let methodID: number = 200;
_maxPerfIteration = -1;
sendBatch(0, batchSize, maxIteration);
function sendBatch(startID: number, batchSize: number, messagesRemaining: number): void
{
batchSize = Math.min(batchSize, messagesRemaining);
for (let i = startID; i < startID + batchSize; i++)
{
if (i === maxIteration - 1)
{
buffer.writeBigInt64LE(BigInt(startTime), 0);
}
buffer.writeInt32LE(i + 1, 8);
if (i === 0)
{
buffer.writeInt32LE(maxIteration, 12);
}
IC.queueFork(config.icInstanceName, methodID, buffer);
}
IC.flushQueue();
// Utils.log(`Sent batch of ${batchSize} messages`, null, Utils.LoggingLevel.Minimal);
messagesRemaining -= batchSize;
if (messagesRemaining > 0)
{
setImmediate(sendBatch, startID + batchSize, batchSize, messagesRemaining);
}
}
break;
default:
Utils.log(`Error: Unknown Impulse operation '${opName}'`);
break;
}
break;
case 204:
let rawParams: Uint8Array = rpc.getRawParams();
let lbVersion = StringEncoding.fromUTF8Bytes(rawParams);
// let lbVersion: string = rpc.jsonParams["languageBindingVersion"];
reportVersion(lbVersion);
break;
default:
Utils.log(`(No method is associated with methodID ${rpc.methodID})`, loggingPrefix)
break;
}
break;
case Messages.DispatchedMessageType.AppEvent:
let appEvent: Messages.AppEvent = message as Messages.AppEvent;
switch (appEvent.eventType)
{
case Messages.AppEventType.ICConnected:
// Note: Types and methods are published in this handler so that they're available regardless of the 'icHostingMode'
publishEntities();
break;
case Messages.AppEventType.ICStarting:
break;
case Messages.AppEventType.ICStopped:
const exitCode: number = appEvent.args[0];
stopICTest();
break;
case Messages.AppEventType.BecomingPrimary:
Utils.log("Normal app processing can begin", loggingPrefix);
_canAcceptKeyStrokes = true;
break;
case Messages.AppEventType.UpgradeState:
{
const upgradeMode: Messages.AppUpgradeMode = appEvent.args[0];
_appState = _appState.upgrade<AppStateVNext>(AppStateVNext);
break;
}
case Messages.AppEventType.UpgradeCode:
{
const upgradeMode: Messages.AppUpgradeMode = appEvent.args[0];
IC.upgrade(messageDispatcher, checkpointProducer, checkpointConsumer, postResultDispatcher); // A no-op code upgrade
break;
}
case Messages.AppEventType.FirstStart:
IC.echo_Post(Date.now(), "now");
break;
}
break;
}
}
catch (error: unknown)
{
let messageName: string = (message.type === Messages.DispatchedMessageType.AppEvent) ? `AppEvent:${Messages.AppEventType[(message as Messages.AppEvent).eventType]}` : Messages.DispatchedMessageType[message.type];
Utils.log(`Error: Failed to process ${messageName} message`);
Utils.log(Utils.makeError(error));
}
}
function publishEntities(): void
{
// let tokens: string[] = Meta.Type.tokenizeComplexType("{ foo: string[], name: { firstName: string, lastName: { middleInitial: { mi: string }[], lastName: string }[][] }[][][], startDate: number }");
// Meta.publishType("rpcType", "number", Messages.RPCType);
// Meta.publishType("rpcType", "number", Messages.RPCType);
// Meta.publishType("surname", "{ middleInitial: string, lastName: string }");
// Meta.publishType("name", "{ firstName: string, lastName: surname[][] }"); // Note that this references the 'surname' custom type
// Meta.publishType("employee", "{ name: name, startDate: number }");
// let employeeInstance: object = {name: {firstName:"foo", lastName: [ [{ middleInitial: "x", lastName: "bar" }] ]}, startDate: 123}; // Alternative to the following definition
// // let employeeInstance: object = {name: {firstName:"foo", lastName: []}, startDate: 123}; // Alternative to the previous definition
// let employeeRuntimeType: string = Meta.Type.getRuntimeType(employeeInstance);
// let employeePublishedType: string = Meta.getPublishedType("employee").expandedDefinition;
// let match: boolean = (Meta.Type.compareComplexTypes(employeePublishedType, employeeRuntimeType) === null);
// let person1: object = [{ name: { firstName: "Mickey", lastName: { middleInitials: ["x", "y"] , surName: "Mouse" }}}];
// let person1RuntimeType: string = Meta.Type.getRuntimeType(person1);
// let person2: object = [[ { name: "Mickey"} ]];
// let person2RuntimeType: string = Meta.Type.getRuntimeType(person2);
// let person3: object = ["foo", "bar"];
// let person3RuntimeType: string = Meta.Type.getRuntimeType(person3);
// Meta.publishPostMethod("getEmployee", 1, ["employeeID:number"], "{ names: { firstName: string[], lastName: string }, startDate: number[], jobs: {title: string, durationInSeconds: bigint[] }[] }");
// Meta.publishType("employee", " { names: { firstNames: string[], lastName:string} , startDate: number[], jobs: {title: string, durationInSeconds: bigint[] } [] }");
// Meta.publishPostMethod("getEmployee", 1, ["employeeID:number"], "employee");
// let numberArray: number[] = [1, 2, 3];
// let stringArray: string[] = ['1', '2', '3'];
// let typedArrayArray: Uint8Array[] = [Uint8Array.from([0]), Uint8Array.from([1])];
// let type: string = "";
// let employee: object = { foo: { bar: "hello" }, name: { firstName: "mickey", lastName: "mouse", aliases: { workAliases: ["Boss"], homeAliases: ["BigEars"] } }, age: 92 };
// let employee2: object = { foo: [ { names: [ { name: "hello" }, { name: "world" } ] }, { names: [ { name: "hello!" }, { name: "world!" } ] } ] };
// type = Meta.Type.getRuntimeType(type);
// type = Meta.Type.getRuntimeType(employee);
// type = Meta.Type.getRuntimeType(employee2);
// type = Meta.Type.getRuntimeType(numberArray);
// type = Meta.Type.getRuntimeType(stringArray);
// type = Meta.Type.getRuntimeType(typedArrayArray);
// Meta.publishType("TestType", "{ name: { first: string, last: string }, foo: Digits }");
// Meta.publishType("TestSimpleType", "Digits[][]");
// Meta.publishPostMethod("TestMethod", 1, ["rawParams: Uint8Array", "foo: string"], "number");
Meta.publishType("Digits", "{ count: number }");
Meta.publishPostMethod("ComputePI", 1, ["digits?: Digits"], "number");
Meta.publishMethod(204, "bootstrap", ["rawParams:Uint8Array"]);
Meta.publishMethod(3, "greetings", ["name:string"]);
Meta.publishPostMethod("joinNames", 1, ["namesSet: Set<string>", "namesArray: string[]"], "string");
Meta.publishPostMethod("postTimeoutTest", 1, ["resultDelayInMs?: number"], "void");
}
// Handler for the results of previously called post methods (in Ambrosia, only 'post' methods return values). See Messages.PostResultDispatcher.
function postResultDispatcher(senderInstanceName: string, methodName: string, methodVersion: number, callID: number, callContextData: any, result: any, errorMsg: string): boolean
{
let handled: boolean = true;
if (errorMsg)
{
Utils.log(`Error: ${errorMsg}`);
}
else
{
switch (methodName)
{
case "_echo": // The result from IC.echo_Post()
switch (callContextData)
{
case "now":
const now: number = result;
Utils.log(`Now is: ${Utils.getTime(now)}`);
break;
case "sendLargeMessage":
const s: string = result;
Utils.log(`Large message size: ${(s.length / 1024.0)} KB`, null, Utils.LoggingLevel.Minimal);
break;
default:
handled = false;
}
break;
case "_getPublishedMethods": // The result from Meta.getPublishedMethods_Post()
const methodListXml: string = result;
const formattedMethodListXml: string = Utils.formatXml(Utils.decodeXml(methodListXml));
Utils.logHeader(`Available methods on '${callContextData.targetInstanceName}':`);
Utils.log(formattedMethodListXml.indexOf(Utils.NEW_LINE) === -1 ? formattedMethodListXml : Utils.NEW_LINE + formattedMethodListXml);
break;
case "_getPublishedTypes": // The result from Meta.getPublishedTypes_Post()
const typeListXml: string = result;
const formattedTypeListXml: string = Utils.formatXml(typeListXml);
Utils.logHeader(`Available types on '${callContextData.targetInstanceName}':`);
Utils.log(formattedTypeListXml.indexOf(Utils.NEW_LINE) === -1 ? formattedTypeListXml : Utils.NEW_LINE + formattedTypeListXml);
break;
case "_isPublishedMethod": // The result from Meta.isPublishedMethod_Post()
const isPublished: boolean = result;
Utils.log(`Method '${callContextData.targetMethodName}' (version ${callContextData.targetMethodVersion}) is ${isPublished ? "published" : "not published"}`);
break;
case "ComputePI":
Utils.log(result ? `PI = ${result}` : "ComputePI returned void");
break;
case "joinNames":
Utils.log(`Joined names = ${result}`);
break;
case "_ping":
const roundtripTimeInMs: number = result;
const pingResult: string = (roundtripTimeInMs === -1) ? `failed [after ${callContextData.timeoutInMs}ms]` : `succeeded [round-trip time: ${roundtripTimeInMs}ms]`;
Utils.log(`Ping of '${callContextData.destinationInstance}' ${pingResult}`);
break;
default:
handled = false;
}
}
return (handled);
}
/** Serializes the app state and returns an OutgoingCheckpoint object. */
function checkpointProducer(): Streams.OutgoingCheckpoint
{
/*
// Create a stream that will be used as the output for serialized app state
// TODO: This is just a test stream
let testCheckpointFileName: string = Path.join(_tempFolder, "GeneratedCheckpoint.dat");
let checkpointLength: number = 123; // (1024 * 1024 * 100) + 123; // 100 MB
if ((Utils.getFileSize(testCheckpointFileName) != checkpointLength))
{
Utils.createTestFile(testCheckpointFileName, checkpointLength)
}
let checkpointStream: Stream.Readable = fs.createReadStream(testCheckpointFileName);
// When the checkpoint stream has been sent, OutgoingCheckpoint.onFinished() will be called.
return ({ dataStream: checkpointStream, length: checkpointLength, onFinished: onCheckpointSent });
*/
function onCheckpointSent(error?: Error): void
{
Utils.log(`checkpointProducer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint saved"}`)
}
return (Streams.simpleCheckpointProducer(_appState, onCheckpointSent));
}
/** Returns an IncomingCheckpoint object used to receive a checkpoint of app state. */
function checkpointConsumer(): Streams.IncomingCheckpoint
{
/*
// Create a stream that will be used as the input to deserialize and load a checkpoint of app state
// TODO: This is just a test stream
let receiverStream: Stream.Writable = fs.createWriteStream(Path.join(_tempFolder, "ReceivedCheckpoint.dat"));
return ({ dataStream: receiverStream, onFinished: null });
*/
function onCheckpointReceived(appState?: Root.AmbrosiaAppState, error?: Error): void
{
if (!error)
{
if (!appState) // Should never happen
{
throw new Error(`An appState object was expected, not ${appState}`);
}
_appState = appState as AppState;
}
Utils.log(`checkpointConsumer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint loaded"}`);
}
return (Streams.simpleCheckpointConsumer<AppState>(AppState, onCheckpointReceived));
}
let config: Configuration.AmbrosiaConfig = new Configuration.AmbrosiaConfig(messageDispatcher, checkpointProducer, checkpointConsumer, postResultDispatcher);
Utils.log(`IC test running: Press 'X' (or 'Enter') to stop${config.isIntegratedIC && !config.isTimeTravelDebugging ? ", or 'H' to list all available test commands" : ""}`);
// @ts-tactical-any-cast: Suppress error "Argument of type 'typeof AppState' is not assignable to parameter of type 'new (restoredAppState?: AppStateVNext | AppState | undefined) => AppStateVNext | AppState' ts(2345)" [because we use 'strictFunctionTypes']
let _appState: AppState | AppStateVNext = IC.start<AppState | AppStateVNext>(config, AppState as any);
// Test of AppState upgrade
// _appState = _appState.upgrade<AppStateVNext>(AppStateVNext);
// Detect when 'x' (or 'Enter') is pressed, or other message-generating key (eg. F[ork], B[atch], [P]ost)
Utils.consoleInputStart(handleKeyStroke);
// Add handler for Ctrl+Break [this only works for Windows and only for Cmd.exe; PowerShell reserves Ctrl+Break to break into the script debugger]
process.on("SIGBREAK", () =>
{
handleKeyStroke(String.fromCharCode(3)); // 3 is the "Ctrl+C" code
});
async function handleKeyStroke(char: string)
{
const isCtrlC: boolean = (char.charCodeAt(0) === 3);
const runningTTDorSeparated: boolean = (config.isIntegratedIC && config.isTimeTravelDebugging) || (config.icHostingMode === Configuration.ICHostingMode.Separated);
// Always allow Ctrl+C, and always allow 'X' and 'Enter' when in TTD mode (if running Integrated), or when running in 'Separated' IC mode
if (isCtrlC || (runningTTDorSeparated && ((char === 'x') || (char === Utils.ENTER_KEY))))
{
Utils.log("IC test stopping");
stopICTest();
return;
}
if (!_canAcceptKeyStrokes)
{
return;
}
try
{
switch (char)
{
case "h":
Utils.logHeader("Available test commands:")
Utils.log("X: Exit (stop) the test");
Utils.log("F: Call Fork RPC");
Utils.log("I: Call implicitly batched RPC");
Utils.log("B: Call explicitly batched RPCs");
Utils.log("P: Post RPC");
Utils.log("O: Post RPC Timeout Test (10 seconds)");
Utils.log("M: Get published methods");
Utils.log("T: Get published types");
Utils.log("S: Check if a method (of a specific version) is published");
Utils.log("R: Request checkpoint");
Utils.log("E: Echo");
Utils.log("L: Send large message (64 MB)");
Utils.log("Z: Run Fork performance test");
break;
case "x":
case Utils.ENTER_KEY:
Utils.log("IC test stopping");
stopICTest();
break;
case "a":
IC.callImpulse(config.icInstanceName, 33, { opName: "attachToBadInstance" });
break;
case "r":
IC.callImpulse(config.icInstanceName, 33, { opName: "requestCheckpoint" });
break;
case "l":
// Note: Using 128 MB requires setting lbOptions.maxMessageQueueSizeInMB to 129 (MB) or higher
Utils.log("Sending large message...", null, Utils.LoggingLevel.Minimal);
IC.callImpulse(config.icInstanceName, 33, { opName: "sendLargeMessage", sizeInKB: 64 * 1024 })
break;
case "f": // Fork
// IC.callFork(config.icInstanceName, 3, { name: "AmbrosiaJS" });
IC.callImpulse(config.icInstanceName, 33, { opName: "reportVersion" });
break;
case "b": // [Explicit] Batch
IC.callImpulse(config.icInstanceName, 33, { opName: "explicitBatch" });
break;
case "i": // [Implicit] Batch
IC.callImpulse(config.icInstanceName, 33, { opName: "implicitBatch" });
break;
case "p": // Post
/*
if (config.icInstanceName !== "test")
{
IC.postFork("test", "ComputePI", 1, -1, null, 5);
}
*/
// IC.postFork(config.icInstanceName, "ComputePI", 1, -1, null, IC.arg("digits?", { count: 5 }));
IC.postByImpulse(config.icInstanceName, "joinNames", 1, -1, null, IC.arg("namesSet", new Set<string>(["a", "b", "c"])), IC.arg("namesArray", [null, "e", null, "g"]));
break;
case "o": // Post timeout
IC.postByImpulse(config.icInstanceName, "postTimeoutTest", 1, 10000, null, IC.arg("resultDelayInMs?", -1));
break;
case "e": // Echo
IC.echo_PostByImpulse(Date.now(), "now");
break;
case "g": // Ping
IC.ping_PostByImpulse(config.icInstanceName);
break;
case "m": // getPublishedMethods
// Note: We don't need to pass a callContext object here, we're just doing it for illustration purposes
Meta.getPublishedMethods_PostByImpulse(config.icInstanceName, false, false, { targetInstanceName: config.icInstanceName });
break;
case "t": // getPublishedTypes
// Note: We don't need to pass a callContext object here, we're just doing it for illustration purposes
Meta.getPublishedTypes_PostByImpulse(config.icInstanceName, false, { targetInstanceName: config.icInstanceName });
break;
case "s": // isPublishedMethod
// Note: We don't need to pass a callContext object here, we're just doing it for illustration purposes
Meta.isPublishedMethod_PostByImpulse(config.icInstanceName, "ComputePI", 1, { targetMethodName: "ComputePI", targetMethodVersion: 1 });
break;
case "z": // Fork perf test
// Note: Run with "node .\lib\Demo.js" [use a Release IC.exe] and set 'outputLoggingLevel' to 'Minimal' in ambrosiaConfig.json; 'outputLogDestination' can be 'ConsoleAndFile'
IC.callImpulse(config.icInstanceName, 33, { opName: "runForkPerfTest" });
break;
}
}
catch (error: unknown)
{
Utils.log("Error: " + Utils.makeError(error).message);
}
}
} | the_stack |
import bigInt from 'big-integer'
import { assert } from 'chai'
import { Utils, XrplNetwork } from 'xpring-common-js'
import { XrpError, XrpUtils } from '../../../src'
import XrpCurrency from '../../../src/XRP/protobuf-wrappers/xrp-currency'
import XrpCurrencyAmount from '../../../src/XRP/protobuf-wrappers/xrp-currency-amount'
import XrplIssuedCurrency from '../../../src/XRP/protobuf-wrappers/xrpl-issued-currency'
import XrpMemo from '../../../src/XRP/protobuf-wrappers/xrp-memo'
import XrpPath from '../../../src/XRP/protobuf-wrappers/xrp-path'
import XrpPathElement from '../../../src/XRP/protobuf-wrappers/xrp-path-element'
import XrpPayment from '../../../src/XRP/protobuf-wrappers/xrp-payment'
import XrpSigner from '../../../src/XRP/protobuf-wrappers/xrp-signer'
import XrpTransaction from '../../../src/XRP/protobuf-wrappers/xrp-transaction'
import XrpSignerEntry from '../../../src/XRP/protobuf-wrappers/xrp-signer-entry'
import {
testTransactionSignature,
testSequence,
testFee,
testMemoData,
testMemoFormat,
testMemoType,
testAccountTransactionID,
testFlags,
testLastLedgerSequence,
testTransactionHash,
expectedTimestamp,
testIsValidated,
testLedgerIndex,
testCurrencyProto,
testPathElementProtoWithAccount,
testPathElementProtoWithCurrencyIssuer,
testEmptyPathProto,
testPathProtoOneElement,
testPathProtoThreeElements,
testIssuedCurrencyProto,
testCurrencyAmountProtoDrops,
testCurrencyAmountProtoIssuedCurrency,
testPaymentProtoAllFieldsSet,
testPaymentProtoMandatoryFieldsOnly,
testMemoProtoAllFields,
testEmptyMemoProto,
testSignerProto,
testSignerEntryProto,
testGetTransactionResponseProto,
testGetTransactionResponseProtoMandatoryOnly,
testGetTransactionResponseProtoSigners,
testInvalidIssuedCurrencyProtoBadValue,
testInvalidIssuedCurrencyProtoBadIssuer,
testInvalidIssuedCurrencyProtoBadCurrency,
testInvalidCurrencyProtoNoName,
testInvalidCurrencyProtoNoCode,
testInvalidCurrencyAmountProto,
testInvalidCurrencyAmountProtoEmpty,
testInvalidPathElementWithAccountIssuer,
testInvalidPathElementWithAccountCurrency,
testInvalidPathElementProtoEmpty,
testInvalidPaymentProtoNoAmount,
testInvalidPaymentProtoBadDestination,
testInvalidPaymentProtoNoDestination,
testInvalidPaymentProtoXrpPaths,
testInvalidPaymentProtoXrpSendMax,
testInvalidSignerProtoNoAccount,
testInvalidSignerProtoBadAccount,
testInvalidSignerProtoNoPublicKey,
testInvalidSignerProtoNoTxnSignature,
testInvalidSignerEntryProtoNoAccount,
testInvalidSignerEntryProtoBadAccount,
testInvalidSignerEntryProtoNoSignerWeight,
testInvalidGetTransactionResponseProto,
testInvalidGetTransactionResponseProtoUnsupportedType,
testInvalidGetTransactionResponseProtoNoTransaction,
testInvalidGetTransactionResponseProtoNoAccount,
testInvalidGetTransactionResponseProtoBadAccount,
testInvalidGetTransactionResponseProtoNoFee,
testInvalidGetTransactionResponseProtoBadFee,
testInvalidGetTransactionResponseProtoNoSequence,
testInvalidGetTransactionResponseProtoNoSigningPublicKey,
testInvalidGetTransactionResponseProtoNoSigners,
testInvalidGetTransactionResponseProtoNoSignature,
testInvalidGetTransactionResponseProtoNoData,
testInvalidGetTransactionResponseProtoNoHash,
} from '../fakes/fake-xrp-protobufs'
// TODO(amiecorso): Refactor tests to separate files.
describe('Protocol Buffer Conversion', function (): void {
// Currency
it('Convert Currency protobuf to XrpCurrency object', function (): void {
// GIVEN a Currency protocol buffer with a code and a name.
// WHEN the protocol buffer is converted to a native Typescript type.
const currency = XrpCurrency.from(testCurrencyProto)
// THEN the currency converted as expected.
assert.deepEqual(currency.code, testCurrencyProto.getCode_asB64())
assert.deepEqual(currency.name, testCurrencyProto.getName())
})
it('Convert Currency protobuf missing required field name', function (): void {
// GIVEN a Currency protocol buffer missing a name.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpCurrency.from(testInvalidCurrencyProtoNoName)
}, XrpError)
})
it('Convert Currency protobuf missing required field code', function (): void {
// GIVEN a Currency protocol buffer missing a code.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpCurrency.from(testInvalidCurrencyProtoNoCode)
}, XrpError)
})
// PathElement
it('Convert PathElement protobuf with one valid field set to XrpPathElement', function (): void {
// GIVEN a PathElement protocol buffer with account field set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const pathElement = XrpPathElement.from(testPathElementProtoWithAccount)
// THEN the currency converted as expected.
assert.equal(
pathElement.account,
testPathElementProtoWithAccount.getAccount()!.getAddress(),
)
assert.equal(pathElement.currency, undefined)
assert.equal(pathElement.issuer, undefined)
})
it('Convert PathElement protobuf with two valid fields set to XrpPathElement', function (): void {
// GIVEN a PathElement protocol buffer with currency and issuer fields set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const pathElement = XrpPathElement.from(
testPathElementProtoWithCurrencyIssuer,
)
// THEN the currency converted as expected.
assert.equal(pathElement.account, undefined)
assert.deepEqual(
pathElement.currency,
XrpCurrency.from(testPathElementProtoWithCurrencyIssuer.getCurrency()!),
)
assert.equal(
pathElement.issuer,
testPathElementProtoWithCurrencyIssuer.getIssuer()!.getAddress(),
)
})
it('Convert PathElement protobuf with mutually exclusive fields set to XrpPathElement', function (): void {
// GIVEN a PathElement protocol buffer with account and currency fields set.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpPathElement.from(testInvalidPathElementWithAccountCurrency)
}, XrpError)
})
it('Convert PathElement protobuf with different mutually exclusive fields set to XrpPathElement', function (): void {
// GIVEN a PathElement protocol buffer with account and issuer fields set.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpPathElement.from(testInvalidPathElementWithAccountIssuer)
}, XrpError)
})
it('Convert PathElement protobuf with no fields set to XrpPathElement', function (): void {
// GIVEN a PathElement protocol buffer with no fields set.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpPathElement.from(testInvalidPathElementProtoEmpty)
}, XrpError)
})
// Path
it('Convert Path protobuf with no paths to XrpPath', function (): void {
// GIVEN a set of paths with zero path elements.
// WHEN the protocol buffer is converted to a native TypeScript type.
const path = XrpPath.from(testEmptyPathProto)
// THEN there are zero paths in the output.
assert.equal(path.pathElements.length, 0)
})
it('Convert Path protobuf with one path element to XrpPath', function (): void {
// GIVEN a set of paths with one path element.
// WHEN the protocol buffer is converted to a native TypeScript type.
const path = XrpPath.from(testPathProtoOneElement)
// THEN there is one path in the output.
assert.equal(path.pathElements.length, 1)
})
it('Convert Path protobuf with many Paths to XrpPath', function (): void {
// GIVEN a set of paths with three path elements.
// WHEN the protocol buffer is converted to a native TypeScript type.
const path = XrpPath.from(testPathProtoThreeElements)
// THEN there are multiple paths in the output.
assert.equal(path.pathElements.length, 3)
})
// IssuedCurrency
it('Convert IssuedCurrency to XrplIssuedCurrency', function (): void {
// GIVEN an IssuedCurrency protocol buffer,
// WHEN the protocol buffer is converted to a native TypeScript type.
const issuedCurrency = XrplIssuedCurrency.from(testIssuedCurrencyProto)
// THEN the IssuedCurrency converted as expected.
assert.deepEqual(
issuedCurrency?.currency,
XrpCurrency.from(testIssuedCurrencyProto.getCurrency()!),
)
assert.equal(
issuedCurrency?.issuer,
testIssuedCurrencyProto.getIssuer()?.getAddress(),
)
assert.deepEqual(
issuedCurrency?.value,
bigInt(testIssuedCurrencyProto.getValue()),
)
})
it('Convert IssuedCurrency with bad value', function (): void {
// GIVEN an IssuedCurrency protocol buffer with an invalid value field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrplIssuedCurrency.from(testInvalidIssuedCurrencyProtoBadValue)
}, XrpError)
})
it('Convert IssuedCurrency with bad issuer', function (): void {
// GIVEN an IssuedCurrency protocol buffer with a missing issuer field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrplIssuedCurrency.from(testInvalidIssuedCurrencyProtoBadIssuer)
}, XrpError)
})
it('Convert IssuedCurrency with bad currency', function (): void {
// GIVEN an IssuedCurrency protocol buffer with a missing currency field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrplIssuedCurrency.from(testInvalidIssuedCurrencyProtoBadCurrency)
}, XrpError)
})
// CurrencyAmount tests
it('Convert CurrencyAmount with drops', function (): void {
// GIVEN a CurrencyAmount protocol buffer with an XRP amount.
// WHEN the protocol buffer is converted to a native TypeScript type.
const currencyAmount = XrpCurrencyAmount.from(testCurrencyAmountProtoDrops)
// THEN the result has drops set and no issued amount.
assert.isUndefined(currencyAmount?.issuedCurrency)
assert.equal(
currencyAmount?.drops,
testCurrencyAmountProtoDrops.getXrpAmount()?.getDrops(),
)
})
it('Convert CurrencyAmount with Issued Currency', function (): void {
// GIVEN a CurrencyAmount protocol buffer with an issued currency amount.
// WHEN the protocol buffer is converted to a native TypeScript type.
const currencyAmount = XrpCurrencyAmount.from(
testCurrencyAmountProtoIssuedCurrency,
)
// THEN the result has an issued currency set and no drops amount.
assert.deepEqual(
currencyAmount?.issuedCurrency,
XrplIssuedCurrency.from(testIssuedCurrencyProto),
)
assert.isUndefined(currencyAmount?.drops)
})
it('Convert CurrencyAmount with bad inputs', function (): void {
// GIVEN a CurrencyAmount protocol buffer with no amounts
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpCurrencyAmount.from(testInvalidCurrencyAmountProto)
}, XrpError)
})
it('Convert CurrencyAmount with nothing set', function (): void {
// GIVEN a CurrencyAmount protocol buffer with nothing set
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpCurrencyAmount.from(testInvalidCurrencyAmountProtoEmpty)
}, XrpError)
})
// Payment
it('Convert Payment with all fields set', function (): void {
// GIVEN a payment protocol buffer with all fields set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const payment = XrpPayment.from(
testPaymentProtoAllFieldsSet,
XrplNetwork.Test,
)
// THEN the result is as expected.
assert.deepEqual(
payment.amount,
XrpCurrencyAmount.from(
testPaymentProtoAllFieldsSet.getAmount()?.getValue()!,
),
)
assert.equal(
payment.destinationXAddress,
XrpUtils.encodeXAddress(
testPaymentProtoAllFieldsSet
.getDestination()!
.getValue()!
.getAddress()!,
testPaymentProtoAllFieldsSet.getDestinationTag()?.getValue(),
true,
),
)
assert.deepEqual(
payment.deliverMin,
XrpCurrencyAmount.from(
testPaymentProtoAllFieldsSet.getDeliverMin()?.getValue()!,
),
)
assert.deepEqual(
payment.invoiceID,
testPaymentProtoAllFieldsSet.getInvoiceId()?.getValue(),
)
assert.deepEqual(
payment.paths,
testPaymentProtoAllFieldsSet
.getPathsList()
.map((path) => XrpPath.from(path)),
)
assert.deepEqual(
payment.sendMax,
XrpCurrencyAmount.from(
testPaymentProtoAllFieldsSet.getSendMax()?.getValue()!,
),
)
})
it('Convert Payment with only mandatory fields set', function (): void {
// GIVEN a payment protocol buffer with only mandatory fields set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const payment = XrpPayment.from(
testPaymentProtoMandatoryFieldsOnly,
XrplNetwork.Test,
)
// THEN the result is as expected.
assert.deepEqual(
payment.amount,
XrpCurrencyAmount.from(
testPaymentProtoMandatoryFieldsOnly.getAmount()?.getValue()!,
),
)
assert.equal(
payment.destinationXAddress,
XrpUtils.encodeXAddress(
testPaymentProtoMandatoryFieldsOnly
?.getDestination()!
.getValue()!
.getAddress()!,
testPaymentProtoMandatoryFieldsOnly?.getDestinationTag()?.getValue(),
true,
),
)
assert.deepEqual(
payment.sendMax,
XrpCurrencyAmount.from(
testPaymentProtoMandatoryFieldsOnly.getSendMax()?.getValue()!,
),
)
assert.isUndefined(payment.deliverMin)
assert.isUndefined(payment.invoiceID)
assert.isUndefined(payment.paths)
})
it('Convert Payment without amount field', function (): void {
// GIVEN a payment protocol buffer without amount field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown
assert.throws(() => {
XrpPayment.from(testInvalidPaymentProtoNoAmount, XrplNetwork.Test)
}, XrpError)
})
it('Convert Payment without destination field', function (): void {
// GIVEN a payment protocol buffer without destination field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown
assert.throws(() => {
XrpPayment.from(testInvalidPaymentProtoNoDestination, XrplNetwork.Test)
}, XrpError)
})
it('Convert Payment with invalid destination field', function (): void {
// GIVEN a payment protocol buffer with an invalid destination field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown
assert.throws(() => {
XrpPayment.from(testInvalidPaymentProtoBadDestination, XrplNetwork.Test)
}, XrpError)
})
it('Convert Payment with paths field in XRP transaction', function (): void {
// GIVEN a payment protocol buffer with a paths field in an XRP transaction
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown
assert.throws(() => {
XrpPayment.from(testInvalidPaymentProtoXrpPaths, XrplNetwork.Test)
}, XrpError)
})
it('Convert Payment with sendMax field in XRP transaction', function (): void {
// GIVEN a payment protocol buffer with a sendMax field in an XRP transaction
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown
assert.throws(() => {
XrpPayment.from(testInvalidPaymentProtoXrpSendMax, XrplNetwork.Test)
}, XrpError)
})
// Memo
it('Convert Memo with all fields set', function (): void {
// GIVEN a memo with all fields set.
// WHEN the protocol buffer is converted to a native TypeScript type
const memo = XrpMemo.from(testMemoProtoAllFields)
// THEN all fields are present and set correctly.
assert.deepEqual(memo?.data, testMemoData)
assert.deepEqual(memo?.format, testMemoFormat)
assert.deepEqual(memo?.type, testMemoType)
})
it('Convert Memo with no fields set', function (): void {
// GIVEN a memo with no fields set.
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpMemo.from(testEmptyMemoProto)
}, XrpError)
})
// Signer
it('Convert Signer protobuf with all fields set', function (): void {
// GIVEN a Signer protocol buffer with all fields set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const signer = XrpSigner.from(testSignerProto, XrplNetwork.Test)
// THEN all fields are present and converted correctly.
assert.equal(
signer?.accountXAddress,
XrpUtils.encodeXAddress(
testSignerProto.getAccount()?.getValue()?.getAddress()!,
undefined,
true,
),
)
assert.deepEqual(
signer?.signingPublicKey,
testSignerProto.getSigningPublicKey()?.getValue_asU8(),
)
assert.deepEqual(
signer?.transactionSignature,
testSignerProto.getTransactionSignature()?.getValue_asU8(),
)
})
it('Convert Signer protobuf missing required field account', function (): void {
// GIVEN a Signer protocol buffer missing an account.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpSigner.from(testInvalidSignerProtoNoAccount, XrplNetwork.Test)
}, XrpError)
})
it('Convert Signer protobuf with invalid field account', function (): void {
// GIVEN a Signer protocol buffer with an invalid account.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpSigner.from(testInvalidSignerProtoBadAccount, XrplNetwork.Test)
}, XrpError)
})
it('Convert Signer protobuf missing required field SigningPubKey', function (): void {
// GIVEN a Signer protocol buffer missing a public key.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpSigner.from(testInvalidSignerProtoNoPublicKey, XrplNetwork.Test)
}, XrpError)
})
it('Convert Signer protobuf missing required field TxnSignature', function (): void {
// GIVEN a Signer protocol buffer missing a transaction signature.
// WHEN the protocol buffer is converted to a native Typescript type THEN an error is thrown.
assert.throws(() => {
XrpSigner.from(testInvalidSignerProtoNoTxnSignature, XrplNetwork.Test)
}, XrpError)
})
// SignerEntry
it('Convert SignerEntry with all fields set', function (): void {
// GIVEN a SignerEntry protocol buffer with all fields set.
// WHEN the protocol buffer is converted to a native TypeScript type.
const signerEntry = XrpSignerEntry.from(
testSignerEntryProto,
XrplNetwork.Test,
)
// THEN all fields are present and converted correctly.
const expectedXAddress = XrpUtils.encodeXAddress(
testSignerEntryProto.getAccount()?.getValue()?.getAddress()!,
undefined,
true,
)
assert.equal(signerEntry.accountXAddress, expectedXAddress)
assert.equal(
signerEntry.signerWeight,
testSignerEntryProto.getSignerWeight()?.getValue(),
)
})
it('Convert SignerEntry with no account field set', function (): void {
// GIVEN a SignerEntry protocol buffer with no account field set.
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpSignerEntry.from(
testInvalidSignerEntryProtoNoAccount,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert SignerEntry with bad account field', function (): void {
// GIVEN a SignerEntry protocol buffer with a bad account field.
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpSignerEntry.from(
testInvalidSignerEntryProtoBadAccount,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert SignerEntry with no SignerWeight field set', function (): void {
// GIVEN a SignerEntry protocol buffer with no signerWeight field set.
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpSignerEntry.from(
testInvalidSignerEntryProtoNoSignerWeight,
XrplNetwork.Test,
)
}, XrpError)
})
// Transaction
it('Convert PAYMENT Transaction, all common fields set', function (): void {
// GIVEN a GetTransactionResponse protobuf containing a Transaction protobuf with all common fields set.
const transactionProto = testGetTransactionResponseProto.getTransaction()
// WHEN the protocol buffer is converted to a native TypeScript type.
const transaction = XrpTransaction.from(
testGetTransactionResponseProto,
XrplNetwork.Test,
)
// THEN all fields are present and converted correctly.
assert.equal(transaction.fee, testFee)
assert.equal(transaction.sequence, testSequence)
assert.equal(
transaction.signingPublicKey,
transactionProto?.getSigningPublicKey()?.getValue_asB64(),
)
assert.equal(transaction.transactionSignature, testTransactionSignature)
assert.equal(transaction.accountTransactionID, testAccountTransactionID)
assert.equal(transaction.flags, testFlags)
assert.equal(transaction.lastLedgerSequence, testLastLedgerSequence)
assert.deepEqual(transaction.memos, [XrpMemo.from(testMemoProtoAllFields)!])
assert.deepEqual(transaction.signers, [
XrpSigner.from(testSignerProto, XrplNetwork.Test)!,
])
assert.equal(
transaction.sourceXAddress,
XrpUtils.encodeXAddress(
transactionProto!.getAccount()!.getValue()!.getAddress()!,
transactionProto!.getSourceTag()?.getValue(),
true,
),
)
assert.equal(transaction.hash, Utils.toHex(testTransactionHash))
assert.equal(transaction.timestamp, expectedTimestamp)
assert.equal(
transaction.deliveredAmount,
testGetTransactionResponseProto
.getMeta()
?.getDeliveredAmount()
?.getValue()
?.getIssuedCurrencyAmount()
?.getValue(),
)
assert.equal(transaction.validated, testIsValidated)
assert.equal(transaction.ledgerIndex, testLedgerIndex)
})
it('Convert PAYMENT Transaction with only mandatory common fields set', function (): void {
// GIVEN a GetTransactionResponse protocol buffer containing a Transaction protobuf with only mandatory common fields set.
const transactionProto = testGetTransactionResponseProtoMandatoryOnly.getTransaction()
// WHEN the protocol buffer is converted to a native TypeScript type.
const transaction = XrpTransaction.from(
testGetTransactionResponseProtoMandatoryOnly,
XrplNetwork.Test,
)
// THEN all fields are present and converted correctly.
assert.equal(transaction.fee, testFee)
assert.equal(transaction.sequence, testSequence)
assert.deepEqual(
transaction.signingPublicKey,
transactionProto?.getSigningPublicKey()?.getValue_asB64(),
)
assert.deepEqual(transaction.transactionSignature, testTransactionSignature)
assert.equal(transaction.hash, Utils.toHex(testTransactionHash))
assert.isUndefined(transaction.accountTransactionID)
assert.isUndefined(transaction.flags)
assert.isUndefined(transaction.lastLedgerSequence)
assert.isUndefined(transaction.memos)
assert.isUndefined(transaction.signers)
assert.equal(
transaction.sourceXAddress,
XrpUtils.encodeXAddress(
transactionProto!.getAccount()!.getValue()!.getAddress()!,
transactionProto!.getSourceTag()?.getValue(),
true,
),
)
assert.isUndefined(transaction.timestamp)
assert.isUndefined(transaction.deliveredAmount)
})
it('Convert PAYMENT Transaction with mandatory common fields set, with signers instead of public key', function (): void {
// GIVEN a GetTransactionResponse protocol buffer containing a Transaction protobuf with only mandatory common fields set.
const transactionProto = testGetTransactionResponseProtoSigners.getTransaction()
// WHEN the protocol buffer is converted to a native TypeScript type.
const transaction = XrpTransaction.from(
testGetTransactionResponseProtoSigners,
XrplNetwork.Test,
)
// THEN all fields are present and converted correctly.
assert.equal(transaction.fee, testFee)
assert.equal(transaction.sequence, testSequence)
assert.deepEqual(
transaction.signingPublicKey,
transactionProto?.getSigningPublicKey()?.getValue_asB64(),
)
assert.deepEqual(transaction.transactionSignature, testTransactionSignature)
assert.equal(transaction.hash, Utils.toHex(testTransactionHash))
assert.isUndefined(transaction.accountTransactionID)
assert.isUndefined(transaction.flags)
assert.isUndefined(transaction.lastLedgerSequence)
assert.isUndefined(transaction.memos)
assert.deepEqual(transaction.signers, [
XrpSigner.from(testSignerProto, XrplNetwork.Test)!,
])
assert.equal(
transaction.sourceXAddress,
XrpUtils.encodeXAddress(
transactionProto?.getAccount()!.getValue()!.getAddress()!,
transactionProto?.getSourceTag()?.getValue(),
true,
),
)
assert.isUndefined(transaction.timestamp)
assert.isUndefined(transaction.deliveredAmount)
})
it('Convert PAYMENT Transaction with bad payment fields', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with Transaction payment fields which are incorrect
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProto,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert unsupported transaction type', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction of unsupported type
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoUnsupportedType,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert Transaction with no transaction', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with no Transaction field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoTransaction,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no account', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing an account field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoAccount,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with bad account', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field with a bad account field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoBadAccount,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no fee', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a fee field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoFee,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with bad fee', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field with a bad fee field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoBadFee,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no sequence', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a sequence field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoSequence,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no signingPublicKey', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a signingPublicKey field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoSigningPublicKey,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no signers', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a signers field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoSigners,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no transactionSignature', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a transactionSignature field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoSignature,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no data', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a data field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoData,
XrplNetwork.Test,
)
}, XrpError)
})
it('Convert PAYMENT Transaction with no hash', function (): void {
// GIVEN a GetTransactionResponse protocol buffer with a Transaction field missing a hash field
// WHEN the protocol buffer is converted to a native TypeScript type THEN an error is thrown.
assert.throws(() => {
XrpTransaction.from(
testInvalidGetTransactionResponseProtoNoHash,
XrplNetwork.Test,
)
}, XrpError)
})
}) | the_stack |
import { createTail, Tail, TailMessage, TailOptions, setSubtract, ErrorInfo, TailConnection, TailConnectionCallbacks, UnparsedMessage } from './deps_app.ts';
export type TailKey = string; // accountId-scriptId
export interface TailControllerCallbacks {
onTailCreating(accountId: string, scriptId: string): void;
onTailCreated(accountId: string, scriptId: string, tookMillis: number, tail: Tail): void;
onTailConnectionOpen(accountId: string, scriptId: string, timeStamp: number, tookMillis: number): void;
onTailConnectionClose(accountId: string, scriptId: string, timeStamp: number, code: number, reason: string, wasClean: boolean): void;
onTailConnectionError(accountId: string, scriptId: string, timeStamp: number, errorInfo?: ErrorInfo): void;
onTailConnectionMessage(accountId: string, scriptId: string, timeStamp: number, message: TailMessage): void;
onTailConnectionUnparsedMessage(accountId: string, scriptId: string, timeStamp: number, message: UnparsedMessage, parseError: Error): void;
onTailsChanged(tailKeys: ReadonlySet<TailKey>): void;
onNetworkStatusChanged(online: boolean): void;
onTailFailedToStart(accountId: string, scriptId: string, trigger: string, error: Error): void;
}
export class TailController {
private readonly callbacks: TailControllerCallbacks;
private readonly records = new Map<TailKey, Record>();
private readonly websocketPingIntervalSeconds: number;
private readonly inactiveTailSeconds: number;
private tailOptions: TailOptions = { filters: [] };
private online?: boolean;
constructor(callbacks: TailControllerCallbacks, opts: { websocketPingIntervalSeconds: number, inactiveTailSeconds: number }) {
this.callbacks = callbacks;
this.websocketPingIntervalSeconds = opts.websocketPingIntervalSeconds;
this.inactiveTailSeconds = opts.inactiveTailSeconds;
// deno-lint-ignore no-explicit-any
const navigatorAsAny = window.navigator as any;
if (typeof navigatorAsAny.onLine === 'boolean') {
this.setOnline(navigatorAsAny.onLine);
}
window.addEventListener('online', () => this.setOnline(true));
window.addEventListener('offline', () => this.setOnline(false));
}
setTailOptions(tailOptions: TailOptions) {
console.log(`TailController.setTailOptions ${JSON.stringify(tailOptions)}`);
this.tailOptions = tailOptions;
for (const record of this.records.values()) {
if (record.connection) {
record.connection.setOptions(tailOptions);
}
}
}
async setTails(accountId: string, apiToken: string, scriptIds: ReadonlySet<string>) {
const stopKeys = setSubtract(this.computeStartingOrStartedTailKeys(), new Set([...scriptIds].map(v => packTailKey(accountId, v))));
for (const stopKey of stopKeys) {
const record = this.records.get(stopKey)!;
record.state = 'inactive';
record.stopRequestedTime = Date.now();
setTimeout(() => {
if (record.state === 'inactive' && record.stopRequestedTime && (Date.now() - record.stopRequestedTime) >= this.inactiveTailSeconds) {
record.state = 'stopping';
console.log(`Stopping ${record.scriptId}, inactive for ${Date.now() - record.stopRequestedTime}ms`);
record.connection?.close(1000 /* normal closure */, 'no longer interested');
this.records.delete(record.tailKey);
}
}, this.inactiveTailSeconds * 1000);
}
if (stopKeys.size > 0) {
this.dispatchTailsChanged();
}
for (const scriptId of scriptIds) {
const tailKey = packTailKey(accountId, scriptId);
const existingRecord = this.records.get(tailKey);
if (existingRecord) {
if (existingRecord.state === 'inactive') {
console.log(`Reviving inactive ${scriptId}`);
}
existingRecord.state = 'started';
existingRecord.stopRequestedTime = undefined;
} else {
const record: Record = { state: 'starting', tailKey, apiToken, accountId, scriptId, retryCountAfterClose: 0 };
this.records.set(tailKey, record);
await this.startTailConnection(record);
record.state = 'started';
}
this.dispatchTailsChanged();
}
}
//
private dispatchTailsChanged() {
const tailKeys = new Set([...this.records.values()].filter(v => v.state === 'started').map(v => v.tailKey));
this.callbacks.onTailsChanged(tailKeys);
}
private computeStartingOrStartedTailKeys(): Set<TailKey> {
return new Set([...this.records.values()].filter(v => v.state === 'starting' || v.state === 'started').map(v => v.tailKey))
}
private setOnline(online: boolean) {
if (online === this.online) return;
const oldOnline = this.online;
this.online = online;
this.callbacks.onNetworkStatusChanged(online);
if (typeof oldOnline === 'boolean') {
if (online) {
for (const record of this.records.values()) {
if (record.state === 'started') {
const { accountId, scriptId } = record;
this.startTailConnection(record)
.catch(e => this.callbacks.onTailFailedToStart(accountId, scriptId, 'restart-after-coming-online', e as Error));
}
}
} else {
for (const record of this.records.values()) {
record.connection?.close(1000 /* normal closure */, 'offline');
}
}
}
}
private async startTailConnection(record: Record) {
const allowedToStart = record.state === 'starting' || record.state === 'started';
if (!allowedToStart) return;
const { accountId, scriptId } = unpackTailKey(record.tailKey);
const { apiToken } = record;
if (!record.tail || Date.now() > new Date(record.tail.expires_at).getTime() - 1000 * 60 * 5) {
const tailCreatingTime = Date.now();
this.callbacks.onTailCreating(accountId, scriptId);
const tail = await createTail(accountId, scriptId, apiToken);
record.tail = tail;
this.callbacks.onTailCreated(accountId, scriptId, Date.now() - tailCreatingTime, tail);
}
// we might have been inactivated already, don't start the ws
if (record.state === 'inactive') return;
const { callbacks, websocketPingIntervalSeconds } = this;
// deno-lint-ignore no-this-alias
const dis = this;
const openingTime = Date.now();
const tailConnectionCallbacks: TailConnectionCallbacks = {
onOpen(_cn: TailConnection, timeStamp: number) {
record.retryCountAfterClose = 0;
callbacks.onTailConnectionOpen(accountId, scriptId, timeStamp, Date.now() - openingTime);
},
onClose(_cn: TailConnection, timeStamp: number, code: number, reason: string, wasClean: boolean) {
callbacks.onTailConnectionClose(accountId, scriptId, timeStamp, code, reason, wasClean);
record.closeTime = Date.now();
if (record.state === 'started' && dis.online !== false) {
// we didn't want to close, reschedule another TailConnection
record.retryCountAfterClose++;
const delaySeconds = Math.min(record.retryCountAfterClose * 5, 60);
console.log(`Will attempt to restart ${scriptId} in ${delaySeconds} seconds`);
setTimeout(async function() {
if (record.state === 'started') {
await dis.startTailConnection(record);
}
}, delaySeconds * 1000);
}
},
onError(_cn: TailConnection, timeStamp: number, errorInfo?: ErrorInfo) {
callbacks.onTailConnectionError(accountId, scriptId, timeStamp, errorInfo);
},
onTailMessage(_cn: TailConnection, timeStamp: number, message: TailMessage) {
if (record.state !== 'started') return;
callbacks.onTailConnectionMessage(accountId, scriptId, timeStamp, message);
},
onUnparsedMessage(_cn: TailConnection, timeStamp: number, message: UnparsedMessage, parseError: Error) {
console.log('onUnparsedMessage', timeStamp, message, parseError);
callbacks.onTailConnectionUnparsedMessage(accountId, scriptId, timeStamp, message, parseError);
},
};
record.connection = new TailConnection(record.tail!.url, tailConnectionCallbacks, { websocketPingIntervalSeconds }).setOptions(this.tailOptions);
}
}
export function unpackTailKey(tailKey: TailKey): { accountId: string, scriptId: string} {
const m = /^([^\s-]+)-([^\s]+)$/.exec(tailKey);
if (!m) throw new Error(`Bad tailKey: ${tailKey}`);
return { accountId: m[1], scriptId: m[2] };
}
export function packTailKey(accountId: string, scriptId: string) {
return `${accountId}-${scriptId}`;
}
//
interface Record {
readonly tailKey: TailKey;
readonly accountId: string;
readonly scriptId: string;
state: 'starting' | 'started' | 'inactive' | 'stopping';
apiToken: string;
retryCountAfterClose: number;
connection?: TailConnection;
stopRequestedTime?: number;
closeTime?: number;
tail?: Tail;
}
//
export class SwitchableTailControllerCallbacks implements TailControllerCallbacks {
private readonly callbacks: TailControllerCallbacks;
private readonly enabledFn: () => boolean;
constructor(callbacks: TailControllerCallbacks, enabledFn: () => boolean) {
this.callbacks = callbacks;
this.enabledFn = enabledFn;
}
onTailCreating(accountId: string, scriptId: string) {
if (!this.enabledFn()) return;
this.callbacks.onTailCreating(accountId, scriptId);
}
onTailCreated(accountId: string, scriptId: string, tookMillis: number, tail: Tail) {
if (!this.enabledFn()) return;
this.callbacks.onTailCreated(accountId, scriptId, tookMillis, tail);
}
onTailConnectionOpen(accountId: string, scriptId: string, timeStamp: number, tookMillis: number) {
if (!this.enabledFn()) return;
this.callbacks.onTailConnectionOpen(accountId, scriptId, timeStamp, tookMillis);
}
onTailConnectionClose(accountId: string, scriptId: string, timeStamp: number, code: number, reason: string, wasClean: boolean) {
if (!this.enabledFn()) return;
this.callbacks.onTailConnectionClose(accountId, scriptId, timeStamp, code, reason, wasClean);
}
onTailConnectionError(accountId: string, scriptId: string, timeStamp: number, errorInfo?: ErrorInfo) {
if (!this.enabledFn()) return;
this.callbacks.onTailConnectionError(accountId, scriptId, timeStamp, errorInfo);
}
onTailConnectionMessage(accountId: string, scriptId: string, timeStamp: number, message: TailMessage) {
if (!this.enabledFn()) return;
this.callbacks.onTailConnectionMessage(accountId, scriptId, timeStamp, message);
}
onTailConnectionUnparsedMessage(accountId: string, scriptId: string, timeStamp: number, message: UnparsedMessage, parseError: Error) {
if (!this.enabledFn()) return;
this.callbacks.onTailConnectionUnparsedMessage(accountId, scriptId, timeStamp, message, parseError);
}
onTailsChanged(tails: ReadonlySet<TailKey>) {
if (!this.enabledFn()) return;
this.callbacks.onTailsChanged(tails);
}
onNetworkStatusChanged(online: boolean) {
if (!this.enabledFn()) return;
this.callbacks.onNetworkStatusChanged(online);
}
onTailFailedToStart(accountId: string, scriptId: string, trigger: string, error: Error) {
if (!this.enabledFn()) return;
this.callbacks.onTailFailedToStart(accountId, scriptId, trigger, error);
}
} | the_stack |
import { Droppable, DropEventArgs } from '@syncfusion/ej2-base';
import { isNullOrUndefined, extend } from '@syncfusion/ej2-base';
import { setStyleAttribute, remove, updateBlazorTemplate } from '@syncfusion/ej2-base';
import { getUpdateUsingRaf, appendChildren, setDisplayValue, clearReactVueTemplates } from '../base/util';
import * as events from '../base/constant';
import { IRenderer, IGrid, NotifyArgs, IModelGenerator, RowDataBoundEventArgs, CellFocusArgs, InfiniteScrollArgs } from '../base/interface';
import { VirtualInfo } from '../base/interface';
import { Column } from '../models/column';
import { Row } from '../models/row';
import { Cell } from '../models/cell';
import { RowRenderer } from './row-renderer';
import { CellMergeRender } from './cell-merge-renderer';
import { ServiceLocator } from '../services/service-locator';
import { AriaService } from '../services/aria-service';
import { RowModelGenerator } from '../services/row-model-generator';
import { GroupModelGenerator } from '../services/group-model-generator';
import { isGroupAdaptive } from '../base/util';
import { Grid } from '../base/grid';
import { VirtualFreezeRenderer } from './virtual-freeze-renderer';
import { VirtualContentRenderer } from '../renderer/virtual-content-renderer';
import { GroupLazyLoadRenderer } from './group-lazy-load-renderer';
import { FreezeContentRender } from './freeze-renderer';
import { freezeTable } from '../base/enum';
import * as literals from '../base/string-literals';
// eslint-disable-next-line valid-jsdoc
/**
* Content module is used to render grid content
*
* @hidden
*/
export class ContentRender implements IRenderer {
//Internal variables
private contentTable: Element;
private contentPanel: Element;
protected rows: Row<Column>[] = [];
protected freezeRows: Row<Column>[] = [];
protected movableRows: Row<Column>[] = [];
protected rowElements: Element[];
protected freezeRowElements: Element[] = [];
private index: number;
/** @hidden */
public prevInfo: VirtualInfo;
/** @hidden */
public currentInfo: VirtualInfo = {};
/** @hidden */
public prevCurrentView: Object[] = [];
public colgroup: Element;
protected isLoaded: boolean = true;
protected tbody: HTMLElement;
private droppable: Droppable;
private viewColIndexes: number[] = [];
private drop: Function = (e: DropEventArgs) => {
this.parent.notify(events.columnDrop, { target: e.target, droppedElement: e.droppedElement });
remove(e.droppedElement);
}
private args: NotifyArgs;
private infiniteCache: { [x: number]: Row<Column>[] } | { [x: number]: Row<Column>[][] } = {};
private isRemove: boolean = false;
private pressedKey: string;
private visibleRows: Row<Column>[] = [];
private visibleFrozenRows: Row<Column>[] = [];
protected rightFreezeRows: Row<Column>[] = [];
private isAddRows: boolean = false;
private currentMovableRows: Object[];
private initialPageRecords: Object;
private isInfiniteFreeze: boolean = false;
private useGroupCache: boolean = false;
private rafCallback: Function = (args: NotifyArgs) => {
const arg: NotifyArgs = args;
return () => {
if (this.parent.isFrozenGrid() && this.parent.enableVirtualization) {
const tableName: freezeTable = (<{ tableName?: freezeTable }>args).tableName;
this.isLoaded = this.parent.getFrozenMode() === literals.leftRight ? tableName === 'frozen-right' : tableName === 'movable';
if (this.parent.enableColumnVirtualization && args.requestType === 'virtualscroll' && this.isLoaded) {
const mHdr: Element[] = [].slice.call(this.parent.getMovableVirtualHeader().getElementsByClassName(literals.row));
const fHdr: Element[] = [].slice.call(this.parent.getFrozenVirtualHeader().getElementsByClassName(literals.row));
this.isLoaded = mHdr.length === fHdr.length;
}
}
this.ariaService.setBusy(<HTMLElement>this.getPanel().querySelector('.' + literals.content), false);
if (this.parent.isDestroyed) { return; }
let rows: Row<Column>[] = this.rows.slice(0);
if (this.parent.enableInfiniteScrolling) {
rows = this.parent.getRowsObject(); const prevPage: number = (<{ prevPage: number }>arg).prevPage;
if (this.parent.infiniteScrollSettings.enableCache && prevPage) {
const maxBlock: number = this.parent.infiniteScrollSettings.maxBlocks; rows = [];
const rowIdx: number = (parseInt(this.rowElements[0].getAttribute('aria-rowindex'), 10) + 1);
const startIdx: number = Math.ceil(rowIdx / this.parent.pageSettings.pageSize);
for (let i: number = 0, count: number = startIdx; i < maxBlock; i++, count++) {
if (this.infiniteCache[count]) {
rows = [...rows, ...this.infiniteCache[count]] as Row<Column>[];
}
}
}
}
if (this.parent.isFrozenGrid()) {
rows = args.isFrozen ? this.freezeRows : args.renderFrozenRightContent ? this.parent.getFrozenRightRowsObject()
: this.movableRows;
}
this.parent.notify(events.contentReady, { rows: rows, args: arg });
if (this.isLoaded) {
this.parent.isManualRefresh = false;
this.parent.trigger(events.dataBound, {}, () => {
if (this.parent.allowTextWrap) {
this.parent.notify(events.freezeRender, { case: 'textwrap' });
}
});
}
if (arg) {
const action: string = (arg.requestType || '').toLowerCase() + '-complete';
this.parent.notify(action, arg);
if (args.requestType === 'batchsave') {
args.cancel = false;
this.parent.trigger(events.actionComplete, args);
}
}
if (this.isLoaded) {
this.parent.hideSpinner();
}
};
}
//Module declarations
protected parent: IGrid;
private serviceLocator: ServiceLocator;
private ariaService: AriaService;
protected generator: IModelGenerator<Column>;
/**
* Constructor for content renderer module
*
* @param {IGrid} parent - specifies the Igrid
* @param {ServiceLocator} serviceLocator - specifies the service locator
*/
constructor(parent?: IGrid, serviceLocator?: ServiceLocator) {
this.parent = parent;
this.serviceLocator = serviceLocator;
this.ariaService = this.serviceLocator.getService<AriaService>('ariaService');
this.parent.enableDeepCompare = this.parent.getDataModule().isRemote();
this.generator = this.getModelGenerator();
if (this.parent.isDestroyed) { return; }
if (!this.parent.enableColumnVirtualization && !this.parent.enableVirtualization
&& !this.parent.groupSettings.enableLazyLoading) {
this.parent.on(events.columnVisibilityChanged, this.setVisible, this);
}
this.parent.on(events.colGroupRefresh, this.colGroupRefresh, this);
this.parent.on(events.uiUpdate, this.enableAfterRender, this);
this.parent.on(events.refreshInfiniteModeBlocks, this.refreshContentRows, this);
this.parent.on(events.beforeCellFocused, this.beforeCellFocused, this);
this.parent.on(events.destroy, this.droppableDestroy, this);
}
private beforeCellFocused(e: CellFocusArgs): void {
if (e.byKey && (e.keyArgs.action === 'upArrow' || e.keyArgs.action === 'downArrow')) {
this.pressedKey = e.keyArgs.action;
} else {
this.pressedKey = undefined;
}
}
/**
* The function is used to render grid content div
*
* @returns {void}
*/
public renderPanel(): void {
const gObj: IGrid = this.parent;
let div: Element = this.parent.element.querySelector( '.' + literals.gridContent);
if (div) {
this.ariaService.setOptions(<HTMLElement>this.parent.element.querySelector('.' + literals.content), { busy: false });
this.setPanel(div);
return;
}
div = this.parent.createElement('div', { className: literals.gridContent });
const innerDiv: Element = this.parent.createElement('div', {
className: literals.content
});
this.ariaService.setOptions(<HTMLElement>innerDiv, { busy: false });
div.appendChild(innerDiv);
this.setPanel(div);
gObj.element.appendChild(div);
}
/**
* The function is used to render grid content table
*
* @returns {void}
*/
public renderTable(): void {
const contentDiv: Element = this.getPanel();
const virtualTable: Element = contentDiv.querySelector('.e-virtualtable');
const virtualTrack: Element = contentDiv.querySelector('.e-virtualtrack');
if (this.parent.enableVirtualization && !isNullOrUndefined(virtualTable) && !isNullOrUndefined(virtualTrack)) {
remove(virtualTable);
remove(virtualTrack);
}
contentDiv.appendChild(this.createContentTable('_content_table'));
this.setTable(contentDiv.querySelector('.' + literals.table));
this.ariaService.setOptions(<HTMLElement>this.getTable(), {
multiselectable: this.parent.selectionSettings.type === 'Multiple'
});
this.initializeContentDrop();
if (this.parent.frozenRows) {
this.parent.getHeaderContent().classList.add('e-frozenhdrcont');
}
}
/**
* The function is used to create content table elements
*
* @param {string} id - specifies the id
* @returns {Element} returns the element
* @hidden
*/
public createContentTable(id: string): Element {
const innerDiv: Element = <Element>this.getPanel().firstElementChild;
if (this.getTable()) {
remove(this.getTable());
}
const table: Element = innerDiv.querySelector('.' + literals.table) ? innerDiv.querySelector('.' + literals.table) :
this.parent.createElement('table', {
className: literals.table, attrs: {
cellspacing: '0.25px', role: 'grid',
id: this.parent.element.id + id
}
});
this.setColGroup(<Element>this.parent.getHeaderTable().querySelector(literals.colGroup).cloneNode(true));
table.appendChild(this.getColGroup());
table.appendChild(this.parent.createElement( literals.tbody));
innerDiv.appendChild(table);
return innerDiv;
}
/**
* Refresh the content of the Grid.
*
* @param {NotifyArgs} args - specifies the args
* @returns {void}
*/
// tslint:disable-next-line:max-func-body-length
public refreshContentRows(args: NotifyArgs = {}): void {
const gObj: IGrid = this.parent;
if (gObj.currentViewData.length === 0) { return; }
const dataSource: Object = this.currentMovableRows || gObj.currentViewData;
const contentModule: FreezeContentRender = (this.parent.contentModule as FreezeContentRender);
const isReact: boolean = gObj.isReact && !isNullOrUndefined(gObj.rowTemplate);
let frag: DocumentFragment | HTMLElement = isReact ? gObj.createElement( literals.tbody) : document.createDocumentFragment();
if (!this.initialPageRecords) {
this.initialPageRecords = extend([], dataSource);
}
const hdrfrag: DocumentFragment = isReact ? gObj.createElement( literals.tbody) : document.createDocumentFragment();
const columns: Column[] = <Column[]>gObj.getColumns();
let tr: Element; let hdrTbody: HTMLElement; const frzCols: number = gObj.getFrozenColumns();
const isFrozenGrid: boolean = this.parent.isFrozenGrid();
let trElement: Element;
const row: RowRenderer<Column> = new RowRenderer<Column>(this.serviceLocator, null, this.parent);
const isInfiniteScroll: boolean = this.parent.enableInfiniteScrolling
&& (args as InfiniteScrollArgs).requestType === 'infiniteScroll';
gObj.notify(events.destroyChildGrid, {});
this.rowElements = [];
this.rows = [];
const fCont: Element = this.getPanel().querySelector('.' + literals.frozenContent);
const mCont: HTMLElement = this.getPanel().querySelector('.' + literals.movableContent) as HTMLElement;
const cont: HTMLElement = this.getPanel().querySelector('.' + literals.content) as HTMLElement;
let tbdy: Element;
let tableName: freezeTable;
if (isGroupAdaptive(gObj)) {
if (['sorting', 'filtering', 'searching', 'grouping', 'ungrouping', 'reorder']
.some((value: string) => { return args.requestType === value; })) {
this.emptyVcRows();
}
}
let modelData: Row<Column>[];
if (this.parent.enableVirtualization && this.parent.isFrozenGrid()) {
if (this.parent.enableColumnVirtualization && args.requestType === 'virtualscroll'
&& args.virtualInfo.sentinelInfo.axis === 'X') {
modelData = (<{ generateRows?: Function }>(<Grid>this.parent).contentModule).generateRows(dataSource, args);
args.renderMovableContent = true;
}
modelData = (<{ generateRows?: Function }>(<Grid>this.parent).contentModule).generateRows(dataSource as Object[], args);
} else {
modelData = this.checkCache(modelData, args);
if (!this.isAddRows && !this.useGroupCache) {
modelData = this.generator.generateRows(dataSource, args);
}
}
this.setGroupCache(modelData, args);
this.parent.notify(events.setInfiniteCache, { isInfiniteScroll: isInfiniteScroll, modelData: modelData, args: args });
const idx: number = modelData[0].cells[0].index;
if (isFrozenGrid) {
tableName = contentModule.setTbody(modelData, args);
tbdy = contentModule.getTbody(tableName);
}
const isFrozenLeft: boolean = this.parent.getFrozenMode() === literals.leftRight && tableName === literals.frozenRight;
/* eslint-disable */
if (args.requestType !== 'infiniteScroll' && (this.parent as any).registeredTemplate
&& (this.parent as any).registeredTemplate.template && !args.isFrozen && !isFrozenLeft) {
const templatetoclear: any = [];
for (let i: number = 0; i < (this.parent as any).registeredTemplate.template.length; i++) {
for (let j: number = 0; j < (this.parent as any).registeredTemplate.template[i].rootNodes.length; j++) {
if (isNullOrUndefined((this.parent as any).registeredTemplate.template[i].rootNodes[j].parentNode)) {
templatetoclear.push((this.parent as any).registeredTemplate.template[i]);
/* eslint-enable */
}
}
}
this.parent.destroyTemplate(['template'], templatetoclear);
}
if ((this.parent.isReact || this.parent.isVue) && args.requestType !== 'infiniteScroll' && !args.isFrozen) {
const templates: string[] = [
this.parent.isVue ? 'template' : 'columnTemplate', 'rowTemplate', 'detailTemplate',
'captionTemplate', 'commandsTemplate', 'groupFooterTemplate', 'groupCaptionTemplate'
];
clearReactVueTemplates(this.parent, templates);
}
if (this.parent.enableColumnVirtualization) {
const cellMerge: CellMergeRender<Column> = new CellMergeRender(this.serviceLocator, this.parent);
cellMerge.updateVirtualCells(modelData);
}
if (!isFrozenGrid) {
this.tbody = this.getTable().querySelector( literals.tbody);
}
let startIndex: number = 0;
let blockLoad: boolean = true;
if (isGroupAdaptive(gObj) && gObj.vcRows.length) {
const top: string = 'top';
const scrollTop: number = !isNullOrUndefined(args.virtualInfo.offsets) ? args.virtualInfo.offsets.top :
(!isNullOrUndefined(args.scrollTop) ? args.scrollTop[top] : 0);
if (scrollTop !== 0) {
const offsets: { [x: number]: number } = gObj.vGroupOffsets;
const bSize: number = gObj.pageSettings.pageSize / 2;
const values: number[] = Object.keys(offsets).map((key: string) => offsets[key]);
for (let m: number = 0; m < values.length; m++) {
if (scrollTop < values[m]) {
if (!isNullOrUndefined(args.virtualInfo) && args.virtualInfo.direction === 'up') {
startIndex = m > 0 ? ((m - 1) * bSize) : (m * bSize);
break;
} else {
startIndex = m * bSize;
if (this.parent.contentModule.isEndBlock(m) || this.parent.contentModule.isEndBlock(m + 1)) {
args.virtualInfo.blockIndexes = [m, m + 1];
}
break;
}
}
}
if (Math.round(scrollTop + (this.contentPanel.firstElementChild as HTMLElement).offsetHeight) >=
this.contentPanel.firstElementChild.scrollHeight && !args.rowObject) {
blockLoad = false;
}
}
}
const isVFFrozenOnly: boolean = gObj.frozenRows && !gObj.isFrozenGrid() && this.parent.enableVirtualization
&& args.requestType === 'reorder';
if ((gObj.frozenRows && args.requestType === 'virtualscroll' && args.virtualInfo.sentinelInfo.axis === 'X') || isVFFrozenOnly) {
const bIndex: number[] = args.virtualInfo.blockIndexes;
const page: number = args.virtualInfo.page;
args.virtualInfo.blockIndexes = [1, 2];
if (isVFFrozenOnly) {
args.virtualInfo.page = 1;
}
const data: Object = isVFFrozenOnly ? this.initialPageRecords : dataSource;
const mhdrData: Row<Column>[] = (<{ generateRows?: Function }>(<{ vgenerator?: Function }>this).vgenerator)
.generateRows(data, args);
mhdrData.splice(this.parent.frozenRows);
for (let i: number = 0; i < this.parent.frozenRows; i++) {
mhdrData[i].cells.splice(0, this.parent.getFrozenColumns());
tr = row.render(mhdrData[i], columns);
hdrfrag.appendChild(tr);
}
args.virtualInfo.blockIndexes = bIndex;
args.virtualInfo.page = page;
if (isVFFrozenOnly && args.virtualInfo.page === 1) {
modelData.splice(0, this.parent.frozenRows);
}
}
this.virtualFrozenHdrRefresh(hdrfrag, modelData, row, args, dataSource, columns);
for (let i: number = startIndex, len: number = modelData.length; i < len; i++) {
this.rows.push(modelData[i]);
if (this.parent.groupSettings.enableLazyLoading && !this.useGroupCache && this.parent.groupSettings.columns.length) {
this.setRowsInLazyGroup(modelData[i], i);
if (isNullOrUndefined(modelData[i].indent)) {
continue;
}
}
this.setInfiniteVisibleRows(args, modelData[i], tableName);
if (isGroupAdaptive(gObj) && args.virtualInfo && args.virtualInfo.blockIndexes
&& (this.rowElements.length >= (args.virtualInfo.blockIndexes.length * this.parent.contentModule.getBlockSize()))
&& blockLoad) {
this.parent.currentViewData['records'] = this.rows.map((m: Row<Column>) => m.data);
break;
}
if (!gObj.rowTemplate) {
tr = row.render(modelData[i], columns);
const isVFreorder: boolean = this.ensureFrozenHeaderRender(args);
if (gObj.frozenRows && i < gObj.frozenRows && !isInfiniteScroll && args.requestType !== 'virtualscroll' && isVFreorder
&& this.ensureVirtualFrozenHeaderRender(args)) {
hdrfrag.appendChild(tr);
} else {
frag.appendChild(tr);
}
if (modelData[i].isExpand) {
gObj.notify(events.expandChildGrid, (<HTMLTableRowElement>tr).cells[gObj.groupSettings.columns.length]);
}
} else {
const rowTemplateID: string = gObj.element.id + 'rowTemplate';
let elements: NodeList;
if (gObj.isReact) {
const isHeader: boolean = gObj.frozenRows && i < gObj.frozenRows;
const copied: Object = extend({ index: i }, dataSource[i]);
gObj.getRowTemplate()(copied, gObj, 'rowTemplate', rowTemplateID, null, null, isHeader ? hdrfrag : frag);
gObj.renderTemplates();
} else {
elements = gObj.getRowTemplate()(extend({ index: i }, dataSource[i]), gObj, 'rowTemplate', rowTemplateID);
}
if (!gObj.isReact && (elements[0] as Element).tagName === 'TBODY') {
for (let j: number = 0; j < elements.length; j++) {
const isTR: boolean = elements[j].nodeName.toLowerCase() === 'tr';
if (isTR || ((elements[j] as Element).querySelectorAll && (elements[j] as Element).querySelectorAll('tr').length)) {
tr = isTR ? elements[j] as Element : (elements[j] as Element).querySelector('tr');
}
}
if (gObj.frozenRows && i < gObj.frozenRows) {
hdrfrag.appendChild(tr);
} else {
frag.appendChild(tr);
}
} else {
if (gObj.frozenRows && i < gObj.frozenRows) {
tr = !gObj.isReact ? appendChildren(hdrfrag, elements) : hdrfrag.lastElementChild;
} else {
// frag.appendChild(tr);
if (!gObj.isReact) {
tr = appendChildren(frag, elements);
}
trElement = gObj.isReact ? frag.lastElementChild : tr.lastElementChild;
}
}
const arg: RowDataBoundEventArgs = { data: modelData[i].data, row: trElement ? trElement : tr };
this.parent.trigger(events.rowDataBound, arg);
}
if (modelData[i].isDataRow) {
this.rowElements.push(tr);
}
this.ariaService.setOptions(this.getTable() as HTMLElement, { colcount: gObj.getColumns().length.toString() });
}
if (isFrozenGrid) {
contentModule.splitRows(tableName);
}
if ((gObj.frozenRows && args.requestType !== 'virtualscroll' && !isInfiniteScroll && this.ensureVirtualFrozenHeaderRender(args))
|| (args.requestType === 'virtualscroll' && args.virtualInfo.sentinelInfo && args.virtualInfo.sentinelInfo.axis === 'X')) {
hdrTbody = isFrozenGrid ? contentModule.getFrozenHeader(tableName) : gObj.getHeaderTable().querySelector( literals.tbody);
if (isReact) {
const parentTable: HTMLElement = hdrTbody.parentElement;
remove(hdrTbody);
parentTable.appendChild(hdrfrag);
} else {
hdrTbody.innerHTML = '';
hdrTbody.appendChild(hdrfrag);
}
}
if (!gObj.enableVirtualization && gObj.frozenRows && idx === 0 && cont.offsetHeight === Number(gObj.height)) {
cont.style.height = (cont.offsetHeight - hdrTbody.offsetHeight) + 'px';
}
args.rows = this.rows.slice(0);
if (isFrozenGrid) {
contentModule.setIsFrozen(args, tableName);
}
this.index = idx;
getUpdateUsingRaf<HTMLElement>(
() => {
this.parent.notify(events.beforeFragAppend, args);
const isVFTable: boolean = this.parent.enableVirtualization && this.parent.isFrozenGrid();
if (!this.parent.enableVirtualization && !isInfiniteScroll) {
if (this.parent.isFrozenGrid()) {
remove(contentModule.getTbody(tableName));
tbdy = this.parent.createElement( literals.tbody);
} else {
this.tbody.innerHTML = '';
remove(this.tbody);
this.tbody = this.parent.createElement( literals.tbody);
}
}
if (isFrozenGrid && !isVFTable && !this.parent.enableInfiniteScrolling) {
this.appendContent(tbdy, frag as DocumentFragment, args, tableName);
} else {
if (gObj.rowTemplate) {
updateBlazorTemplate(gObj.element.id + 'rowTemplate', 'RowTemplate', gObj);
}
if (isVFTable) {
if (args.renderFrozenRightContent) {
const frCont: Element = gObj.getContent().querySelector('.e-frozen-right-content').querySelector( literals.tbody);
this.appendContent(frCont, frag as DocumentFragment, args);
} else if (!args.renderMovableContent) {
this.appendContent(fCont.querySelector( literals.tbody), frag as DocumentFragment, args);
} else {
this.appendContent(mCont.querySelector( literals.tbody), frag as DocumentFragment, args);
args.renderMovableContent = false;
}
if (!this.parent.getFrozenColumns()) {
contentModule.renderNextFrozentPart(args, tableName);
}
} else {
if (!isNullOrUndefined(this.parent.infiniteScrollModule) && this.parent.enableInfiniteScrolling) {
this.isAddRows = false;
this.parent.notify(events.removeInfiniteRows, { args: args });
this.parent.notify(events.appendInfiniteContent, {
tbody: tbdy ? tbdy : this.tbody, frag: frag, args: args, rows: this.rows,
rowElements: this.rowElements, visibleRows: this.visibleRows,
tableName: tableName
});
if (!frzCols && isFrozenGrid) {
if ((gObj.getFrozenMode() !== literals.leftRight
&& (tableName === literals.frozenLeft || tableName === literals.frozenRight))
|| (gObj.getFrozenMode() === literals.leftRight
&& (tableName === literals.frozenLeft || tableName === 'movable'))) {
this.refreshContentRows(extend({}, args));
}
}
} else {
this.useGroupCache = false;
this.appendContent(this.tbody, frag as DocumentFragment, args);
}
}
}
if (frzCols) {
contentModule.renderNextFrozentPart(args, tableName);
}
frag = null;
},
this.rafCallback(extend({}, args)));
}
public emptyVcRows(): void {
this.parent.vcRows = [];
this.parent.vRows = [];
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public appendContent(tbody: Element, frag: DocumentFragment, args: NotifyArgs, tableName?: string): void {
const isReact: boolean = this.parent.isReact && !isNullOrUndefined(this.parent.rowTemplate);
if (isReact) {
this.getTable().appendChild(frag);
} else {
tbody.appendChild(frag);
this.getTable().appendChild(tbody);
}
}
private setRowsInLazyGroup(row: Row<Column>, index: number): void {
if (this.parent.groupSettings.enableLazyLoading && !this.useGroupCache && this.parent.groupSettings.columns.length) {
(this.parent.contentModule as GroupLazyLoadRenderer).maintainRows(row, index);
}
}
private setGroupCache(data: Row<Column>[], args: NotifyArgs): void {
if (!this.useGroupCache && this.parent.groupSettings.enableLazyLoading) {
this.parent.notify(events.setGroupCache, { args: args, data: data });
}
}
private ensureFrozenHeaderRender(args: NotifyArgs): boolean {
return !((this.parent.enableVirtualization
&& (args.requestType === 'reorder' || args.requestType === 'refresh')) || (this.parent.infiniteScrollSettings.enableCache
&& this.parent.frozenRows && this.parent.infiniteScrollModule.requestType === 'delete'
&& this.parent.pageSettings.currentPage !== 1));
}
private ensureVirtualFrozenHeaderRender(args: NotifyArgs): boolean {
return !(this.parent.enableVirtualization && args.requestType === 'delete');
}
private checkCache(modelData: Row<Column>[], args: InfiniteScrollArgs): Row<Column>[] {
if (this.parent.infiniteScrollSettings.enableCache && args.requestType === 'infiniteScroll') {
const index: number = args.isFrozen ? 1 : 0;
const frozenCols: boolean = this.parent.isFrozenGrid();
this.isAddRows = !isNullOrUndefined(this.infiniteCache[this.parent.pageSettings.currentPage]);
if (frozenCols && !isNullOrUndefined(this.infiniteCache[this.parent.pageSettings.currentPage])) {
this.isAddRows = (this.infiniteCache[this.parent.pageSettings.currentPage][index] as Row<Column>[]).length !== 0;
}
if (this.isAddRows) {
const data: Row<Column>[] = !frozenCols ? this.infiniteCache[this.parent.pageSettings.currentPage] as Row<Column>[]
: this.infiniteCache[this.parent.pageSettings.currentPage][index] as Row<Column>[];
modelData = this.parent.pageSettings.currentPage === 1 ? data.slice(this.parent.frozenRows) : data;
}
return modelData;
}
if (this.parent.groupSettings.enableLazyLoading && this.parent.groupSettings.columns.length &&
(args.requestType === 'paging' || args.requestType === 'columnstate' || args.requestType === 'reorder')
&& (this.parent.contentModule as GroupLazyLoadRenderer).getGroupCache()[this.parent.pageSettings.currentPage]) {
this.useGroupCache = true;
return (this.parent.contentModule as GroupLazyLoadRenderer).initialGroupRows(args.requestType === 'reorder');
}
return null;
}
private setInfiniteVisibleRows(args: InfiniteScrollArgs, data: Row<Column>, tableName: freezeTable): void {
const frozenCols: boolean = this.parent.isFrozenGrid();
if (this.parent.enableInfiniteScrolling && !this.parent.infiniteScrollSettings.enableCache) {
if (frozenCols) {
if (tableName === literals.frozenLeft || (this.parent.getFrozenMode() === 'Right' && tableName === literals.frozenRight)) {
this.visibleFrozenRows.push(data);
} else if (tableName === 'movable') {
this.visibleRows.push(data);
} else {
this.rightFreezeRows.push(data);
}
} else if (!this.parent.infiniteScrollSettings.enableCache) {
this.visibleRows.push(data);
}
}
}
private getCurrentBlockInfiniteRecords(isFreeze?: boolean): Row<Column>[] {
let data: Row<Column>[] = [];
if (this.parent.infiniteScrollSettings.enableCache) {
if (!Object.keys(this.infiniteCache).length) {
return [];
}
const frozenCols: boolean = this.parent.isFrozenGrid();
const rows: Element[] = this.parent.getRows();
let index: number = parseInt(rows[this.parent.frozenRows].getAttribute(literals.ariaRowIndex), 10);
const first: number = Math.ceil((index + 1) / this.parent.pageSettings.pageSize);
index = parseInt(rows[rows.length - 1].getAttribute(literals.ariaRowIndex), 10);
const last: number = Math.ceil(index / this.parent.pageSettings.pageSize);
if (frozenCols) {
const idx: number = isFreeze ? 0 : 1;
for (let i: number = first; i <= last; i++) {
data = !data.length ? this.infiniteCache[i][idx] as Row<Column>[]
: data.concat(this.infiniteCache[i][idx] as Row<Column>[]);
}
if (this.parent.frozenRows && this.parent.pageSettings.currentPage > 1) {
data = ((this.infiniteCache[1][idx] as Row<Column>[]).slice(0, this.parent.frozenRows) as Row<Column>[]).concat(data);
}
} else {
for (let i: number = first; i <= last; i++) {
data = !data.length ? this.infiniteCache[i] as Row<Column>[] : data.concat(this.infiniteCache[i] as Row<Column>[]);
}
if (this.parent.frozenRows && this.parent.pageSettings.currentPage > 1) {
data = (this.infiniteCache[1].slice(0, this.parent.frozenRows) as Row<Column>[]).concat(data);
}
}
}
return data;
}
private getReorderedVFRows(args: NotifyArgs): Row<Column>[] {
return (this.parent.contentModule as VirtualFreezeRenderer).getReorderedFrozenRows(args);
}
private getReorderedRows(args: NotifyArgs): Row<Column>[] {
return (this.parent.contentModule as VirtualContentRenderer).getReorderedFrozenRows(args);
}
private virtualFrozenHdrRefresh(
hdrfrag: DocumentFragment, modelData: Row<Column>[],
row: RowRenderer<Column>, args: NotifyArgs, dataSource: Object, columns: Column[]
): void {
if (this.parent.frozenRows && this.parent.enableVirtualization
&& (args.requestType === 'reorder' || args.requestType === 'refresh')) {
let tr: Element;
let fhdrData: Row<Column>[] = [];
if (this.parent.isFrozenGrid()) {
this.currentMovableRows = dataSource as Object[];
fhdrData = this.getReorderedVFRows(args);
} else {
fhdrData = this.getReorderedRows(args);
}
for (let i: number = 0; i < fhdrData.length; i++) {
tr = row.render(fhdrData[i], columns);
hdrfrag.appendChild(tr);
}
if (args.virtualInfo.page === 1) {
modelData.splice(0, this.parent.frozenRows);
}
if (args.renderMovableContent) {
this.parent.currentViewData = this.currentMovableRows;
this.currentMovableRows = null;
}
}
}
protected getInfiniteRows(): Row<Column>[] {
let rows: Row<Column>[] = [];
const frozenCols: boolean = this.parent.isFrozenGrid();
if (this.parent.enableInfiniteScrolling) {
if (this.parent.infiniteScrollSettings.enableCache) {
const keys: string[] = Object.keys(this.infiniteCache);
for (let i: number = 0; i < keys.length; i++) {
rows = !frozenCols ? [...rows, ...this.infiniteCache[keys[i]]] : [...rows, ...this.infiniteCache[keys[i]][0]];
}
} else {
rows = frozenCols ? this.visibleFrozenRows : this.visibleRows;
}
}
return rows;
}
private getInfiniteMovableRows(): Row<Column>[] {
const infiniteCacheRows: Row<Column>[] = this.getCurrentBlockInfiniteRecords();
const infiniteRows: Row<Column>[] = this.parent.enableInfiniteScrolling ? infiniteCacheRows.length ? infiniteCacheRows
: this.visibleRows : [];
return infiniteRows;
}
/**
* Get the content div element of grid
*
* @returns {Element} returns the element
*/
public getPanel(): Element {
return this.contentPanel;
}
/**
* Set the content div element of grid
*
* @param {Element} panel - specifies the panel
* @returns {void}
*/
public setPanel(panel: Element): void {
this.contentPanel = panel;
}
/**
* Get the content table element of grid
*
* @returns {Element} returns the element
*/
public getTable(): Element {
return this.contentTable;
}
/**
* Set the content table element of grid
*
* @param {Element} table - specifies the table
* @returns {void}
*/
public setTable(table: Element): void {
this.contentTable = table;
}
/**
* Get the Movable Row collection in the Freeze pane Grid.
*
* @returns {Row[] | HTMLCollectionOf<HTMLTableRowElement>} returns the row
*/
public getRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> {
const infiniteRows: Row<Column>[] = this.getInfiniteRows();
return infiniteRows.length ? infiniteRows : this.parent.getFrozenColumns() ? this.freezeRows : this.rows;
}
/**
* Get the Movable Row collection in the Freeze pane Grid.
*
* @returns {Row[] | HTMLCollectionOf<HTMLTableRowElement>} returns the row
*/
public getMovableRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> {
const infiniteRows: Row<Column>[] = this.getInfiniteMovableRows();
return infiniteRows.length ? infiniteRows : this.movableRows;
}
/**
* Get the content table data row elements
*
* @returns {Element} returns the element
*/
public getRowElements(): Element[] {
return this.parent.getFrozenColumns() ? this.freezeRowElements : this.rowElements;
}
/**
* Get the Freeze pane movable content table data row elements
*
* @returns {Element} returns the element
*/
public getMovableRowElements(): Element[] {
return this.rowElements;
}
/**
* Get the content table data row elements
*
* @param {Element[]} elements - specifies the elements
* @returns {void}
*/
public setRowElements(elements: Element[]): void {
this.rowElements = elements;
}
/**
* Get the header colgroup element
*
* @returns {Element} returns the element
*/
public getColGroup(): Element {
return this.colgroup;
}
/**
* Set the header colgroup element
*
* @param {Element} colGroup - specifies the colgroup
* @returns {Element} returns the element
*/
public setColGroup(colGroup: Element): Element {
if (!isNullOrUndefined(colGroup)) {
colGroup.id = 'content-' + colGroup.id;
}
return this.colgroup = colGroup;
}
/**
* Function to hide content table column based on visible property
*
* @param {Column[]} columns - specifies the column
* @returns {void}
*/
public setVisible(columns?: Column[]): void {
const gObj: IGrid = this.parent;
const isFrozenGrid: boolean = this.parent.isFrozenGrid();
const frzCols: number = gObj.getFrozenColumns();
let rows: Row<Column>[] = [];
if (isFrozenGrid) {
const fRows: Row<Column>[] = this.freezeRows;
const mRows: Row<Column>[] = this.movableRows;
const rowLen: number = fRows.length;
let cellLen: number;
let rightRows: Row<Column>[] = [];
if (gObj.getFrozenMode() === literals.leftRight) {
rightRows = gObj.getFrozenRightRowsObject();
}
for (let i: number = 0, row: Row<Column>; i < rowLen; i++) {
cellLen = mRows[i].cells.length;
const rightLen: number = rightRows.length ? rightRows[i].cells.length : 0;
row = fRows[i].clone();
for (let j: number = 0; j < cellLen; j++) {
row.cells.push(mRows[i].cells[j]);
}
for (let k: number = 0; k < rightLen; k++) {
row.cells.push(rightRows[i].cells[k]);
}
rows.push(row);
}
} else {
rows = <Row<Column>[]>this.getRows();
}
let testRow: Row<Column>;
rows.some((r: Row<Column>) => { if (r.isDataRow) { testRow = r; } return r.isDataRow; });
let needFullRefresh: boolean = true;
if (!gObj.groupSettings.columns.length && testRow) {
needFullRefresh = false;
}
let tr: Object = gObj.getDataRows();
const args: NotifyArgs = {};
const infiniteData: Row<Column>[] = this.infiniteRowVisibility();
let contentrows: Row<Column>[] = infiniteData ? infiniteData
: this.rows.filter((row: Row<Column>) => !row.isDetailRow);
for (let c: number = 0, clen: number = columns.length; c < clen; c++) {
const column: Column = columns[c];
let idx: number = this.parent.getNormalizedColumnIndex(column.uid);
let colIdx: number = this.parent.getColumnIndexByUid(column.uid);
const displayVal: string = column.visible === true ? '' : 'none';
if (idx !== -1 && testRow && idx < testRow.cells.length) {
if (isFrozenGrid) {
if (column.getFreezeTableName() !== 'movable') {
if (column.getFreezeTableName() === literals.frozenRight) {
const left: number = this.parent.getFrozenLeftColumnsCount();
const movable: number = this.parent.getMovableColumnsCount();
colIdx = idx = idx - (left + movable);
const colG: Element = this.parent.getContent().querySelector('.e-frozen-right-content').querySelector(literals.colGroup);
setStyleAttribute(<HTMLElement>colG.childNodes[idx], { 'display': displayVal });
contentrows = gObj.getFrozenRightRowsObject();
tr = gObj.getFrozenRightDataRows();
} else {
setStyleAttribute(<HTMLElement>this.getColGroup().childNodes[idx], { 'display': displayVal });
const infiniteFreezeData: Row<Column>[] = this.infiniteRowVisibility(true);
contentrows = infiniteFreezeData ? infiniteFreezeData : this.freezeRows;
tr = gObj.getDataRows();
}
} else {
const mTable: Element = gObj.getContent().querySelector('.' + literals.movableContent).querySelector(literals.colGroup);
colIdx = idx = idx - frzCols - this.parent.getFrozenLeftColumnsCount();
setStyleAttribute(<HTMLElement>mTable.childNodes[idx], { 'display': displayVal });
tr = (<Grid>gObj).getMovableDataRows();
const infiniteMovableData: Row<Column>[] = this.infiniteRowVisibility();
contentrows = infiniteMovableData ? infiniteMovableData : this.movableRows;
}
} else {
setStyleAttribute(<HTMLElement>this.getColGroup().childNodes[idx], { 'display': displayVal });
}
}
if (!needFullRefresh) {
this.setDisplayNone(tr, colIdx, displayVal, contentrows);
}
if (!this.parent.invokedFromMedia && column.hideAtMedia) {
this.parent.updateMediaColumns(column);
}
this.parent.invokedFromMedia = false;
}
if (needFullRefresh) {
this.refreshContentRows({ requestType: 'refresh' });
} else {
if (!this.parent.getFrozenColumns()) {
this.parent.notify(events.partialRefresh, { rows: contentrows, args: args });
} else {
this.parent.notify(events.partialRefresh, { rows: this.freezeRows, args: { isFrozen: true, rows: this.freezeRows } });
this.parent.notify(events.partialRefresh, { rows: this.movableRows, args: { isFrozen: false, rows: this.movableRows } });
}
}
}
/**
* @param {Object} tr - specifies the trr
* @param {number} idx - specifies the idx
* @param {string} displayVal - specifies the displayval
* @param {Row<Column>} rows - specifies the rows
* @returns {void}
* @hidden
*/
public setDisplayNone(tr: Object, idx: number, displayVal: string, rows: Row<Column>[]): void {
setDisplayValue(tr, idx, displayVal, rows, this.parent, this.parent.isRowDragable());
this.parent.notify(events.infiniteShowHide, { visible: displayVal, index: idx, isFreeze: this.isInfiniteFreeze });
}
private infiniteRowVisibility(isFreeze?: boolean): Row<Column>[] {
let infiniteData: Row<Column>[];
if (this.parent.enableInfiniteScrolling) {
this.isInfiniteFreeze = isFreeze;
if (this.parent.infiniteScrollSettings.enableCache) {
infiniteData = isFreeze ? this.getCurrentBlockInfiniteRecords(true) : this.getCurrentBlockInfiniteRecords();
} else {
infiniteData = isFreeze ? this.visibleFrozenRows : this.visibleRows;
}
}
return infiniteData;
}
private colGroupRefresh(): void {
if (this.getColGroup()) {
let colGroup: Element;
if (this.parent.enableColumnVirtualization && this.parent.getFrozenColumns()
&& (<{ isXaxis?: Function }>this.parent.contentModule).isXaxis()) {
colGroup = <Element>this.parent.getMovableVirtualHeader().querySelector(literals.colGroup).cloneNode(true);
} else {
colGroup = this.getHeaderColGroup();
}
this.getTable().replaceChild(colGroup, this.getColGroup());
this.setColGroup(colGroup);
}
}
protected getHeaderColGroup(): Element {
return <Element>this.parent.element.querySelector('.' + literals.gridHeader).querySelector(literals.colGroup).cloneNode(true);
}
private initializeContentDrop(): void {
const gObj: IGrid = this.parent;
this.droppable = new Droppable(gObj.element as HTMLElement, {
accept: '.e-dragclone',
drop: this.drop as (e: DropEventArgs) => void
});
}
private droppableDestroy(): void {
if (this.droppable && !this.droppable.isDestroyed) {
this.droppable.destroy();
}
}
private canSkip(column: Column, row: Row<Column>, index: number): boolean {
/**
* Skip the toggle visiblity operation when one of the following success
* 1. Grid has empty records
* 2. column visible property is unchanged
* 3. cell`s isVisible property is same as column`s visible property.
*/
return isNullOrUndefined(row) || //(1)
isNullOrUndefined(column.visible) || //(2)
row.cells[index].visible === column.visible; //(3)
}
public getModelGenerator(): IModelGenerator<Column> {
return this.generator = this.parent.allowGrouping ? new GroupModelGenerator(this.parent) : new RowModelGenerator(this.parent);
}
public renderEmpty(tbody: HTMLElement): void {
this.getTable().appendChild(tbody);
if (this.parent.frozenRows) {
this.parent.getHeaderContent().querySelector( literals.tbody).innerHTML = '';
}
}
public setSelection(uid: string, set: boolean, clearAll?: boolean): void {
this.parent.notify(events.setFreezeSelection, { uid: uid, set: set, clearAll: clearAll });
const isFrozen: boolean = this.parent.isFrozenGrid();
if (isFrozen && this.parent.enableVirtualization) {
return;
}
if (isFrozen) {
const rows: Row<Column>[] = (<Row<Column>[]>this.getMovableRows()).filter((row: Row<Column>) => clearAll || uid === row.uid);
for (let i: number = 0; i < rows.length; i++) {
rows[i].isSelected = set;
}
}
const row: Row<Column>[] = (<Row<Column>[]>this.getRows()).filter((row: Row<Column>) => clearAll || uid === row.uid);
for (let j: number = 0; j < row.length; j++) {
row[j].isSelected = set;
const cells: Cell<Column>[] = row[j].cells;
for (let k: number = 0; k < cells.length; k++) {
cells[k].isSelected = set;
}
}
}
public getRowByIndex(index: number): Element {
index = this.getInfiniteRowIndex(index);
return this.parent.getDataRows()[index];
}
private getInfiniteRowIndex(index: number): number {
if (this.parent.infiniteScrollSettings.enableCache) {
const fRows: number = this.parent.frozenRows;
const idx: number = fRows > index ? 0 : fRows;
const firstRowIndex: number = parseInt(this.parent.getRows()[idx].getAttribute(literals.ariaRowIndex), 10);
index = fRows > index ? index : (index - firstRowIndex) + fRows;
}
return index;
}
public getVirtualRowIndex(index: number): number {
return index;
}
public getMovableRowByIndex(index: number): Element {
index = this.getInfiniteRowIndex(index);
return this.parent.getMovableDataRows()[index];
}
private enableAfterRender(e: NotifyArgs): void {
if (e.module === 'group' && e.enable) {
this.generator = this.getModelGenerator();
}
}
public setRowObjects(rows: Row<Column>[]): void {
this.rows = rows;
}
/**
* @param {NotifyArgs} args - specifies the args
* @returns {void}
* @hidden
*/
public immutableModeRendering(args: NotifyArgs = {}): void {
const gObj: IGrid = this.parent;
gObj.hideSpinner();
const key: string = gObj.getPrimaryKeyFieldNames()[0];
const oldKeys: object = {}; const newKeys: object = {}; const newRowObjs: Row<Column>[] = [];
const oldIndexes: Object = {};
const oldRowObjs: Row<Column>[] = gObj.getRowsObject().slice();
const batchChangeKeys: Object = this.getBatchEditedRecords(key, oldRowObjs); const newIndexes: Object = {};
const hasBatch: boolean = Object.keys(batchChangeKeys).length !== 0;
if (gObj.getContent().querySelector('.e-emptyrow') || args.requestType === 'reorder'
|| this.parent.groupSettings.columns.length) {
this.refreshContentRows(args);
} else {
if (gObj.currentViewData.length === 0) { return; }
const oldRowElements: Object = {};
const tbody: Element = gObj.createElement( literals.tbody);
const dataSource: Object[] = gObj.currentViewData;
const trs: Element[] = [].slice.call(this.getTable().querySelector( literals.tbody).children);
if (this.prevCurrentView.length) {
const prevLen: number = this.prevCurrentView.length;
const currentLen: number = dataSource.length;
if (prevLen === currentLen) {
for (let i: number = 0; i < currentLen; i++) {
if (this.parent.editSettings.mode === 'Batch'
&& trs[i].classList.contains('e-insertedrow')) {
trs.splice(i, 1);
--i;
continue;
}
newKeys[dataSource[i][key]] = oldKeys[this.prevCurrentView[i][key]] = i;
newIndexes[i] = dataSource[i][key];
oldRowElements[oldRowObjs[i].uid] = trs[i];
oldIndexes[i] = this.prevCurrentView[i][key];
}
} else {
for (let i: number = 0; i < currentLen; i++) {
newKeys[dataSource[i][key]] = i;
newIndexes[i] = dataSource[i][key];
}
for (let i: number = 0; i < prevLen; i++) {
if (this.parent.editSettings.mode === 'Batch'
&& trs[i].classList.contains('e-insertedrow')) {
trs.splice(i, 1);
--i;
continue;
}
oldRowElements[oldRowObjs[i].uid] = trs[i];
oldKeys[this.prevCurrentView[i][key]] = i;
oldIndexes[i] = this.prevCurrentView[i][key];
}
}
}
for (let i: number = 0; i < dataSource.length; i++) {
const oldIndex: number = oldKeys[dataSource[i][key]];
if (!isNullOrUndefined(oldIndex)) {
let isEqual: boolean = false;
if (this.parent.enableDeepCompare) {
isEqual = this.objectEqualityChecker(this.prevCurrentView[oldIndex], dataSource[i]);
}
const tr: HTMLTableRowElement = oldRowElements[oldRowObjs[oldIndex].uid] as HTMLTableRowElement;
newRowObjs.push(oldRowObjs[oldIndex]);
if (this.rowElements[oldIndex] && this.rowElements[oldIndex].getAttribute('data-uid') === newRowObjs[i].uid
&& ((hasBatch && isNullOrUndefined(batchChangeKeys[newIndexes[i]]))
|| (!hasBatch && (isEqual || this.prevCurrentView[oldIndex] === dataSource[i])))) {
if (oldIndex !== i) {
this.refreshImmutableContent(i, tr, newRowObjs[i]);
}
tbody.appendChild(tr);
continue;
}
if ((hasBatch && !isNullOrUndefined(batchChangeKeys[newIndexes[i]]))
|| (!this.parent.enableDeepCompare && dataSource[i] !== this.prevCurrentView[oldIndex])
|| (this.parent.enableDeepCompare && !isEqual)) {
oldRowObjs[oldIndex].setRowValue(dataSource[i]);
}
tbody.appendChild(tr);
this.refreshImmutableContent(i, tr, newRowObjs[i]);
} else {
const row: RowRenderer<Column> = new RowRenderer<Column>(this.serviceLocator, null, gObj);
const modelData: Row<Column>[] = this.generator.generateRows([dataSource[i]]);
newRowObjs.push(modelData[0]);
const tr: HTMLTableRowElement = row.render(modelData[0], gObj.getColumns()) as HTMLTableRowElement;
tbody.appendChild(tr);
this.refreshImmutableContent(i, tr, newRowObjs[i]);
}
}
this.rows = newRowObjs;
this.rowElements = [].slice.call(tbody.children);
remove(this.getTable().querySelector( literals.tbody));
this.getTable().appendChild(tbody);
this.parent.trigger(events.dataBound, {}, () => {
if (this.parent.allowTextWrap) {
this.parent.notify(events.freezeRender, { case: 'textwrap' });
}
});
if (args) {
const action: string = (args.requestType || '').toLowerCase() + '-complete';
this.parent.notify(action, args);
}
}
}
private objectEqualityChecker(old: Object, next: Object): boolean {
const keys: string[] = Object.keys(old);
let isEqual: boolean = true;
for (let i: number = 0; i < keys.length; i++) {
if (old[keys[i]] !== next[keys[i]]) {
const isDate: boolean = old[keys[i]] instanceof Date && next[keys[i]] instanceof Date;
if (!isDate || ((old[keys[i]] as Date).getTime() !== (next[keys[i]] as Date).getTime())) {
isEqual = false; break;
}
}
}
return isEqual;
}
private getBatchEditedRecords(primaryKey: string, rows: Row<Column>[]): Object {
const keys: Object = {};
const changes: Object = (this.parent as Grid).getBatchChanges();
let changedRecords: Object[] = [];
let addedRecords: Object[] = [];
if (Object.keys(changes).length) {
changedRecords = (<{ changedRecords?: Object[] }>changes).changedRecords;
addedRecords = (<{ addedRecords?: Object[] }>changes).addedRecords;
}
const args: NotifyArgs = { cancel: false };
this.parent.notify(events.immutableBatchCancel, { rows: rows, args: args });
if (addedRecords.length) {
if (this.parent.editSettings.newRowPosition === 'Bottom') {
rows.splice(rows.length - 1, addedRecords.length);
} else {
if (!args.cancel) {
rows.splice(0, addedRecords.length);
}
}
}
for (let i: number = 0; i < changedRecords.length; i++) {
keys[changedRecords[i][primaryKey]] = i;
}
return keys;
}
private refreshImmutableContent(index: number, tr: HTMLTableRowElement, row: Row<Column>): void {
row.isAltRow = this.parent.enableAltRow ? index % 2 !== 0 : false;
if (row.isAltRow) {
tr.classList.add('e-altrow');
} else {
tr.classList.remove('e-altrow');
}
row.index = index;
row.edit = undefined;
row.isDirty = false;
tr.setAttribute(literals.ariaRowIndex, index.toString());
this.updateCellIndex(tr, index);
}
private updateCellIndex(rowEle: HTMLTableRowElement, index: number): void {
for (let i: number = 0; i < rowEle.cells.length; i++) {
rowEle.cells[i].setAttribute('index', index.toString());
}
}
} | the_stack |
declare module 'net' {
import * as stream from 'stream';
import EventEmitter = require('events');
import * as dns from 'dns';
type LookupFunction = (
hostname: string,
options: dns.LookupOneOptions,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
) => void;
interface AddressInfo {
address: string;
family: string;
port: number;
}
interface SocketConstructorOpts {
fd?: number | undefined;
allowHalfOpen?: boolean | undefined;
readable?: boolean | undefined;
writable?: boolean | undefined;
}
interface OnReadOpts {
buffer: Uint8Array | (() => Uint8Array);
/**
* This function is called for every chunk of incoming data.
* Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer.
* Return false from this function to implicitly pause() the socket.
*/
callback(bytesWritten: number, buf: Uint8Array): boolean;
}
interface ConnectOpts {
/**
* If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket.
* Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will
* still be emitted as normal and methods like pause() and resume() will also behave as expected.
*/
onread?: OnReadOpts | undefined;
}
interface TcpSocketConnectOpts extends ConnectOpts {
port: number;
host?: string | undefined;
localAddress?: string | undefined;
localPort?: number | undefined;
hints?: number | undefined;
family?: number | undefined;
lookup?: LookupFunction | undefined;
}
interface IpcSocketConnectOpts extends ConnectOpts {
path: string;
}
type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts;
class Socket extends stream.Duplex {
constructor(options?: SocketConstructorOpts);
// Extended base methods
write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean;
write(str: Uint8Array | string, encoding?: string, cb?: (err?: Error) => void): boolean;
connect(options: SocketConnectOpts, connectionListener?: () => void): this;
connect(port: number, host: string, connectionListener?: () => void): this;
connect(port: number, connectionListener?: () => void): this;
connect(path: string, connectionListener?: () => void): this;
setEncoding(encoding?: string): this;
pause(): this;
resume(): this;
setTimeout(timeout: number, callback?: () => void): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): AddressInfo | string;
unref(): void;
ref(): void;
readonly bufferSize: number;
readonly bytesRead: number;
readonly bytesWritten: number;
readonly connecting: boolean;
readonly destroyed: boolean;
readonly localAddress: string;
readonly localPort: number;
readonly remoteAddress?: string | undefined;
readonly remoteFamily?: string | undefined;
readonly remotePort?: number | undefined;
// Extended base methods
end(cb?: () => void): void;
end(buffer: Uint8Array | string, cb?: () => void): void;
end(str: Uint8Array | string, encoding?: string, cb?: () => void): void;
/**
* events.EventEmitter
* 1. close
* 2. connect
* 3. data
* 4. drain
* 5. end
* 6. error
* 7. lookup
* 8. timeout
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: (had_error: boolean) => void): this;
addListener(event: "connect", listener: () => void): this;
addListener(event: "data", listener: (data: Buffer) => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "end", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this;
addListener(event: "ready", listener: () => void): this;
addListener(event: "timeout", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close", had_error: boolean): boolean;
emit(event: "connect"): boolean;
emit(event: "data", data: Buffer): boolean;
emit(event: "drain"): boolean;
emit(event: "end"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean;
emit(event: "ready"): boolean;
emit(event: "timeout"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: (had_error: boolean) => void): this;
on(event: "connect", listener: () => void): this;
on(event: "data", listener: (data: Buffer) => void): this;
on(event: "drain", listener: () => void): this;
on(event: "end", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this;
on(event: "ready", listener: () => void): this;
on(event: "timeout", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: (had_error: boolean) => void): this;
once(event: "connect", listener: () => void): this;
once(event: "data", listener: (data: Buffer) => void): this;
once(event: "drain", listener: () => void): this;
once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this;
once(event: "ready", listener: () => void): this;
once(event: "timeout", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: (had_error: boolean) => void): this;
prependListener(event: "connect", listener: () => void): this;
prependListener(event: "data", listener: (data: Buffer) => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this;
prependListener(event: "ready", listener: () => void): this;
prependListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: (had_error: boolean) => void): this;
prependOnceListener(event: "connect", listener: () => void): this;
prependOnceListener(event: "data", listener: (data: Buffer) => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this;
prependOnceListener(event: "ready", listener: () => void): this;
prependOnceListener(event: "timeout", listener: () => void): this;
}
interface ListenOptions {
port?: number | undefined;
host?: string | undefined;
backlog?: number | undefined;
path?: string | undefined;
exclusive?: boolean | undefined;
readableAll?: boolean | undefined;
writableAll?: boolean | undefined;
/**
* @default false
*/
ipv6Only?: boolean | undefined;
}
// https://github.com/nodejs/node/blob/master/lib/net.js
class Server extends EventEmitter {
constructor(connectionListener?: (socket: Socket) => void);
constructor(options?: { allowHalfOpen?: boolean | undefined, pauseOnConnect?: boolean | undefined }, connectionListener?: (socket: Socket) => void);
listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this;
listen(port?: number, hostname?: string, listeningListener?: () => void): this;
listen(port?: number, backlog?: number, listeningListener?: () => void): this;
listen(port?: number, listeningListener?: () => void): this;
listen(path: string, backlog?: number, listeningListener?: () => void): this;
listen(path: string, listeningListener?: () => void): this;
listen(options: ListenOptions, listeningListener?: () => void): this;
listen(handle: any, backlog?: number, listeningListener?: () => void): this;
listen(handle: any, listeningListener?: () => void): this;
close(callback?: (err?: Error) => void): this;
address(): AddressInfo | string | null;
getConnections(cb: (error: Error | null, count: number) => void): void;
ref(): this;
unref(): this;
maxConnections: number;
connections: number;
listening: boolean;
/**
* events.EventEmitter
* 1. close
* 2. connection
* 3. error
* 4. listening
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "connection", listener: (socket: Socket) => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "connection", socket: Socket): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connection", listener: (socket: Socket) => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "connection", listener: (socket: Socket) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "connection", listener: (socket: Socket) => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connection", listener: (socket: Socket) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
}
interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined;
}
interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined;
}
type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts;
function createServer(connectionListener?: (socket: Socket) => void): Server;
function createServer(options?: { allowHalfOpen?: boolean | undefined, pauseOnConnect?: boolean | undefined }, connectionListener?: (socket: Socket) => void): Server;
function connect(options: NetConnectOpts, connectionListener?: () => void): Socket;
function connect(port: number, host?: string, connectionListener?: () => void): Socket;
function connect(path: string, connectionListener?: () => void): Socket;
function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket;
function createConnection(port: number, host?: string, connectionListener?: () => void): Socket;
function createConnection(path: string, connectionListener?: () => void): Socket;
function isIP(input: string): number;
function isIPv4(input: string): boolean;
function isIPv6(input: string): boolean;
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Diagram } from '../../../src/diagram/diagram';
import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element';
import { NodeModel, PathModel } from '../../../src/diagram/objects/node-model';
import { ShadowModel, RadialGradientModel, StopModel, LinearGradientModel, GradientModel } from '../../../src/diagram/core/appearance-model';
import { NodeConstraints } from '../../../src/diagram/enum/enum';
import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec';
/**
* Shadow & Gradient
*/
describe('Diagram Control for shadow properties', () => {
describe('Shadow', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramg' });
document.body.appendChild(ele);
let shape1: PathModel = { type: 'Path', data: 'M370.9702,194.9961L359.5112,159.7291L389.5112,137.9341L419.5112,159.7291L408.0522,194.9961L370.9702,194.9961z' }
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: shape1
};
let shadow1: ShadowModel = { angle: 135 };
let shape2: PathModel = { type: 'Path', data: 'M370.9702,194.9961L359.5112,159.7291L389.5112,137.9341L419.5112,159.7291L408.0522,194.9961L370.9702,194.9961z' }
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 250, offsetY: 200,
shape: shape2, shadow: shadow1, constraints: NodeConstraints.Default | NodeConstraints.Shadow
};
let shadow2: ShadowModel = { distance: 10 };
let shape3: PathModel = { type: 'Path', data: 'M370.9702,194.9961L359.5112,159.7291L389.5112,137.9341L419.5112,159.7291L408.0522,194.9961L370.9702,194.9961z' }
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, shadow: shadow2, constraints: NodeConstraints.Default | NodeConstraints.Shadow
};
let shadow3: ShadowModel = { opacity: 0.9 };
let shape4: PathModel = { type: 'Path', data: 'M370.9702,194.9961L359.5112,159.7291L389.5112,137.9341L419.5112,159.7291L408.0522,194.9961L370.9702,194.9961z' }
let node4: NodeModel = {
id: 'node4', width: 100, height: 100, offsetX: 100, offsetY: 400,
shape: shape4, shadow: shadow3, constraints: NodeConstraints.Default | NodeConstraints.Shadow
};
let shadow4: ShadowModel = { color: 'red', opacity: 0.9 };
let shape5: PathModel = { type: 'Path', data: 'M370.9702,194.9961L359.5112,159.7291L389.5112,137.9341L419.5112,159.7291L408.0522,194.9961L370.9702,194.9961z' }
let node5: NodeModel = {
id: 'node5', width: 100, height: 100, offsetX: 250, offsetY: 400,
shape: shape5, shadow: shadow4, constraints: NodeConstraints.Default | NodeConstraints.Shadow
};
diagram = new Diagram({ mode: 'SVG', width: 1000, height: 1000, nodes: [node1, node2, node3, node4, node5] });
diagram.appendTo('#diagramg');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Testing default and custom shadow in SVG rendering Mode', (done: Function) => {
if (diagram.nodes.length) {
let failure: boolean = false;
for (let i: number = 0; i < diagram.nodes.length; i++) {
let node: NodeModel = diagram.nodes[i];
let element: DiagramElement = node.wrapper.children[0];
if (!(node.shadow === element.shadow) && element.shadow) {
failure = true;
break;
}
}
if (!failure) {
done();
} else {
fail();
}
}
});
});
describe('Gradient', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramh' });
document.body.appendChild(ele);
let shape1: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' }
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: shape1
};
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let shape2: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 250, offsetY: 200,
shape: shape2, style: { gradient: gradient1 }
};
let stopscol2: StopModel[] = [];
let stops3: StopModel = { color: 'white', offset: 0 };
stopscol2.push(stops3);
let stops4: StopModel = { color: 'red', offset: 50 };
stopscol2.push(stops4);
let gradient2: RadialGradientModel = { stops: stopscol2, type: 'Radial' };
let shape3: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, style: { gradient: gradient2 }
};
diagram = new Diagram({ mode: 'SVG', width: 1000, height: 1000, nodes: [node1, node2, node3] });
diagram.appendTo('#diagramh');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Testing radial gradient in SVG rendering Mode', (done: Function) => {
if (diagram.nodes.length) {
let failure: boolean = false;
for (let i: number = 0; i < diagram.nodes.length; i++) {
let node: NodeModel = diagram.nodes[i];
let element: DiagramElement = node.wrapper.children[0];
if (!(node.style.gradient === element.style.gradient)) {
failure = true;
break;
}
}
if (!failure) {
done();
} else {
fail();
}
}
});
});
describe('Gradient', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramh' });
document.body.appendChild(ele);
let shape1: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' }
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: shape1
};
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let shape2: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 250, offsetY: 200,
shape: shape2, style: { gradient: gradient1 }
};
let stopscol2: StopModel[] = [];
let stops3: StopModel = { color: 'white', offset: 50 };
stopscol2.push(stops3);
let stops4: StopModel = { color: 'red', offset: 0 };
stopscol2.push(stops4);
let gradient2: RadialGradientModel = { stops: stopscol2, type: 'Radial' };
let shape3: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, style: { gradient: gradient2 }
};
let stopscol21: StopModel[] = [];
let stops31: StopModel = { color: 'white', offset: 50 };
stopscol21.push(stops3);
let stops41: StopModel = { color: 'red', offset: 0 };
stopscol21.push(stops4);
let gradient21: GradientModel = { stops: stopscol21, type: undefined };
let shape31: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node31: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, style: { gradient: gradient21 }
};
diagram = new Diagram({ mode: 'SVG', width: 1000, height: 1000, nodes: [node1, node2, node3] });
diagram.appendTo('#diagramh');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Testing radial gradient for offset change in SVG rendering Mode', (done: Function) => {
if (diagram.nodes.length) {
let failure: boolean = false;
for (let i: number = 0; i < diagram.nodes.length; i++) {
let node: NodeModel = diagram.nodes[i];
let element: DiagramElement = node.wrapper.children[0];
if (!(node.style.gradient === element.style.gradient)) {
failure = true;
break;
}
}
if (!failure) {
done();
} else {
fail();
}
}
});
});
describe('Gradient', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagrami' });
document.body.appendChild(ele);
let shape1: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' }
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: shape1
};
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: LinearGradientModel = { x1: 0, x2: 50, y1: 0, y2: 50, stops: stopscol, type: 'Linear' };
let shape2: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 250, offsetY: 200,
shape: shape2, style: { gradient: gradient1 }
};
let stopscol2: StopModel[] = [];
let stops3: StopModel = { color: 'white', offset: 0 };
stopscol2.push(stops3);
let stops4: StopModel = { color: 'red', offset: 50 };
stopscol2.push(stops4);
let gradient2: LinearGradientModel = { stops: stopscol2, type: 'Linear' };
gradient2.x1 = 10;
gradient2.x2 = 20;
gradient2.y1 = 20;
gradient2.y2 = 20;
let shape3: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, style: { gradient: gradient2 }
};
diagram = new Diagram({ mode: 'SVG', width: 1000, height: 1000, nodes: [node1, node2, node3] });
diagram.appendTo('#diagrami');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Checking Linear Gradient in SVG rendering Mode', (done: Function) => {
if (diagram.nodes.length) {
let failure: boolean = false;
for (let i: number = 0; i < diagram.nodes.length; i++) {
let node: NodeModel = diagram.nodes[i];
let element: DiagramElement = node.wrapper.children[0];
if (!(node.style.gradient === element.style.gradient)) {
failure = true;
break;
}
}
if (!failure) {
done();
} else {
fail();
}
}
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
describe('Gradient', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagramh' });
document.body.appendChild(ele);
let shape1: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' }
let node1: NodeModel = {
id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 200,
shape: shape1,
annotations: [{ id: 'label1', content: 'label' }]
};
let stopscol: StopModel[] = [];
let stops1: StopModel = { color: 'white', offset: 0 };
stopscol.push(stops1);
let stops2: StopModel = { color: 'red', offset: 50 };
stopscol.push(stops2);
let gradient1: RadialGradientModel = { cx: 50, cy: 50, fx: 50, fy: 50, stops: stopscol, type: 'Radial' };
let shape2: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node2: NodeModel = {
id: 'node2', width: 100, height: 100, offsetX: 250, offsetY: 200,
shape: shape2, style: { gradient: gradient1 },
annotations: [{ id: 'label1', content: 'label' }]
};
let stopscol2: StopModel[] = [];
let stops3: StopModel = { color: 'white', offset: 0 };
stopscol2.push(stops3);
let stops4: StopModel = { color: 'red', offset: 50 };
stopscol2.push(stops4);
let gradient2: RadialGradientModel = { stops: stopscol2, type: 'Radial' };
let shape3: PathModel = { type: 'Path', data: 'M 0,0 L 100,0 L100,100 L0,100 Z' };
let node3: NodeModel = {
id: 'node3', width: 100, height: 100, offsetX: 400, offsetY: 200,
shape: shape3, style: { gradient: gradient2 }
};
diagram = new Diagram({ width: 1000, height: 1000, nodes: [node1, node2, node3] });
diagram.appendTo('#diagramh');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Testing radial gradient in SVG mode', (done: Function) => {
expect((document.getElementById('node2_content_radial').parentNode as SVGElement).id === 'diagramhgradient_pattern').toBe(true);
done();
});
});
describe('Radial Gradient issue in Canvas mode', () => {
let diagram: Diagram;
let ele: HTMLElement;
beforeAll((): void => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
ele = createElement('div', { id: 'diagram_group' });
document.body.appendChild(ele);
let nodes: NodeModel[] = [
{
id: 'node1', width: 100, height: 100, offsetX: 400, offsetY: 300, annotations: [{ content: 'Node1', height: 50, width: 50 }],
style: { strokeColor: '#8f908f', fill: '#e2f3fa', gradient: {
cx: 50, cy: 50, fx: 50, fy: 50,
stops: [{ color: '#00555b', offset: 0 },
{ color: '#37909A', offset: 90 }],
type: 'Radial'
} },
shape: { type: 'Basic', shape: 'Diamond' },
},
{
id: 'node2', width: 80, height: 130, offsetX: 600, offsetY: 100, annotations: [{ content: 'Node2', height: 50, width: 50 }],
style: { strokeColor: '#8f908f', fill: '#e2f3fa', gradient: {
cx: 50, cy: 50, fx: 50, fy: 50,
stops: [{ color: '#00555b', offset: 0 },
{ color: '#37909A', offset: 90 }],
type: 'Radial'
} },
shape: { type: 'Basic', shape: 'Ellipse' },
}
];
diagram = new Diagram({
width: '800px', height: '500px', nodes: nodes,
mode: 'Canvas'
});
diagram.appendTo('#diagram_group');
});
afterAll((): void => {
diagram.destroy();
ele.remove();
});
it('Check whether radial gradient applied for the node', (done: Function) => {
expect((diagram.nodes[0].style.gradient as RadialGradientModel).stops[0].color === "#00555b").toBe(true);
expect((diagram.nodes[0].style.gradient as RadialGradientModel).stops[1].color === "#37909A").toBe(true);
done();
});
});
}); | the_stack |
import { c, cB, cE, cM, cNotM } from '../../../_utils/cssr'
import fadeInScaleUpTransition from '../../../_styles/transitions/fade-in-scale-up.cssr'
// vars:
// --n-bezier
// --n-icon-color
// --n-icon-color-disabled
// --n-panel-border-radius
// --n-panel-color
// --n-panel-box-shadow
// --n-panel-text-color
// panel header
// --n-panel-header-padding
// --n-panel-header-divider-color
// panel calendar
// --n-calendar-left-padding
// --n-calendar-right-padding
// --n-calendar-title-height
// --n-calendar-title-padding
// --n-calendar-title-font-size
// --n-calendar-title-text-color
// --n-calendar-title-font-weight
// --n-calendar-title-grid-template-columns
// --n-calendar-days-height
// --n-calendar-days-divider-color
// --n-calendar-days-font-size
// --n-calendar-days-text-color
// --n-calendar-divider-color
// panel action
// --n-panel-action-padding
// --n-panel-action-divider-color
// panel item
// --n-item-border-radius
// --n-item-size
// --n-item-cell-width
// --n-item-cell-height
// --n-item-text-color
// --n-item-color-included
// --n-item-color-disabled
// --n-item-color-hover
// --n-item-color-active
// --n-item-font-size
// --n-item-text-color-disabled
// --n-item-text-color-active
// scroll item
// --n-scroll-item-width
// --n-scroll-item-height
// --n-scroll-item-border-radius
// panel arrow
// --n-arrow-size
// --n-arrow-color
export default c([
cB('date-picker', `
position: relative;
z-index: auto;
`, [
cB('date-picker-icon', `
color: var(--n-icon-color);
transition: color .3s var(--n-bezier);
`),
cM('disabled', [
cB('date-picker-icon', `
color: var(--n-icon-color-disabled);
`)
])
]),
cB('date-panel', `
outline: none;
margin: 4px 0;
display: grid;
grid-template-columns: 0fr;
border-radius: var(--n-panel-border-radius);
background-color: var(--n-panel-color);
box-shadow: var(--n-panel-box-shadow);
color: var(--n-panel-text-color);
`, [
fadeInScaleUpTransition(),
cB('date-panel-calendar', {
padding: 'var(--n-calendar-left-padding)',
display: 'grid',
gridTemplateColumns: '1fr',
gridArea: 'left-calendar'
}, [
cM('end', {
padding: 'var(--n-calendar-right-padding)',
gridArea: 'right-calendar'
})
]),
cB('date-panel-month-calendar', {
display: 'flex',
gridArea: 'left-calendar'
}, [
cE('picker-col', `
min-width: var(--n-scroll-item-width);
height: calc(var(--n-scroll-item-height) * 6);
user-select: none;
`, [
c('&:first-child', `
min-width: calc(var(--n-scroll-item-width) + 4px);
`, [
cE('picker-col-item', [
c('&::before', 'left: 4px;')
])
]),
cE('padding', `
height: calc(var(--n-scroll-item-height) * 5)
`)
]),
cE('picker-col-item', `
z-index: 0;
cursor: pointer;
height: var(--n-scroll-item-height);
box-sizing: border-box;
padding-top: 4px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
transition:
color .3s var(--n-bezier),
background-color .3s var(--n-bezier);
background: #0000;
color: var(--n-item-text-color);
`, [
c('&::before', `
z-index: -1;
content: "";
position: absolute;
left: 0;
right: 4px;
top: 4px;
bottom: 0;
border-radius: var(--n-scroll-item-border-radius);
transition:
background-color .3s var(--n-bezier);
`),
cNotM('disabled', [
c('&:hover::before', `
background-color: var(--n-item-color-hover);
`),
cM('selected', `
color: var(--n-item-color-active);
`, [
c('&::before', 'background-color: var(--n-item-color-hover);')
])
]),
cM('disabled', `
background-color: var(--n-item-color-disabled);
cursor: not-allowed;
`)
])
]),
cM('date', {
gridTemplateAreas: `
"left-calendar"
"footer"
"action"
`
}),
cM('daterange', {
gridTemplateAreas: `
"left-calendar divider right-calendar"
"footer footer footer"
"action action action"
`
}),
cM('datetime', {
gridTemplateAreas: `
"header"
"left-calendar"
"footer"
"action"
`
}),
cM('datetimerange', {
gridTemplateAreas: `
"header header header"
"left-calendar divider right-calendar"
"footer footer footer"
"action action action"
`
}),
cM('month', {
gridTemplateAreas: `
"left-calendar"
"footer"
"action"
`
}),
cB('date-panel-footer', {
gridArea: 'footer'
}),
cB('date-panel-actions', {
gridArea: 'action'
}),
cB('date-panel-header', {
gridArea: 'header'
}),
cB('date-panel-header', `
box-sizing: border-box;
width: 100%;
align-items: center;
padding: var(--n-panel-header-padding);
display: flex;
justify-content: space-between;
border-bottom: 1px solid var(--n-panel-header-divider-color);
`, [
c('>', [
c('*:not(:last-child)', {
marginRight: '10px'
}),
c('*', {
flex: 1,
width: 0
}),
cB('time-picker', {
zIndex: 1
})
])
]),
cB('date-panel-month', `
box-sizing: border-box;
display: grid;
grid-template-columns: var(--n-calendar-title-grid-template-columns);
align-items: center;
justify-items: center;
padding: var(--n-calendar-title-padding);
height: var(--n-calendar-title-height);
`, [
cE('prev, next, fast-prev, fast-next', `
line-height: 0;
cursor: pointer;
width: var(--n-arrow-size);
height: var(--n-arrow-size);
color: var(--n-arrow-color);
`),
cE('month-year', `
font-size: var(--n-calendar-title-font-size);
font-weight: var(--n-calendar-title-font-weight);
line-height: 17px;
flex-grow: 1;
text-align: center;
color: var(--n-calendar-title-text-color);
`)
]),
cB('date-panel-weekdays', `
display: grid;
margin: auto;
grid-template-columns: repeat(7, var(--n-item-cell-width));
grid-template-rows: repeat(1, var(--n-item-cell-height));
align-items: center;
justify-items: center;
margin-bottom: 4px;
border-bottom: 1px solid var(--n-calendar-days-divider-color);
`, [
cE('day', `
line-height: 15px;
width: var(--n-item-size);
text-align: center;
font-size: var(--n-calendar-days-font-size);
color: var(--n-item-text-color);
`)
]),
cB('date-panel-dates', `
margin: auto;
display: grid;
grid-template-columns: repeat(7, var(--n-item-cell-width));
grid-template-rows: repeat(6, var(--n-item-cell-height));
align-items: center;
justify-items: center;
flex-wrap: wrap;
`, [
cB('date-panel-date', `
position: relative;
width: var(--n-item-size);
height: var(--n-item-size);
line-height: var(--n-item-size);
text-align: center;
font-size: var(--n-item-font-size);
border-radius: var(--n-item-border-radius);
z-index: 0;
cursor: pointer;
transition:
background-color .2s var(--n-bezier),
color .2s var(--n-bezier);
`, [
cNotM('disabled', [
cNotM('selected', [
c('&:hover', {
backgroundColor: 'var(--n-item-color-hover)'
})
])
]),
cM('current', [
cE('sup', `
position: absolute;
top: 2px;
right: 2px;
content: "";
height: 4px;
width: 4px;
border-radius: 2px;
background-color: var(--n-item-color-active);
transition:
background-color .2s var(--n-bezier);
`)
]),
c('&::after', `
content: "";
z-index: -1;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
border-radius: inherit;
transition: background-color .3s var(--n-bezier);
`),
cM('covered, start, end', [
cNotM('excluded', [
c('&::before', `
content: "";
z-index: -2;
position: absolute;
left: calc((var(--n-item-size) - var(--n-item-cell-width)) / 2);
right: calc((var(--n-item-size) - var(--n-item-cell-width)) / 2);
top: 0;
bottom: 0;
background-color: var(--n-item-color-included);
`),
c('&:nth-child(7n + 1)::before', {
borderTopLeftRadius: 'var(--n-item-border-radius)',
borderBottomLeftRadius: 'var(--n-item-border-radius)'
}),
c('&:nth-child(7n + 7)::before', {
borderTopRightRadius: 'var(--n-item-border-radius)',
borderBottomRightRadius: 'var(--n-item-border-radius)'
})
])
]),
cM('selected', {
color: 'var(--n-item-text-color-active)'
}, [
c('&::after', {
backgroundColor: 'var(--n-item-color-active)'
}),
cM('start', [
c('&::before', {
left: '50%'
})
]),
cM('end', [
c('&::before', {
right: '50%'
})
]),
cE('sup', {
backgroundColor: 'var(--n-panel-color)'
})
]),
cM('excluded', {
color: 'var(--n-item-text-color-disabled)'
}, [
cM('selected', [
c('&::after', {
backgroundColor: 'var(--n-item-color-disabled)'
})
])
]),
cM('disabled', {
cursor: 'not-allowed',
color: 'var(--n-item-text-color-disabled)'
}, [
cM('covered', [
c('&::before', {
backgroundColor: 'var(--n-item-color-disabled)'
})
]),
cM('selected', [
c('&::before', {
backgroundColor: 'var(--n-item-color-disabled)'
}),
c('&::after', {
backgroundColor: 'var(--n-item-color-disabled)'
})
])
])
])
]),
cE('vertical-divider', `
grid-area: divider;
height: 100%;
width: 1px;
background-color: var(--n-calendar-divider-color);
`),
cB('date-panel-footer', {
borderTop: '1px solid var(--n-panel-action-divider-color)',
padding: 'var(--n-panel-extra-footer-padding)'
}),
cB('date-panel-actions', `
flex: 1;
padding: var(--n-panel-action-padding);
display: flex;
align-items: center;
justify-content: space-between;
border-top: 1px solid var(--n-panel-action-divider-color);
`, [
cE('prefix, suffix', `
display: flex;
margin-bottom: -8px;
`),
cE('suffix', `
align-self: flex-end;
`),
cE('prefix', `
flex-wrap: wrap;
`),
cB('button', `
margin-bottom: 8px;
`, [
c('&:not(:last-child)', `
margin-right: 8px;
`)
])
])
]),
c('[data-n-date].transition-disabled', {
transition: 'none !important'
}, [
c('&::before, &::after', {
transition: 'none !important'
})
])
]) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.