text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { expect } from 'chai';
import { testImmutableClass } from 'immutable-class-tester';
import { $, Expression } from 'plywood';
import { MANIFESTS } from "../../manifests/index";
import { Essence, EssenceJS, VisStrategy } from './essence';
import { DataCube, Introspection } from "../data-cube/data-cube";
import { DataCubeMock } from "../data-cube/data-cube.mock";
import { TOTALS_MANIFEST } from "../../manifests/totals/totals";
import { Splits } from "../splits/splits";
import { SplitCombineMock } from "../split-combine/split-combine.mock";
import { BAR_CHART_MANIFEST } from "../../manifests/bar-chart/bar-chart";
import { SplitCombine } from "../split-combine/split-combine";
import { RefExpression } from "plywood";
describe('Essence', () => {
var dataCubeJS = {
name: 'twitter',
title: 'Twitter',
clusterName: 'druid',
source: 'twitter',
introspection: ('none' as Introspection),
dimensions: [
{
kind: 'time',
name: 'time',
title: 'Time',
formula: '$time'
},
{
kind: 'string',
name: 'twitterHandle',
title: 'Twitter Handle',
formula: '$twitterHandle'
}
],
measures: [
{
name: 'count',
title: 'count',
formula: '$main.count()'
}
],
timeAttribute: 'time',
defaultTimezone: 'Etc/UTC',
defaultFilter: { op: 'literal', value: true },
defaultSplits: 'time',
defaultDuration: 'P3D',
defaultSortMeasure: 'count',
defaultPinnedDimensions: ['twitterHandle'],
refreshRule: {
rule: "fixed",
time: new Date('2015-09-13T00:00:00Z')
}
};
var dataCube = DataCube.fromJS(dataCubeJS);
var context = { dataCube, visualizations: MANIFESTS };
it('is an immutable class', () => {
testImmutableClass<EssenceJS>(Essence, [
{
visualization: 'totals',
timezone: 'Etc/UTC',
filter: {
op: "literal",
value: true
},
pinnedDimensions: [],
singleMeasure: 'count',
selectedMeasures: [],
splits: []
},
{
visualization: 'totals',
timezone: 'Etc/UTC',
filter: $('twitterHandle').overlap(['A', 'B', 'C']).toJS(),
pinnedDimensions: ['twitterHandle'],
singleMeasure: 'count',
selectedMeasures: ['count'],
splits: []
}
], { context });
});
describe('errors', () => {
it('must have context', () => {
expect(() => {
Essence.fromJS({} as any);
}).to.throw('must have context');
});
});
describe('upgrades', () => {
it('works in the base case', () => {
var essence = Essence.fromJS({
visualization: 'totals',
timezone: 'Etc/UTC',
pinnedDimensions: [],
selectedMeasures: [],
splits: []
}, context);
expect(essence.toJS()).to.deep.equal({
"filter": {
"action": {
"action": "in",
"expression": {
"action": {
"action": "timeRange",
"duration": "P3D",
"step": -1
},
"expression": {
"name": "m",
"op": "ref"
},
"op": "chain"
}
},
"expression": {
"name": "time",
"op": "ref"
},
"op": "chain"
},
"multiMeasureMode": true,
"pinnedDimensions": [],
"singleMeasure": "count",
"selectedMeasures": [],
"splits": [],
"timezone": "Etc/UTC",
"visualization": "totals"
});
});
it('adds timezone', () => {
var linkItem = Essence.fromJS({
visualization: 'totals',
pinnedDimensions: ['statusCode'],
selectedMeasures: ['count'],
splits: [],
filter: 'true'
}, context);
expect(linkItem.toJS()).to.deep.equal({
"filter": {
"op": "literal",
"value": true
},
"multiMeasureMode": true,
"pinnedDimensions": [],
"singleMeasure": "count",
"selectedMeasures": [
"count"
],
"splits": [],
"timezone": "Etc/UTC",
"visualization": "totals"
});
});
it('handles time series', () => {
var hashNoVis = "2/EQUQLgxg9AqgKgYWAGgN7APYAdgC5gA2AlmAKYBOAhgSsAG7UCupeY5zAvsgNoC6ybZsmAQMjAHZgU3EWMnB+MsAHcSZcgAlK4gCYEW/cYwIEgA=";
var timeSeriesHash = `time-series/${hashNoVis}`;
var lineChartHash = `line-chart/${hashNoVis}`;
var barChartHash = `bar-chart/${hashNoVis}`;
var timeSeries = Essence.fromHash(timeSeriesHash, context);
var lineChart = Essence.fromHash(lineChartHash, context);
var barChart = Essence.fromHash(barChartHash, context);
expect(timeSeries.visualization).to.equal(lineChart.visualization);
expect(timeSeries.visualization).to.not.equal(barChart.visualization);
});
});
describe('.fromDataCube', () => {
it('works in the base case', () => {
var essence = Essence.fromDataCube(dataCube, context);
expect(essence.toJS()).to.deep.equal({
"filter": {
"action": {
"action": "in",
"expression": {
"action": {
"action": "timeRange",
"duration": "P3D",
"step": -1
},
"expression": {
"name": "m",
"op": "ref"
},
"op": "chain"
}
},
"expression": {
"name": "time",
"op": "ref"
},
"op": "chain"
},
"pinnedDimensions": [
"twitterHandle"
],
"singleMeasure": "count",
"selectedMeasures": [
"count"
],
"splits": [
{
"bucketAction": {
"action": "timeBucket",
"duration": "PT1H"
},
"expression": {
"name": "time",
"op": "ref"
},
"sortAction": {
"action": "sort",
"direction": "ascending",
"expression": {
"name": "time",
"op": "ref"
}
}
}
],
"timezone": "Etc/UTC",
"visualization": "line-chart"
});
});
});
describe('.toHash / #fromHash', () => {
it("is symmetric", () => {
var essence1 = Essence.fromJS({
visualization: 'totals',
timezone: 'Etc/UTC',
filter: {
op: "literal",
value: true
},
pinnedDimensions: ['twitterHandle'],
selectedMeasures: ['count'],
splits: []
}, context);
var hash = essence1.toHash();
var essence2 = Essence.fromHash(hash, context);
expect(essence1.toJS()).to.deep.equal(essence2.toJS());
});
});
describe('vis picking', () => {
describe("#getBestVisualization", () => {
it("#getBestVisualization", () => {
var dimensions = DataCubeMock.twitter().dimensions;
var vis1 = Essence.getBestVisualization(MANIFESTS, DataCubeMock.twitter(), Splits.EMPTY, null, null);
expect(vis1.visualization.name).to.deep.equal("totals");
var vis2 = Essence.getBestVisualization(MANIFESTS, DataCubeMock.twitter(), Splits.fromJS(['tweetLength'], { dimensions }), null, TOTALS_MANIFEST);
expect(vis2.visualization.name).to.deep.equal("bar-chart");
var vis3 = Essence.getBestVisualization(MANIFESTS, DataCubeMock.twitter(), Splits.fromJS(['time'], { dimensions }), null, BAR_CHART_MANIFEST);
expect(vis3.visualization.name).to.deep.equal("line-chart");
});
});
describe("#changeSplits", () => {
var essence: Essence = null;
beforeEach(() => {
essence = Essence.fromJS({
visualization: null,
timezone: 'Etc/UTC',
pinnedDimensions: [],
selectedMeasures: [],
splits: []
}, {
dataCube: DataCubeMock.twitter(),
visualizations: MANIFESTS
});
});
var timeSplit = SplitCombine.fromJS({expression: { op: 'ref', name: 'time' }});
var tweetLengthSplit = SplitCombine.fromJS({expression: { op: 'ref', name: 'tweetLength' }});
var twitterHandleSplit = SplitCombine.fromJS({expression: { op: 'ref', name: 'twitterHandle' }});
it("defaults to bar chart with numeric dimension and is sorted on self", () => {
essence = essence.addSplit(tweetLengthSplit, VisStrategy.FairGame);
expect(essence.visualization.name).to.deep.equal("bar-chart");
expect((essence.splits.get(0).sortAction.expression as RefExpression).name).to.deep.equal('tweetLength');
expect(essence.visResolve.state).to.deep.equal("ready");
});
it("defaults to line chart with a time split", () => {
essence = essence.changeSplit(timeSplit, VisStrategy.FairGame);
expect(essence.visualization.name).to.deep.equal("line-chart");
expect(essence.visResolve.state).to.deep.equal("ready");
});
it("fall back with no splits", () => {
essence = essence.changeVisualization(BAR_CHART_MANIFEST);
expect(essence.visualization.name).to.deep.equal("bar-chart");
expect(essence.visResolve.state).to.deep.equal("manual");
});
it("in fair game, adding a string split to time split results in line chart", () => {
essence = essence.addSplit(timeSplit, VisStrategy.FairGame);
essence = essence.addSplit(twitterHandleSplit, VisStrategy.FairGame);
expect(essence.visualization.name).to.deep.equal("line-chart");
expect(essence.visResolve.state).to.deep.equal("ready");
});
it("gives existing vis a bonus", () => {
essence = essence.addSplit(timeSplit, VisStrategy.FairGame);
essence = essence.changeVisualization(BAR_CHART_MANIFEST);
expect(essence.visualization.name).to.deep.equal("bar-chart");
expect(essence.visResolve.state).to.deep.equal("ready");
essence = essence.addSplit(twitterHandleSplit, VisStrategy.UnfairGame);
expect(essence.visualization.name).to.deep.equal("bar-chart");
expect(essence.visResolve.state).to.deep.equal("ready");
});
it("falls back when can't handle measures", () => {
// todo
});
});
});
}); | the_stack |
import * as assert from 'assert';
import * as nock from 'nock';
import {describe, it, afterEach} from 'mocha';
import {Impersonated, JWT} from '../src';
import {CredentialRequest} from '../src/auth/credentials';
const PEM_PATH = './test/fixtures/private.pem';
nock.disableNetConnect();
const url = 'http://example.com';
function createGTokenMock(body: CredentialRequest) {
return nock('https://www.googleapis.com')
.post('/oauth2/v4/token')
.reply(200, body);
}
interface ImpersonatedCredentialRequest {
delegates: string[];
scope: string[];
lifetime: string;
}
describe('impersonated', () => {
afterEach(() => {
nock.cleanAll();
});
it('should request impersonated credentials on first request', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
nock(url).get('/').reply(200),
createGTokenMock({
access_token: 'abc123',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken',
(body: ImpersonatedCredentialRequest) => {
assert.strictEqual(body.lifetime, '30s');
assert.deepStrictEqual(body.delegates, []);
assert.deepStrictEqual(body.scope, [
'https://www.googleapis.com/auth/cloud-platform',
]);
return true;
}
)
.reply(200, {
accessToken: 'qwerty345',
expireTime: tomorrow.toISOString(),
}),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
await impersonated.request({url});
assert.strictEqual(impersonated.credentials.access_token, 'qwerty345');
assert.strictEqual(
impersonated.credentials.expiry_date,
tomorrow.getTime()
);
scopes.forEach(s => s.done());
});
it('should not request impersonated credentials on second request', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
nock(url).get('/').reply(200),
nock(url).get('/').reply(200),
createGTokenMock({
access_token: 'abc123',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken',
(body: ImpersonatedCredentialRequest) => {
assert.strictEqual(body.lifetime, '30s');
assert.deepStrictEqual(body.delegates, []);
assert.deepStrictEqual(body.scope, [
'https://www.googleapis.com/auth/cloud-platform',
]);
return true;
}
)
.reply(200, {
accessToken: 'qwerty345',
expireTime: tomorrow.toISOString(),
}),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
await impersonated.request({url});
await impersonated.request({url});
assert.strictEqual(impersonated.credentials.access_token, 'qwerty345');
assert.strictEqual(
impersonated.credentials.expiry_date,
tomorrow.getTime()
);
scopes.forEach(s => s.done());
});
it('should request impersonated credentials once new credentials expire', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
nock(url).get('/').reply(200),
nock(url).get('/').reply(200),
createGTokenMock({
access_token: 'abc123',
}),
createGTokenMock({
access_token: 'abc456',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken',
() => {
return true;
}
)
.reply(200, {
accessToken: 'qwerty345',
expireTime: tomorrow.toISOString(),
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken',
() => {
return true;
}
)
.reply(200, {
accessToken: 'qwerty456',
expireTime: tomorrow.toISOString(),
}),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
await impersonated.request({url});
// Force both the wrapped and impersonated client to appear to have
// expired:
jwt.credentials.expiry_date = Date.now();
impersonated.credentials.expiry_date = Date.now();
await impersonated.request({url});
assert.strictEqual(impersonated.credentials.access_token, 'qwerty456');
assert.strictEqual(
impersonated.credentials.expiry_date,
tomorrow.getTime()
);
scopes.forEach(s => s.done());
});
it('throws meaningful error when context available', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
createGTokenMock({
access_token: 'abc123',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken'
)
.reply(404, {
error: {
code: 404,
message: 'Requested entity was not found.',
status: 'NOT_FOUND',
},
}),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
impersonated.credentials.access_token = 'initial-access-token';
impersonated.credentials.expiry_date = Date.now() - 10000;
await assert.rejects(impersonated.request({url}), /NOT_FOUND/);
scopes.forEach(s => s.done());
});
it('handles errors without context', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
createGTokenMock({
access_token: 'abc123',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken'
)
.reply(500),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
impersonated.credentials.access_token = 'initial-access-token';
impersonated.credentials.expiry_date = Date.now() - 10000;
await assert.rejects(impersonated.request({url}), /unable to impersonate/);
scopes.forEach(s => s.done());
});
it('handles error authenticating sourceClient', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
nock('https://www.googleapis.com').post('/oauth2/v4/token').reply(401),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
await assert.rejects(impersonated.request({url}), /unable to impersonate/);
scopes.forEach(s => s.done());
});
it('should populate request headers', async () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const scopes = [
createGTokenMock({
access_token: 'abc123',
}),
nock('https://iamcredentials.googleapis.com')
.post(
'/v1/projects/-/serviceAccounts/target@project.iam.gserviceaccount.com:generateAccessToken',
(body: ImpersonatedCredentialRequest) => {
assert.strictEqual(body.lifetime, '30s');
assert.deepStrictEqual(body.delegates, []);
assert.deepStrictEqual(body.scope, [
'https://www.googleapis.com/auth/cloud-platform',
]);
return true;
}
)
.reply(200, {
accessToken: 'qwerty345',
expireTime: tomorrow.toISOString(),
}),
];
const jwt = new JWT(
'foo@serviceaccount.com',
PEM_PATH,
undefined,
['http://bar', 'http://foo'],
'bar@subjectaccount.com'
);
const impersonated = new Impersonated({
sourceClient: jwt,
targetPrincipal: 'target@project.iam.gserviceaccount.com',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
impersonated.credentials.access_token = 'initial-access-token';
impersonated.credentials.expiry_date = Date.now() - 10000;
const headers = await impersonated.getRequestHeaders();
assert.strictEqual(headers['Authorization'], 'Bearer qwerty345');
assert.strictEqual(
impersonated.credentials.expiry_date,
tomorrow.getTime()
);
scopes.forEach(s => s.done());
});
}); | the_stack |
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'fs'
import { copy } from 'fs-extra'
import { copyFile } from 'fs/promises'
import { dump } from 'js-yaml'
import { Argv } from 'yargs'
import { $, cd, nothrow } from 'zx'
import { DEPLOYMENT_PASSWORDS_SECRET } from '../common/constants'
import { decrypt, encrypt } from '../common/crypt'
import { env, isChart } from '../common/envalid'
import { hfValues } from '../common/hf'
import { getImageTag, prepareEnvironment } from '../common/setup'
import {
BasicArguments,
createK8sSecret,
generateSecrets,
getFilename,
getK8sSecret,
isCore,
loadYaml,
OtomiDebugger,
rootDir,
setParsedArgs,
terminal,
} from '../common/utils'
import { writeValues } from '../common/values'
import { genSops } from './gen-sops'
import { validateValues } from './validate-values'
const getInputValues = (): Record<string, any> | undefined => {
return loadYaml(env.VALUES_INPUT)
}
type Arguments = BasicArguments
const cmdName = getFilename(__filename)
const debug: OtomiDebugger = terminal(cmdName)
const generateLooseSchema = () => {
const devOnlyPath = `${rootDir}/.vscode/values-schema.yaml`
const targetPath = `${env.ENV_DIR}/.vscode/values-schema.yaml`
const sourcePath = `${rootDir}/values-schema.yaml`
const valuesSchema = loadYaml(sourcePath)
const trimmedVS = dump(JSON.parse(JSON.stringify(valuesSchema, (k, v) => (k === 'required' ? undefined : v), 2)))
debug.debug('generated values-schema.yaml: ', trimmedVS)
writeFileSync(targetPath, trimmedVS)
debug.info(`Stored loose YAML schema at: ${targetPath}`)
if (isCore) {
// for validation of .values/env/* files we also generate a loose schema here:
writeFileSync(devOnlyPath, trimmedVS)
debug.debug(`Stored loose YAML schema for otomi-core devs at: ${devOnlyPath}`)
}
}
const valuesOrEmpty = async (): Promise<Record<string, any> | undefined> => {
if (existsSync(`${env.ENV_DIR}/env/cluster.yaml`) && loadYaml(`${env.ENV_DIR}/env/cluster.yaml`)?.cluster?.provider)
return hfValues({ filesOnly: true })
return undefined
}
const getOtomiSecrets = async (
// The chart job calls bootstrap only if the otomi-status config map does not exists
originalValues: Record<string, any>,
): Promise<Record<string, any>> => {
let generatedSecrets: Record<string, any>
// The chart job calls bootstrap only if the otomi-status config map does not exists
const secretId = `secret/${env.DEPLOYMENT_NAMESPACE}/${DEPLOYMENT_PASSWORDS_SECRET}`
debug.info(`Checking ${secretId} already exist on cluster`)
const kubeSecretObject = await getK8sSecret(DEPLOYMENT_PASSWORDS_SECRET, env.DEPLOYMENT_NAMESPACE)
if (!kubeSecretObject) {
debug.info(`Creating ${secretId}`)
generatedSecrets = await generateSecrets(originalValues)
await createK8sSecret(DEPLOYMENT_PASSWORDS_SECRET, env.DEPLOYMENT_NAMESPACE, generatedSecrets)
debug.info(`Created ${secretId}`)
} else {
debug.info(`Found ${secretId} secrets on cluster, recovering`)
generatedSecrets = kubeSecretObject
}
return generatedSecrets
}
const bootstrapValues = async (): Promise<void> => {
const hasOtomi = existsSync(`${env.ENV_DIR}/bin/otomi`)
const binPath = `${env.ENV_DIR}/bin`
mkdirSync(binPath, { recursive: true })
const imageTag = await getImageTag()
const otomiImage = `otomi/core:${imageTag}`
debug.info(`Intalling artifacts from ${otomiImage}`)
await Promise.allSettled([
copyFile(`${rootDir}/bin/aliases`, `${binPath}/aliases`),
copyFile(`${rootDir}/binzx/otomi`, `${binPath}/otomi`),
])
debug.info('Copied bin files')
try {
mkdirSync(`${env.ENV_DIR}/.vscode`, { recursive: true })
await copy(`${rootDir}/.values/.vscode`, `${env.ENV_DIR}/.vscode`, { recursive: true })
debug.info('Copied vscode folder')
} catch (error) {
debug.error(error)
throw new Error(`Could not copy from ${rootDir}/.values/.vscode`)
}
generateLooseSchema()
await Promise.allSettled(
['.secrets.sample']
.filter((val) => !existsSync(`${env.ENV_DIR}/${val.replace(/\.sample$/g, '')}`))
.map(async (val) => copyFile(`${rootDir}/.values/${val}`, `${env.ENV_DIR}/${val}`)),
)
await Promise.allSettled(
['.gitignore', '.prettierrc.yml', 'README.md'].map(async (val) =>
copyFile(`${rootDir}/.values/${val}`, `${env.ENV_DIR}/${val}`),
),
)
if (!existsSync(`${env.ENV_DIR}/env`)) {
debug.log(`Copying basic values`)
await copy(`${rootDir}/.values/env`, `${env.ENV_DIR}/env`, { overwrite: false, recursive: true })
}
debug.log('Copying Otomi Console Setup')
mkdirSync(`${env.ENV_DIR}/docker-compose`, { recursive: true })
await copy(`${rootDir}/docker-compose`, `${env.ENV_DIR}/docker-compose`, { overwrite: true, recursive: true })
await Promise.allSettled(
['core.yaml', 'docker-compose.yml'].map((val) => copyFile(`${rootDir}/${val}`, `${env.ENV_DIR}/${val}`)),
)
let originalValues: Record<string, any>
let generatedSecrets
if (isChart) {
originalValues = getInputValues() as Record<string, any>
// store chart input values, so they can be merged with gerenerated passwords
await writeValues(originalValues)
generatedSecrets = await getOtomiSecrets(originalValues)
} else {
originalValues = (await valuesOrEmpty()) as Record<string, any>
generatedSecrets = await generateSecrets(originalValues)
}
await writeValues(generatedSecrets, false)
await genSops()
if (existsSync(`${env.ENV_DIR}/.sops.yaml`) && existsSync(`${env.ENV_DIR}/.secrets`)) {
await encrypt()
await decrypt()
}
try {
// Do not validate if CLI just bootstraps originalValues with placeholders
if (originalValues !== undefined) await validateValues()
} catch (error) {
debug.error(error)
throw new Error('Tried to bootstrap with invalid values. Please update your values and try again.')
}
// if we did not have the admin password before we know we have generated it for the first time
// so tell the user about it
if (!originalValues?.otomi?.adminPassword) {
debug.log(
'`otomi.adminPassword` has been generated and is stored in the values repository in `env/secrets.settings.yaml`',
)
}
if (existsSync(`${env.ENV_DIR}/.sops.yaml`)) {
// encryption related stuff
const file = '.gitattributes'
await copyFile(`${rootDir}/.values/${file}`, `${env.ENV_DIR}/${file}`)
// just call encrypt and let it sort out what has changed and needs encrypting
await encrypt()
}
if (!hasOtomi) {
debug.log('You can now use the otomi CLI')
}
debug.log(`Done bootstrapping values`)
}
const bootstrapGit = async (): Promise<void> => {
if (existsSync(`${env.ENV_DIR}/.git`)) {
// scenario 3: pull > bootstrap values
debug.info('Values repo already git initialized.')
} else {
// scenario 1 or 2 or 4(2 will only be called upon first otomi commit)
debug.info('Initializing values repo.')
cd(env.ENV_DIR)
const values = await valuesOrEmpty()
await $`git init ${env.ENV_DIR}`
copyFileSync(`bin/hooks/pre-commit`, `${env.ENV_DIR}/.git/hooks/pre-commit`)
const giteaEnabled = values?.charts?.gitea?.enabled ?? true
const clusterDomain = values?.cluster?.domainSuffix
const byor = !!values?.charts?.['otomi-api']?.git
if (!byor && !clusterDomain) {
debug.info('Skipping git repo configuration')
return
}
if (!giteaEnabled && !byor) {
throw new Error('Gitea was disabled but no charts.otomi-api.git config was given.')
} else if (!clusterDomain) {
debug.info('No values defined for git. Skipping git repository configuration')
return
}
let username = 'Otomi Admin'
let email: string
let password: string
let remote: string
const branch = 'main'
if (!giteaEnabled) {
const otomiApiGit = values?.charts?.['otomi-api']?.git
username = otomiApiGit?.user
password = otomiApiGit?.password
remote = otomiApiGit?.repoUrl
email = otomiApiGit?.email
} else {
username = 'otomi-admin'
password = values?.charts?.gitea?.adminPassword ?? values?.otomi?.adminPassword
email = `otomi-admin@${clusterDomain}`
const giteaUrl = `gitea.${clusterDomain}`
const giteaOrg = 'otomi'
const giteaRepo = 'values'
remote = `https://${username}:${encodeURIComponent(password)}@${giteaUrl}/${giteaOrg}/${giteaRepo}.git`
}
await $`git config --local user.name ${username}`
await $`git config --local user.password ${password}`
await $`git config --local user.email ${email}`
await $`git checkout -b ${branch}`
await $`git remote add origin ${remote}`
if (existsSync(`${env.ENV_DIR}/.sops.yaml`)) await nothrow($`git config --local diff.sopsdiffer.textconv "sops -d"`)
cd(rootDir)
debug.log(`Done bootstrapping git`)
}
}
// const notEmpty = (answer: string): boolean => answer?.trim().length > 0
// export const askBasicQuestions = async (): Promise<void> => {
// // TODO: If running this function later (when values exists) then skip questions for which the value exists
// // TODO: Parse the value schema and get defaults!
// const bootstrapWithMinimalValues = await askYesNo(
// 'To get the full otomi experience we need to get some cluster information to bootstrap the minimal viable values, do you wish to continue?',
// { defaultYes: true },
// )
// if (!bootstrapWithMinimalValues) return
// const values: any = {}
// console.log('First few questions will be about the cluster')
// values.cluster = {}
// values.cluster.owner = await ask('Who is the owner of this cluster?', { matchingFn: notEmpty })
// values.cluster.name = await ask('What is the name of this cluster?', { matchingFn: notEmpty })
// values.cluster.domainSuffix = await ask('What is the domain suffix of this cluster?', {
// matchingFn: (a: string) => notEmpty(a) && isURL(a),
// })
// values.cluster.k8sVersion = await ask('What is the kubernetes version of this cluster?', {
// matchingFn: notEmpty,
// defaultAnswer: '1.19',
// })
// values.cluster.apiServer = await ask('What is the api server of this cluster?', {
// matchingFn: (a: string) => notEmpty(a) && isURL(a),
// })
// console.log('What provider is this cluster running on?')
// values.cluster.provider = await cliSelect({
// values: ['aws', 'azure', 'google'],
// valueRenderer: (value, selected) => {
// return selected ? chalk.underline(value) : value
// },
// })
// values.cluster.region = await ask('What is the region of the provider where this cluster is running?', {
// matchingFn: notEmpty,
// })
// console.log('='.repeat(15))
// console.log('Next a few questions about otomi')
// values.otomi = {}
// values.otomi.version = await ask('What version of otomi do you want to run?', {
// matchingFn: notEmpty,
// defaultAnswer: 'master',
// })
// // values.otomi.adminPassword = await ask('What is the admin password for otomi (leave blank to generate)', {defaultAnswer: })
// // const useGitea = await askYesNo('Do you want to store the values on the cluster?', { defaultYes: true })
// // if (useGitea) {
// // // Write to env/chart/gitea.yaml: enabled = true
// // } else {
// // console.log('We need to get credentials where to store the values')
// // const repo = await ask('What is the repository url', {
// // matchingFn: async (answer: string) => {
// // const res = (await nothrow($`git ls-remote ${answer}`)).exitCode === 0
// // if (!res) console.log("It's an invalid repository, please try again.")
// // return res
// // },
// // })
// // const username = await ask('What is the repository username', {
// // matchingFn: notEmpty,
// // })
// // const password = await ask('What is the repository password', {
// // matchingFn: notEmpty,
// // })
// // const email = await ask('What is the repository email', {
// // matchingFn: (answer: string) => isEmail(answer),
// // })
// // }
// // console.log(
// // 'Please select your KMS provider for encryption. Select "none" to disable encryption. (We strongly suggest you only skip encryption for testing purposes.)',
// // )
// // const sopsProvider = await cliSelect({ values: ['none', 'aws', 'azure', 'google', 'vault'], defaultValue: 'none' })
// // const clusterName = await ask('What is the cluster name?', {
// // matchingFn: notEmpty,
// // })
// // const clusterDomain = await ask('What is the cluster domain?', {
// // matchingFn: (answer: string) => notEmpty(answer) && isURL(answer.trim()),
// // })
// }
export const module = {
command: cmdName,
hidden: true,
describe: 'Bootstrap all necessary settings and values',
builder: (parser: Argv): Argv => parser,
handler: async (argv: Arguments): Promise<void> => {
setParsedArgs(argv)
await prepareEnvironment({ skipAllPreChecks: true })
/*
We have the following scenarios:
1. chart install: assume empty env dir, so git init > bootstrap values (=load skeleton files, then merge chart values) > and commit
2. cli install: first time, so git init > bootstrap values
3. cli install: n-th time (.git exists), so pull > bootstrap values
4. chart install: n-th time. (values are stored in some git repository), so configure git, then clone values, then merge chart values) > and commit
*/
await bootstrapValues()
await decrypt()
await bootstrapGit()
},
} | the_stack |
'use strict';
import { GenericOAuth2Router } from '../common/generic-router';
import { AuthRequest, EndpointDefinition, AuthResponse, IdentityProvider, IdpOptions, SamlIdpConfig, CheckRefreshDecision, SamlAuthResponse, ErrorLink } from '../common/types';
import { OidcProfile, Callback, WickedApi } from 'wicked-sdk';
const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:saml');
const Router = require('express').Router;
const saml2 = require('wicked-saml2-js');
const mustache = require('mustache');
const qs = require('querystring');
import { utils } from '../common/utils';
import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail';
/**
* SAML OAuth2 Wrapper implementation
*/
export class SamlIdP implements IdentityProvider {
private genericFlow: GenericOAuth2Router;
private basePath: string;
private authMethodId: string;
private options: IdpOptions;
private authMethodConfig: SamlIdpConfig;
private serviceProvider: any;
private identityProvider: any;
constructor(basePath: string, authMethodId: string, authMethodConfig: any, options: IdpOptions) {
debug(`constructor(${basePath}, ${authMethodId},...)`);
this.genericFlow = new GenericOAuth2Router(basePath, authMethodId);
this.basePath = basePath;
this.authMethodId = authMethodId;
this.authMethodConfig = authMethodConfig;
this.options = options;
if (!authMethodConfig.spOptions)
throw new Error(`SAML Auth Method ${authMethodId}: config does not contain an "spOptions" property.`);
if (!authMethodConfig.idpOptions)
throw new Error(`SAML Auth Method ${authMethodId}: config does not contain an "idpOptions" property.`);
if (!authMethodConfig.profile)
throw new Error(`SAML Auth Method ${authMethodId}: config does not contain a "profile" property.`);
if (!authMethodConfig.profile.sub || !authMethodConfig.profile.email)
throw new Error(`SAML Auth Method ${authMethodId}: config of profile must contain both "sub" and "email" mappings.`);
// Assemble the SAML endpoints
const assertUrl = `${options.externalUrlBase}/${authMethodId}/assert`;
info(`SAML Authentication: Assert URL: ${assertUrl}`);
const entityUrl = `${options.externalUrlBase}/${authMethodId}/metadata.xml`;
info(`SAML Authentication: Metadata URL: ${entityUrl}`);
this.authMethodConfig.spOptions.assert_endpoint = assertUrl;
this.authMethodConfig.spOptions.entity_id = entityUrl;
this.serviceProvider = new saml2.ServiceProvider(authMethodConfig.spOptions);
this.identityProvider = new saml2.IdentityProvider(authMethodConfig.idpOptions);
this.genericFlow.initIdP(this);
}
public getType() {
return "saml";
}
public supportsPrompt(): boolean {
// This is currently not supported by saml2-js, see the following PR:
// https://github.com/Clever/saml2/pull/135
return true;
}
public getRouter() {
return this.genericFlow.getRouter();
}
/**
* In case the user isn't already authenticated, this method will
* be called from the generic flow implementation. It is assumed to
* initiate an authentication of the user by whatever means is
* suitable, depending on the actual Identity Provider implementation.
*
* If you need additional end points responding to any of your workflows,
* register them with the `endpoints()` method below.
*
* `authRequest` contains information on the authorization request,
* in case those are needed (such as for displaying information on the API
* or similar).
*/
public authorizeWithUi(req, res, next, authRequest: AuthRequest) {
debug('authorizeWithUi()');
const instance = this;
// Do your thing...
const options = {} as any;
if (authRequest.prompt == 'login') {
debug('Forcing authentication step (SAML)');
options.force_authn = true;
} else if (authRequest.prompt === 'none') {
debug('Forcing non-interactive login (SAML)');
if (!instance.options.externalUrlBase.startsWith('https')) {
// Non-interactive login is not supported if we're not using https,
// as the browsers ask the user whether it's okay to post a non-secure
// form. This cannot be answered in non-interactive mode.
error('Attempt to do non-interactive authentication over http - THIS DOES NOT WORK.');
(async () => {
await instance.genericFlow.failAuthorizeFlow(req, res, next, 'invalid_request', 'SAML2 cannot answer non-interactive requests over http. Must use https.');
})();
return;
}
options.is_passive = true;
}
this.serviceProvider.create_login_request_url(this.identityProvider, options, function (err, loginUrl, requestId) {
if (err)
return failError(500, err, next);
// Remember the request ID
authRequest.requestId = requestId;
res.redirect(loginUrl);
});
};
/**
* When a user logs out using the /logout endpoint, and the user has a SAML
* session running, also log out (SSO) with the SAML IdP. We use the redirect_uri
* from the logout as RelayState, so that we can redirect back to the /logout
* URL, which then in turn can fire off the logoutHooks for the other IdP (or e.g.
* for additional SAML IdPs).
*
* @param redirect_uri
*/
public logoutHook(req, res, next, redirect_uri: string): boolean {
debug('logoutHook()');
if (!req.session || !req.session[this.authMethodId])
return false; // Nothing to do, not logged in.
debug('Trying to SAML Logout.');
const instance = this;
try {
const authResponse = utils.getAuthResponse(req, instance.authMethodId) as SamlAuthResponse;
const options: any = {
name_id: authResponse.name_id,
session_index: authResponse.session_index
};
// Check that the identityProvider is correctly configured
if (!instance.identityProvider.sso_logout_url) {
next(makeError('The SAML configuration does not contain an sso_logout_url.', 500));
return true;
}
// Now we kill our session state.
utils.deleteSession(req, instance.authMethodId);
if (redirect_uri)
options.relay_state = Buffer.from(redirect_uri).toString('base64');
instance.serviceProvider.create_logout_request_url(
instance.identityProvider,
options,
function (err, logoutUrl) {
if (err) {
error(err);
next(err);
return;
}
debug('logoutUrl:');
debug(logoutUrl);
res.redirect(logoutUrl);
return;
}
);
// This means this method will handle returning something to res; the
// app.get(/logout) endpoint will not do anything more as of the first
// IdP returning true here.
return true;
} catch (ex) {
error(ex);
// Silently just kill all sessions, or at least this one.
return false;
}
}
public getErrorLinks(): ErrorLink {
return null;
}
/**
* In case you need additional end points to be registered, pass them
* back to the generic flow implementation here; they will be registered
* as "/<authMethodName>/<uri>", and then request will be passed into
* the handler function, which is assumed to be of the signature
* `function (req, res, next)` (the standard Express signature)
*/
public endpoints(): EndpointDefinition[] {
return [
{
method: 'get',
uri: '/metadata.xml',
handler: this.createMetadataHandler()
},
{
method: 'post',
uri: '/assert',
handler: this.createAssertHandler()
},
{
method: 'get',
uri: '/assert',
handler: this.createLogoutHandler()
}
];
};
private samlMetadata: string = null;
private createMetadataHandler() {
const instance = this;
return function (req, res, next) {
res.type('application/xml');
if (!instance.samlMetadata) {
instance.samlMetadata = instance.serviceProvider.create_metadata();
}
res.send(instance.samlMetadata);
}
}
private createAssertHandler() {
const instance = this;
return function (req, res, next) {
debug(`assertHandler()`);
const authRequest = utils.getAuthRequest(req, instance.authMethodId);
const requestId = authRequest.requestId;
if (!requestId)
return failMessage(400, 'Invalid state for SAML Assert: Request ID is not present', next);
instance.assert(req, requestId, function (err, samlResponse) {
if (err) {
error('SAML2 assert failed, error:');
error(JSON.stringify(err));
// Let's see if we can make some sense from this...
let errorMessage = 'server_error';
let errorDescription = err.message;
const responseProp = 'urn:oasis:names:tc:SAML:2.0:status:Responder'
if (err.extra && err.extra.status && err.extra.status[responseProp]
&& Array.isArray(err.extra.status[responseProp])
&& err.extra.status[responseProp].length > 0) {
switch (err.extra.status[responseProp][0]) {
case 'urn:oasis:names:tc:SAML:2.0:status:NoPassive':
errorMessage = 'login_required';
errorDescription = 'Interactive login is required'
break;
default:
errorDescription = err.extra.status[responseProp];
break;
}
}
(async () => {
await instance.genericFlow.failAuthorizeFlow(req, res, next, errorMessage, errorDescription);
})();
return;
//return failError(500, err, next);
}
debug(samlResponse);
instance.createAuthResponse(samlResponse, function (err, authResponse) {
if (err)
return next(err);
return instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
});
});
}
}
private createLogoutHandler() {
const instance = this;
return function (req, res, next) {
debug(`logoutHandler()`);
debug(req.query);
const options = {
request_body: req.query
};
const relay_state = req.query.RelayState;
instance.serviceProvider.redirect_assert(instance.identityProvider, options, function (err, response) {
if (err)
return next(err);
debug(response);
if (response.type === 'logout_request') {
// IdP initiated logout
debug('SAML: logout_request');
const in_response_to = response && response.response_header ? response.response_header.in_response_to : null;
instance.getLogoutResponseUrl(in_response_to, relay_state, function (err, redirectUrl) {
if (err)
return next(err);
info(redirectUrl);
info('Successfully logged out, deleting session state.');
utils.deleteSession(req, instance.authMethodId);
return res.redirect(redirectUrl);
});
} else if (response.type === 'logout_response') {
// Response from our logout request
debug('SAML: logout_response');
try {
// Redirect back to our own /logout
let redirect_uri = `${instance.basePath}/logout`;
if (relay_state)
redirect_uri += '?redirect_uri=' + qs.escape((new Buffer(relay_state, 'base64')).toString());
return res.redirect(redirect_uri);
} catch (ex) {
return next(ex);
}
}
});
}
}
private createAuthResponse(samlResponse, callback: Callback<AuthResponse>): void {
debug(`createAuthResponse()`);
const defaultProfile = this.buildProfile(samlResponse);
if (!defaultProfile.sub)
return callback(makeError('SAML Response did not contain a suitable ID (claim "sub" is missing/faulty in configuration?)', 400));
// Map to custom ID
const customId = `${this.authMethodId}:${defaultProfile.sub}`;
defaultProfile.sub = customId;
debug(defaultProfile);
const authResponse: SamlAuthResponse = {
userId: null,
customId: customId,
defaultProfile: defaultProfile,
defaultGroups: [],
name_id: samlResponse.user.name_id,
session_index: samlResponse.user.session_index
}
return callback(null, authResponse);
}
/**
* Verify username and password and return the data on the user, like
* when authorizing via some 3rd party. If this identity provider cannot
* authenticate via username and password, an error will be returned.
*
* @param {*} user Username
* @param {*} pass Password
* @param {*} callback Callback method, `function(err, authenticationData)`
*/
public authorizeByUserPass(user: string, pass: string, callback: Callback<AuthResponse>) {
debug('authorizeByUserPass()');
return failOAuth(400, 'unsupported_grant_type', 'SAML does not support authorizing headless with username and password', callback);
};
public checkRefreshToken(tokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) {
// Decide whether it's okay to refresh this token or not, e.g.
// by checking that the user is still valid in your database or such;
// for 3rd party IdPs, this may be tricky.
return callback(null, {
allowRefresh: true
});
};
private getLogoutResponseUrl(inResponseTo, relayState, callback) {
debug('getLogoutResponseUrl');
const instance = this;
if (!instance.identityProvider.sso_logout_url) {
return callback(makeError('The SAML configuration (identityProvider) does not contain an sso_logout_url.', 500));
}
this.serviceProvider.create_logout_response_url(
instance.identityProvider,
{ in_response_to: inResponseTo, relay_state: relayState },
function (err, logoutResponseUrl) {
if (err) {
console.error('create_logout_response_url failed.');
console.error(err);
return callback(err);
}
return callback(null, logoutResponseUrl);
}
);
}
private assert(req, requestId, callback) {
debug('assert');
if (!requestId || typeof (requestId) !== 'string')
return callback(new Error('assert needs a requestId to verify the SAML assertion.'));
const options = { request_body: req.body };
this.serviceProvider.post_assert(this.identityProvider, options, function (err, samlResponse) {
if (err) {
error('post_assert failed.');
return callback(err);
}
if (!samlResponse.response_header)
return callback(new Error('The SAML response does not have a response_header property'));
if (!samlResponse.response_header.in_response_to)
return callback(new Error('The SAML response\'s response_header does not have an in_response_to property.'));
if (samlResponse.response_header.in_response_to != requestId) {
debug('wrong request ID in SAML response, in_response_to: ' + samlResponse.response_header.in_response_to + ', requestId: ' + requestId);
return callback(new Error('The SAML assertion does not correspond to expected request ID. Please try again.'));
}
debug('samlResponse:');
debug(JSON.stringify(samlResponse, null, 2));
// const userInfo = {
// authenticated_userid: SamlIdP.findSomeId(samlResponse)
// };
callback(null, samlResponse);
});
}
// Currently not used
/*
private redirectAssert(req, callback) {
debug('redirect_assert');
if (!req.query || !req.query.SAMLRequest)
return callback(new Error('Request does not contain a SAMLRequest query parameter. Cannot parse.'));
const options = { request_body: req.query };
this.serviceProvider.redirect_assert(this.identityProvider, options, function (err, samlRequest) {
if (err) {
debug('redirect_assert failed.');
debug(err);
return callback(err);
}
if (!samlRequest.response_header)
return callback(new Error('The SAML Request does not have a response_header property'));
if (!samlRequest.response_header.id)
return callback(new Error('The SAML Request\'s response_header does not have an id property.'));
debug('samlResponse:');
debug(JSON.stringify(samlRequest, null, 2));
callback(null, samlRequest);
});
}
*/
private static getAttributeNames(samlResponse) {
const attributeNames = [];
if (samlResponse.user && samlResponse.user.attributes) {
for (let attributeName in samlResponse.user.attributes) {
attributeNames.push(attributeName.toLowerCase());
}
}
return attributeNames;
}
private static getAttributeValue(samlResponse, wantedAttribute) {
let returnValue = null;
if (samlResponse.user && samlResponse.user.attributes) {
for (let attributeName in samlResponse.user.attributes) {
if (attributeName.toLowerCase() == wantedAttribute.toLowerCase()) {
const attributeValues = samlResponse.user.attributes[attributeName];
if (Array.isArray(attributeValues) && attributeValues.length > 0) {
returnValue = attributeValues[0];
break;
} else if (isString(attributeValues)) {
returnValue = attributeValues;
break;
} else {
debug('Found attribute ' + wantedAttribute + ', but it\'s neither an array nor a string.');
}
}
}
}
return returnValue;
}
private buildProfile(samlResponse): OidcProfile {
debug('buildProfile()');
const samlConfig = this.authMethodConfig;
const profileConfig = samlConfig.profile;
const propNames = SamlIdP.getAttributeNames(samlResponse);
debug('Profile property names:');
debug(propNames);
const profileModel = {};
for (let i = 0; i < propNames.length; ++i) {
const prop = propNames[i];
profileModel[prop] = SamlIdP.getAttributeValue(samlResponse, prop);
}
// By checking that there are mappers for "sub" and "email", we can
// be sure that we can map this to an OidcProfile.
const profile = {} as OidcProfile;
for (let propName in profileConfig) {
const propConfig = profileConfig[propName];
if (isLiteral(propConfig))
profile[propName] = propConfig;
else if (isString(propConfig))
profile[propName] = mustache.render(propConfig, profileModel);
else
warn(`buildProfile: Unknown type for property name ${propName}, expected number, boolean or string (with mustache templates)`);
}
if (samlConfig.trustUsers)
profile.email_verified = true;
debug('Built profile:');
debug(profile);
return profile;
}
}
function isString(ob) {
return (ob instanceof String || typeof ob === "string");
}
function isBoolean(ob) {
return (typeof ob === 'boolean');
}
function isNumber(ob) {
return (typeof ob === 'number');
}
function isLiteral(ob) {
return isBoolean(ob) || isNumber(ob);
} | the_stack |
import {
ProviderAttribute,
ProviderReadNotifyAttribute,
ProviderReadWriteNotifyAttribute
} from "../../provider/ProviderAttribute";
/*eslint no-use-before-define: "off", no-useless-concat: "off"*/
import SubscriptionQos from "../../proxy/SubscriptionQos";
import PeriodicSubscriptionQos from "../../proxy/PeriodicSubscriptionQos";
import * as MulticastPublication from "../types/MulticastPublication";
import * as SubscriptionPublication from "../types/SubscriptionPublication";
import SubscriptionReply from "../types/SubscriptionReply";
import SubscriptionStop from "../types/SubscriptionStop";
import SubscriptionInformation from "../types/SubscriptionInformation";
import ProviderEvent from "../../provider/ProviderEvent";
import * as SubscriptionUtil from "./util/SubscriptionUtil";
import SubscriptionException from "../../exceptions/SubscriptionException";
import * as JSONSerializer from "../../util/JSONSerializer";
import LongTimer from "../../util/LongTimer";
import LoggingManager from "../../system/LoggingManager";
import Dispatcher = require("../Dispatcher");
import SubscriptionRequest = require("../types/SubscriptionRequest");
import BroadcastSubscriptionRequest = require("../types/BroadcastSubscriptionRequest");
import MulticastSubscriptionRequest = require("../types/MulticastSubscriptionRequest");
import OnChangeWithKeepAliveSubscriptionQos = require("../../proxy/OnChangeWithKeepAliveSubscriptionQos");
const log = LoggingManager.getLogger("joynr.dispatching.subscription.PublicationManager");
class PublicationManager {
private dispatcher: Dispatcher;
private started: boolean = true;
private multicastSubscriptions: Record<string, any> = {};
// map: providerId+eventName -> subscriptionIds -> subscription
private onChangeProviderEventToSubscriptions: Record<string, any> = {};
// map: providerId+attributeName -> subscriptionIds -> subscription
private onChangeProviderAttributeToSubscriptions: Record<string, any> = {};
// queued subscriptions for deferred providers
private queuedProviderParticipantIdToSubscriptionRequestsMapping: Record<string, any> = {};
// map: subscriptionId to SubscriptionRequest
private queuedSubscriptionInfos: Record<string, any> = {};
// map: subscriptionId to SubscriptionRequest
private subscriptionInfos: Record<string, any> = {};
private eventObserverFunctions: Record<string, any> = {};
private attributeObserverFunctions: Record<string, any> = {};
// map: key is the provider's participantId, value is the provider object
private participantIdToProvider: Record<string, any> = {};
/**
* The PublicationManager is responsible for handling subscription requests.
*
* @param dispatcher
*/
public constructor(dispatcher: Dispatcher) {
this.dispatcher = dispatcher;
this.triggerPublication = this.triggerPublication.bind(this);
this.removeSubscription = this.removeSubscription.bind(this);
}
private isReady(): boolean {
return this.started;
}
/**
* Helper function to get attribute object based on provider's participantId and
* attribute name
*
* @param participantId the participantId of the provider
* @param attributeName the attribute name
* @returns the provider attribute
*/
private getAttribute(participantId: string, attributeName: string): ProviderReadWriteNotifyAttribute<any> {
const provider = this.participantIdToProvider[participantId];
return provider[attributeName];
}
/**
* Helper function to get attribute value. In case the attribute getter function of
* the provider returns a promise object this function waits until the promise object
* is resolved to resolve the promise object return by this function
*
* @param subscriptionInfo the subscription information
* @param subscriptionInfo.providerParticipantId the participantId of the provider
* @param subscriptionInfo.subscribedToName the attribute to be published
* @returns an A+ promise object which provides attribute value upon success and an
* error upon failure
*/
private getAttributeValue(subscriptionInfo: {
providerParticipantId: string;
subscribedToName: string;
}): Promise<any> {
const attribute = this.getAttribute(subscriptionInfo.providerParticipantId, subscriptionInfo.subscribedToName);
return attribute.get();
}
private sendPublication(subscriptionInfo: SubscriptionInformation, value: any | undefined, exception?: any): void {
log.debug(
`send Publication for subscriptionId ${subscriptionInfo.subscriptionId} and attribute/event ${
subscriptionInfo.subscribedToName
}: ${value}`
);
subscriptionInfo.lastPublication = Date.now();
let subscriptionPublication;
if (exception) {
subscriptionPublication = SubscriptionPublication.create({
error: exception,
subscriptionId: subscriptionInfo.subscriptionId
});
} else {
subscriptionPublication = SubscriptionPublication.create({
response: value,
subscriptionId: subscriptionInfo.subscriptionId
});
}
this.dispatcher.sendPublication(
{
from: subscriptionInfo.providerParticipantId,
to: subscriptionInfo.proxyParticipantId,
expiryDate: Date.now() + subscriptionInfo.qos.publicationTtlMs
},
subscriptionPublication
);
}
private getPeriod(subscriptionInfo: SubscriptionInformation): number | undefined {
return (
(subscriptionInfo.qos as OnChangeWithKeepAliveSubscriptionQos).maxIntervalMs ||
(subscriptionInfo.qos as PeriodicSubscriptionQos).periodMs
);
}
private prepareAttributePublication(subscriptionInfo: SubscriptionInformation, value: any): void {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const timeSinceLastPublication = Date.now() - subscriptionInfo.lastPublication!;
if (
subscriptionInfo.qos.minIntervalMs === undefined ||
timeSinceLastPublication >= subscriptionInfo.qos.minIntervalMs
) {
this.sendPublication(subscriptionInfo, value);
// if registered interval exists => reschedule it
if (subscriptionInfo.onChangeDebounce !== undefined) {
LongTimer.clearTimeout(subscriptionInfo.onChangeDebounce);
delete subscriptionInfo.onChangeDebounce;
}
// if there's an existing interval, clear it and restart
if (subscriptionInfo.subscriptionInterval !== undefined) {
LongTimer.clearTimeout(subscriptionInfo.subscriptionInterval);
subscriptionInfo.subscriptionInterval = this.triggerPublicationTimer(
subscriptionInfo,
this.getPeriod(subscriptionInfo)
);
}
} else if (subscriptionInfo.onChangeDebounce === undefined) {
subscriptionInfo.onChangeDebounce = LongTimer.setTimeout(() => {
subscriptionInfo.onChangeDebounce = undefined;
this.triggerPublication(subscriptionInfo);
}, subscriptionInfo.qos.minIntervalMs - timeSinceLastPublication);
}
}
private prepareBroadcastPublication(subscriptionInfo: SubscriptionInformation, value: any): void {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const timeSinceLastPublication = Date.now() - subscriptionInfo.lastPublication!;
if (
subscriptionInfo.qos.minIntervalMs === undefined ||
timeSinceLastPublication >= subscriptionInfo.qos.minIntervalMs
) {
this.sendPublication(subscriptionInfo, value);
} else {
log.info(
`Two subsequent broadcasts of event ${
subscriptionInfo.subscribedToName
} occured within minIntervalMs of subscription with id ${
subscriptionInfo.subscriptionId
}. Event will not be sent to the subscribing client.`
);
}
}
private triggerPublication(subscriptionInfo: SubscriptionInformation): void {
this.getAttributeValue(subscriptionInfo)
.then((value: any) => this.prepareAttributePublication(subscriptionInfo, value))
.catch((exception: any) => this.sendPublication(subscriptionInfo, undefined, exception));
}
/**
* This functions waits the delay time before publishing the value of the attribute
* specified in the subscription information
*
* @param subscriptionInfo the subscription information
* @param subscriptionInfo.providerParticipantId the participantId of the provider
* @param subscriptionInfo.subscribedToName the attribute to be published
* @param delay the delay to wait for the publication
*/
private triggerPublicationTimer(
subscriptionInfo: {
providerParticipantId: string;
subscribedToName: string;
},
delay?: number
): string | number | undefined {
if (delay !== undefined) {
return LongTimer.setTimeout(this.triggerPublication, delay, subscriptionInfo);
}
}
private getProviderIdAttributeKey(providerId: string, attributeName: string): string {
return `${providerId}.${attributeName}`;
}
private getProviderIdEventKey(providerId: string, eventName: string): string {
return `${providerId}.${eventName}`;
}
/**
* Gives the list of subscriptions for the given providerId and attribute name
*
* @param providerId
* @param attributeName
* @returns a list of subscriptions
e.g. [{ participantId : "...", attributeName : "..." }]
*/
private getSubscriptionsForProviderAttribute(providerId: string, attributeName: string): Record<string, any> {
const key = this.getProviderIdAttributeKey(providerId, attributeName);
// make sure the mapping exists, so that subscriptions can register here
if (this.onChangeProviderAttributeToSubscriptions[key] === undefined) {
this.onChangeProviderAttributeToSubscriptions[key] = {};
}
return this.onChangeProviderAttributeToSubscriptions[key];
}
private resetSubscriptionsForProviderAttribute(providerId: string, attributeName: string): void {
const key = this.getProviderIdAttributeKey(providerId, attributeName);
delete this.onChangeProviderAttributeToSubscriptions[key];
}
/**
* Checks whether the provider attribute is notifiable (=is even interesting to the
* PublicationManager)
*
* @param providerAttribute the provider attribute to check for Notifiability
* @returns if the provider attribute is notifiable
*/
private providerAttributeIsNotifiable(providerAttribute: ProviderAttribute): boolean {
return typeof providerAttribute.isNotifiable === "function" && providerAttribute.isNotifiable();
}
/**
* Checks whether the provider property is an event (=is even interesting to the
* PublicationManager)
*
* @param providerProperty the provider attribute to check for Notifiability
* @returns if the provider attribute is notifiable
*/
private propertyIsProviderEvent(providerProperty: any): boolean {
return providerProperty instanceof ProviderEvent;
}
/**
* @param providerId
* @param attributeName
* @param _attribute
* @param value
*/
private publishAttributeValue(providerId: string, attributeName: string, _attribute: any, value: any): void {
if (!this.isReady()) {
throw new Error(
`attribute publication for providerId "${providerId} and attribute ${attributeName} is not forwarded to subscribers, as the publication manager is already shut down`
);
}
const subscriptions = this.getSubscriptionsForProviderAttribute(providerId, attributeName);
if (!subscriptions) {
log.error(
`ProviderAttribute ${attributeName} for providerId ${providerId} is not registered or notifiable`
);
// TODO: proper error handling for empty subscription map =>
// ProviderAttribute is not notifiable or not registered
return;
}
for (const subscriptionId in subscriptions) {
if (subscriptions.hasOwnProperty(subscriptionId)) {
const subscriptionInfo = subscriptions[subscriptionId];
this.prepareAttributePublication(subscriptionInfo, value);
}
}
}
/**
* Adds a notifiable provider attribute to the internal map if it does not exist =>
* onChange subscriptions can be registered here
*
* @param providerId
* @param attributeName
* @param attribute
*/
private addPublicationAttribute(
providerId: string,
attributeName: string,
attribute: ProviderReadWriteNotifyAttribute<any>
): void {
const key = this.getProviderIdAttributeKey(providerId, attributeName);
this.attributeObserverFunctions[key] = (value: any) => {
this.publishAttributeValue(providerId, attributeName, attribute, value);
};
attribute.registerObserver(this.attributeObserverFunctions[key]);
}
/* Broadcast specific implementation*/
/**
* Gives the list of subscriptions for the given providerId and event name
* @name PublicationManager#getSubscriptionsForProviderEvent
* @private
*
* @param providerId
* @param eventName
* @returns a list of subscriptions e.g. [{ participantId : "...", eventName : "..." }]
*/
private getSubscriptionsForProviderEvent(providerId: string, eventName: string): Record<string, any> {
const key = this.getProviderIdEventKey(providerId, eventName);
// make sure the mapping exists, so that subscriptions can register here
if (this.onChangeProviderEventToSubscriptions[key] === undefined) {
this.onChangeProviderEventToSubscriptions[key] = {};
}
return this.onChangeProviderEventToSubscriptions[key];
}
private prepareMulticastPublication(
providerId: string,
eventName: string,
partitions: any[],
outputParameters: any
): void {
const multicastId = SubscriptionUtil.createMulticastId(providerId, eventName, partitions);
const publication = MulticastPublication.create({
response: outputParameters,
multicastId
});
this.dispatcher.sendMulticastPublication(
{
from: providerId,
expiryDate: Date.now() + SubscriptionQos.DEFAULT_PUBLICATION_TTL_MS //TODO: what should be the ttl?
},
publication
);
}
/**
* @param providerId
* @param eventName
* @param event
* @param data
*/
private publishEventValue(providerId: string, eventName: string, event: ProviderEvent, data: any): void {
const value = data.broadcastOutputParameters;
if (!this.isReady()) {
throw new Error(
`event publication for providerId "${providerId} and eventName ${eventName} is not forwarded to subscribers, as the publication manager is ` +
`already shut down`
);
}
if (!event.selective) {
//handle multicast
this.prepareMulticastPublication(providerId, eventName, data.partitions, value.outputParameters);
return;
}
const subscriptions = this.getSubscriptionsForProviderEvent(providerId, eventName);
const filters = data.filters;
if (!subscriptions) {
log.error(`ProviderEvent ${eventName} for providerId ${providerId} is not registered`);
// TODO: proper error handling for empty subscription map =>
// ProviderEvent is not registered
return;
}
for (const subscriptionId in subscriptions) {
if (subscriptions.hasOwnProperty(subscriptionId)) {
const subscriptionInfo = subscriptions[subscriptionId];
// if any filters present, check them
let publish = true;
if (filters && filters.length > 0) {
for (let i = 0; i < filters.length; i++) {
if (subscriptionInfo.filterParameters && subscriptionInfo.filterParameters.filterParameters) {
publish = filters[i].filter(value, subscriptionInfo.filterParameters.filterParameters);
// stop on first filter failure
if (publish === false) {
break;
}
}
}
}
if (publish) {
this.prepareBroadcastPublication(subscriptionInfo, value.outputParameters);
}
}
}
}
/**
* Adds a provider event to the internal map if it does not exist =>
* onChange subscriptions can be registered here
*
* @param providerId
* @param eventName
* @param event
*/
private addPublicationEvent(providerId: string, eventName: string, event: ProviderEvent): void {
const key = this.getProviderIdEventKey(providerId, eventName);
this.eventObserverFunctions[key] = (data: any) => {
this.publishEventValue(providerId, eventName, event, data || {});
};
event.registerObserver(this.eventObserverFunctions[key]);
}
/* */
private resetSubscriptionsForProviderEvent(providerId: string, eventName: string): void {
const key = this.getProviderIdEventKey(providerId, eventName);
delete this.onChangeProviderEventToSubscriptions[key];
}
/* End of broadcast specific implementation*/
private addRequestToMulticastSubscriptions(multicastId: string, subscriptionId: string): void {
if (this.multicastSubscriptions[multicastId] === undefined) {
this.multicastSubscriptions[multicastId] = [];
}
const subscriptions = this.multicastSubscriptions[multicastId];
for (let i = 0; i < subscriptions.length; i++) {
if (subscriptions[i] === subscriptionId) {
return;
}
}
subscriptions.push(subscriptionId);
}
private removeRequestFromMulticastSubscriptions(multicastId: string, subscriptionId: string): void {
if (multicastId !== undefined && this.multicastSubscriptions[multicastId] !== undefined) {
let i;
for (i = 0; i < this.multicastSubscriptions[multicastId].length; i++) {
if (this.multicastSubscriptions[multicastId][i] === subscriptionId) {
this.multicastSubscriptions[multicastId].splice(i, 1);
break;
}
}
if (this.multicastSubscriptions[multicastId].length === 0) {
delete this.multicastSubscriptions[multicastId];
}
}
}
/**
* Removes a subscription, stops scheduled timers
*
* @param subscriptionId
* @param silent suppress log outputs if subscription cannot be found
*/
private removeSubscription(subscriptionId: string, silent?: boolean): void {
// make sure subscription info exists
let subscriptionInfo = this.subscriptionInfos[subscriptionId];
let pendingSubscriptions;
let pendingSubscription;
let subscriptionObject;
if (subscriptionInfo === undefined) {
if (silent !== true) {
log.warn(`no subscription info found for subscriptionId ${subscriptionId}`);
}
// TODO: proper handling for a non-existent subscription
//check if a subscriptionRequest is queued
subscriptionInfo = this.queuedSubscriptionInfos[subscriptionId];
if (subscriptionInfo === undefined) {
return;
}
pendingSubscriptions = this.queuedProviderParticipantIdToSubscriptionRequestsMapping[
subscriptionInfo.providerParticipantId
];
if (pendingSubscriptions !== undefined) {
for (pendingSubscription in pendingSubscriptions) {
if (pendingSubscriptions.hasOwnProperty(pendingSubscription)) {
subscriptionObject = pendingSubscriptions[pendingSubscription];
if (
subscriptionObject !== undefined &&
subscriptionObject.subscriptionId === subscriptionInfo.subscriptionId
) {
delete pendingSubscriptions[pendingSubscription];
}
}
}
}
delete this.queuedSubscriptionInfos[subscriptionId];
return;
}
const providerParticipantId = subscriptionInfo.providerParticipantId;
// make sure the provider exists for the given participantId
const provider = this.participantIdToProvider[providerParticipantId];
if (provider === undefined) {
log.error(`no provider found for ${providerParticipantId}`);
// TODO: proper error handling for a non-existent provider
return;
}
let subscription;
if (subscriptionInfo.subscriptionType === SubscriptionInformation.SUBSCRIPTION_TYPE_ATTRIBUTE) {
// This is an attribute subscription
const attributeName = subscriptionInfo.subscribedToName;
const attributeSubscriptions = this.getSubscriptionsForProviderAttribute(
providerParticipantId,
attributeName
);
if (attributeSubscriptions === undefined) {
log.error(
`ProviderAttribute ${attributeName} for providerId ${providerParticipantId} is not registered or notifiable`
);
// TODO: proper error handling for empty subscription map =>
// ProviderAttribute is not notifiable or not registered
return;
}
subscription = attributeSubscriptions[subscriptionId];
delete attributeSubscriptions[subscriptionId];
if (Object.keys(attributeSubscriptions).length === 0) {
this.resetSubscriptionsForProviderAttribute(providerParticipantId, attributeName);
}
} else {
// subscriptionInfo.type === SubscriptionInformation.SUBSCRIPTION_TYPE_BROADCAST
// This is a event subscription
const eventName = subscriptionInfo.subscribedToName;
// find all subscriptions for the event/providerParticipantId
const eventSubscriptions = this.getSubscriptionsForProviderEvent(providerParticipantId, eventName);
if (eventSubscriptions === undefined) {
log.error(
`ProviderEvent ${eventName} for providerId ${providerParticipantId} is not registered or notifiable`
);
// TODO: proper error handling for empty subscription map =>
return;
}
subscription = eventSubscriptions[subscriptionId];
delete eventSubscriptions[subscriptionId];
if (Object.keys(eventSubscriptions).length === 0) {
this.resetSubscriptionsForProviderEvent(providerParticipantId, eventName);
}
}
// make sure subscription exists
if (subscription === undefined) {
log.error(`no subscription found for subscriptionId ${subscriptionId}`);
// TODO: proper error handling when subscription does not exist
return;
}
// clear subscription interval if it exists
if (subscription.subscriptionInterval !== undefined) {
LongTimer.clearTimeout(subscription.subscriptionInterval);
}
// clear endDate timeout if it exists
if (subscription.endDateTimeout !== undefined) {
LongTimer.clearTimeout(subscription.endDateTimeout);
}
this.removeRequestFromMulticastSubscriptions(subscription.multicastId, subscriptionId);
delete this.subscriptionInfos[subscriptionId];
}
/**
* Removes a notifiable provider attribute from the internal map if it exists
*
* @param providerId
* @param attributeName
* @param attribute
*/
private removePublicationAttribute(
providerId: string,
attributeName: string,
attribute: ProviderReadNotifyAttribute<any>
): void {
const key = this.getProviderIdAttributeKey(providerId, attributeName);
const subscriptions = this.getSubscriptionsForProviderAttribute(providerId, attributeName);
if (subscriptions !== undefined) {
for (const subscription in subscriptions) {
if (subscriptions.hasOwnProperty(subscription)) {
this.handleSubscriptionStop(
new SubscriptionStop({
subscriptionId: subscription
})
);
}
}
this.resetSubscriptionsForProviderAttribute(providerId, attributeName);
}
attribute.unregisterObserver(this.attributeObserverFunctions[key]);
delete this.attributeObserverFunctions[key];
}
/**
* Removes a provider event from the internal map if it exists
*
* @param providerId
* @param eventName
*/
private removePublicationEvent(providerId: string, eventName: string, event: ProviderEvent): void {
const key = this.getProviderIdEventKey(providerId, eventName);
const subscriptions = this.getSubscriptionsForProviderEvent(providerId, eventName);
if (subscriptions !== undefined) {
for (const subscription in subscriptions) {
if (subscriptions.hasOwnProperty(subscription)) {
this.handleSubscriptionStop(
new SubscriptionStop({
subscriptionId: subscription
})
);
}
}
this.resetSubscriptionsForProviderEvent(providerId, eventName);
}
event.unregisterObserver(this.eventObserverFunctions[key]);
delete this.eventObserverFunctions[key];
}
/**
* the parameter "callbackDispatcher" is optional, as in case of restoring
* subscriptions, no reply must be sent back via the dispatcher
*/
private optionalCallbackDispatcher(
callbackDispatcherSettings: any,
reply: { subscriptionId: string; error?: SubscriptionException },
callbackDispatcher?: Function
): void {
if (callbackDispatcher !== undefined) {
callbackDispatcher(callbackDispatcherSettings, new SubscriptionReply(reply));
}
}
private handleBroadcastSubscriptionRequestInternal(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: BroadcastSubscriptionRequest,
callbackDispatcher: Function | undefined,
callbackDispatcherSettings: any,
multicast: boolean
): void;
private handleBroadcastSubscriptionRequestInternal(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: MulticastSubscriptionRequest,
callbackDispatcher: Function | undefined,
callbackDispatcherSettings: any,
multicast: boolean
): void;
private handleBroadcastSubscriptionRequestInternal(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: BroadcastSubscriptionRequest & MulticastSubscriptionRequest,
callbackDispatcher: Function | undefined,
callbackDispatcherSettings: any,
multicast: boolean
): void {
const requestType = `${multicast ? "multicast" : "broadcast"} subscription request`;
let exception;
let timeToEndDate = 0;
const eventName = subscriptionRequest.subscribedToName;
const subscriptionId = subscriptionRequest.subscriptionId;
// if endDate is defined (also exclude default value 0 for
// the expiryDateMs qos-property)
if (
subscriptionRequest.qos !== undefined &&
subscriptionRequest.qos.expiryDateMs !== undefined &&
subscriptionRequest.qos.expiryDateMs !== SubscriptionQos.NO_EXPIRY_DATE
) {
timeToEndDate = subscriptionRequest.qos.expiryDateMs - Date.now();
// if endDate lies in the past => don't add the subscription
if (timeToEndDate <= 0) {
exception = new SubscriptionException({
detailMessage: `error handling ${requestType}: ${JSONSerializer.stringify(
subscriptionRequest
)}. expiryDateMs ${
subscriptionRequest.qos.expiryDateMs
} for ProviderEvent ${eventName} for providerId ${providerParticipantId} lies in the past`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
}
if (!this.isReady()) {
exception = new SubscriptionException({
detailMessage: `error handling ${requestType}: ${JSONSerializer.stringify(
subscriptionRequest
)} and provider ParticipantId ${providerParticipantId}: joynr runtime already shut down`,
subscriptionId: subscriptionRequest.subscriptionId
});
log.debug(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId: subscriptionRequest.subscriptionId
},
callbackDispatcher
);
return;
}
const provider = this.participantIdToProvider[providerParticipantId];
// construct subscriptionInfo from subscriptionRequest and participantIds
const subscriptionInfo = multicast
? new SubscriptionInformation(
SubscriptionInformation.SUBSCRIPTION_TYPE_MULTICAST,
proxyParticipantId,
providerParticipantId,
subscriptionRequest
)
: new SubscriptionInformation(
SubscriptionInformation.SUBSCRIPTION_TYPE_BROADCAST,
proxyParticipantId,
providerParticipantId,
subscriptionRequest
);
// in case the subscriptionId is already used in a previous
// subscription, remove this one
this.removeSubscription(subscriptionId, true);
// make sure the provider is registered
if (provider === undefined) {
log.warn(`Provider with participantId ${providerParticipantId} not found. Queueing ${requestType}...`);
this.queuedSubscriptionInfos[subscriptionId] = subscriptionInfo;
let pendingSubscriptions = this.queuedProviderParticipantIdToSubscriptionRequestsMapping[
providerParticipantId
];
if (pendingSubscriptions === undefined) {
pendingSubscriptions = [];
this.queuedProviderParticipantIdToSubscriptionRequestsMapping[
providerParticipantId
] = pendingSubscriptions;
}
pendingSubscriptions[pendingSubscriptions.length] = subscriptionInfo;
return;
}
// make sure the provider contains the event being subscribed to
const event = provider[eventName];
if (event === undefined) {
exception = new SubscriptionException({
detailMessage: `error handling ${requestType}: ${JSONSerializer.stringify(
subscriptionRequest
)}. Provider: ${providerParticipantId} misses event ${eventName}`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
// make sure a ProviderEvent is registered
const subscriptions = this.getSubscriptionsForProviderEvent(providerParticipantId, eventName);
if (subscriptions === undefined) {
exception = new SubscriptionException({
detailMessage: `error handling ${requestType}: ${JSONSerializer.stringify(
subscriptionRequest
)}. ProviderEvent ${eventName} for providerId ${providerParticipantId} is not registered`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
if (multicast) {
const multicastId = subscriptionInfo.multicastId;
if (event.selective) {
exception = new SubscriptionException({
detailMessage: `error handling multicast subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. Provider: ${providerParticipantId} event ${eventName} is marked as selective, which is not allowed for multicasts`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.addRequestToMulticastSubscriptions(multicastId!, subscriptionId);
} else {
const checkResult = event.checkFilterParameters(subscriptionRequest.filterParameters);
if (checkResult.caughtErrors.length !== 0) {
exception = new SubscriptionException({
detailMessage: `The incoming subscription request does not contain the expected filter parameters to subscribe to broadcast ${eventName} for providerId ${providerParticipantId}: ${JSON.stringify(
checkResult.caughtErrors
)}`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
}
if (timeToEndDate > 0) {
// schedule to remove subscription from internal maps
subscriptionInfo.endDateTimeout = LongTimer.setTimeout(
this.removeSubscription,
timeToEndDate,
subscriptionId
);
}
// save subscriptionInfo to subscriptionId => subscription and
// ProviderEvent => subscription map
this.subscriptionInfos[subscriptionId] = subscriptionInfo;
subscriptions[subscriptionId] = subscriptionInfo;
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
subscriptionId
},
callbackDispatcher
);
}
/**
* @param subscriptionStop incoming subscriptionStop
*/
public handleSubscriptionStop(subscriptionStop: SubscriptionStop): void {
this.removeSubscription(subscriptionStop.subscriptionId);
}
/**
* @param providerId
* @param eventName
* @returns true if a subscription exists for the given event
*/
public hasSubscriptionsForProviderEvent(providerId: string, eventName: string): boolean {
const subscriptions = this.getSubscriptionsForProviderEvent(providerId, eventName);
let subscriptionId;
if (subscriptions !== undefined) {
for (subscriptionId in subscriptions) {
if (subscriptions.hasOwnProperty(subscriptionId)) {
return true;
}
}
}
return false;
}
/**
* @param providerId
* @param attributeName
* @returns true if a subscription exists for the given attribute
*/
public hasSubscriptionsForProviderAttribute(providerId: string, attributeName: string): boolean {
const subscriptions = this.getSubscriptionsForProviderAttribute(providerId, attributeName);
let subscriptionId;
if (subscriptions !== undefined) {
for (subscriptionId in subscriptions) {
if (subscriptions.hasOwnProperty(subscriptionId)) {
return true;
}
}
}
return false;
}
/**
* Handles SubscriptionRequests
*
* @param proxyParticipantId - participantId of proxy consuming the attribute publications
* providerParticipantId - participantId of provider producing the attribute publications
* subscriptionRequest incoming subscriptionRequest
* callbackDispatcher callback function to inform the caller about the handling result
* @param providerParticipantId
* @param subscriptionRequest
* @param callbackDispatcher
* @param callbackDispatcherSettings
* @throws {Error} when no provider exists or the provider does not have the attribute
*/
public handleSubscriptionRequest(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: SubscriptionRequest,
callbackDispatcher?: Function,
callbackDispatcherSettings?: any
): void {
let exception;
let timeToEndDate = 0;
const attributeName = subscriptionRequest.subscribedToName;
const subscriptionId = subscriptionRequest.subscriptionId;
// if endDate is defined (also exclude default value 0 for
// the expiryDateMs qos-property)
if (
subscriptionRequest.qos !== undefined &&
subscriptionRequest.qos.expiryDateMs !== undefined &&
subscriptionRequest.qos.expiryDateMs !== SubscriptionQos.NO_EXPIRY_DATE
) {
timeToEndDate = subscriptionRequest.qos.expiryDateMs - Date.now();
// if endDate lies in the past => don't add the subscription
if (timeToEndDate <= 0) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. expiryDateMs ${
subscriptionRequest.qos.expiryDateMs
} for ProviderAttribute ${attributeName} for providerId ${providerParticipantId} lies in the past`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
}
if (!this.isReady()) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)} and provider ParticipantId ${providerParticipantId}: joynr runtime already shut down`,
subscriptionId: subscriptionRequest.subscriptionId
});
log.debug(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId: subscriptionRequest.subscriptionId
},
callbackDispatcher
);
return;
}
const provider = this.participantIdToProvider[providerParticipantId];
// construct subscriptionInfo from subscriptionRequest and participantIds
const subscriptionInfo = new SubscriptionInformation(
SubscriptionInformation.SUBSCRIPTION_TYPE_ATTRIBUTE,
proxyParticipantId,
providerParticipantId,
subscriptionRequest
);
// in case the subscriptionId is already used in a previous
// subscription, remove this one
this.removeSubscription(subscriptionId, true);
// make sure the provider is registered
if (provider === undefined) {
log.info(
`Provider with participantId ${providerParticipantId} not found. Queueing subscription request...`
);
this.queuedSubscriptionInfos[subscriptionId] = subscriptionInfo;
let pendingSubscriptions = this.queuedProviderParticipantIdToSubscriptionRequestsMapping[
providerParticipantId
];
if (pendingSubscriptions === undefined) {
pendingSubscriptions = [];
this.queuedProviderParticipantIdToSubscriptionRequestsMapping[
providerParticipantId
] = pendingSubscriptions;
}
pendingSubscriptions[pendingSubscriptions.length] = subscriptionInfo;
return;
}
// make sure the provider contains the attribute being subscribed to
const attribute = provider[attributeName];
if (attribute === undefined) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. Provider: ${providerParticipantId} misses attribute ${attributeName}`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
// make sure the provider attribute is a notifiable provider attribute
// (e.g.: ProviderAttributeNotify[Read][Write])
if (!this.providerAttributeIsNotifiable(attribute)) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. Provider: ${providerParticipantId} attribute ${attributeName} is not notifiable`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
// make sure a ProviderAttribute is registered
const subscriptions = this.getSubscriptionsForProviderAttribute(providerParticipantId, attributeName);
if (subscriptions === undefined) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. ProviderAttribute ${attributeName} for providerId ${providerParticipantId} is not registered or notifiable`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
// Set up publication interval if maxIntervalMs is a number
//(not (is not a number)) ...
const periodMs = this.getPeriod(subscriptionInfo);
if (periodMs && !isNaN(periodMs)) {
if (periodMs < PeriodicSubscriptionQos.MIN_PERIOD_MS) {
exception = new SubscriptionException({
detailMessage: `error handling subscription request: ${JSONSerializer.stringify(
subscriptionRequest
)}. periodMs ${periodMs} is smaller than PeriodicSubscriptionQos.MIN_PERIOD_MS ${
PeriodicSubscriptionQos.MIN_PERIOD_MS
}`,
subscriptionId
});
log.error(exception.detailMessage);
this.optionalCallbackDispatcher(
callbackDispatcherSettings,
{
error: exception,
subscriptionId
},
callbackDispatcher
);
return;
}
}
if (timeToEndDate > 0) {
// schedule to remove subscription from internal maps
subscriptionInfo.endDateTimeout = LongTimer.setTimeout(
this.removeSubscription,
timeToEndDate,
subscriptionId
);
}
// call the get method on the provider at the set interval
subscriptionInfo.subscriptionInterval = this.triggerPublicationTimer(subscriptionInfo, periodMs);
// save subscriptionInfo to subscriptionId => subscription and
// ProviderAttribute => subscription map
this.subscriptionInfos[subscriptionId] = subscriptionInfo;
subscriptions[subscriptionId] = subscriptionInfo;
this.triggerPublication(subscriptionInfo);
this.optionalCallbackDispatcher(callbackDispatcherSettings, { subscriptionId }, callbackDispatcher);
}
/**
* Handles BroadcastSubscriptionRequests
*
* @param proxyParticipantId - participantId of proxy consuming the broadcast
* providerParticipantId - participantId of provider producing the broadcast
* subscriptionRequest incoming subscriptionRequest
* callbackDispatcher callback function to inform the caller about the handling result
* @param providerParticipantId
* @param subscriptionRequest
* @param callbackDispatcher
* @param callbackDispatcherSettings
* @throws {Error} when no provider exists or the provider does not have the event
*/
public handleBroadcastSubscriptionRequest(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: BroadcastSubscriptionRequest,
callbackDispatcher?: Function,
callbackDispatcherSettings?: any
): void {
return this.handleBroadcastSubscriptionRequestInternal(
proxyParticipantId,
providerParticipantId,
subscriptionRequest,
callbackDispatcher,
callbackDispatcherSettings,
false
);
}
/**
* Handles MulticastSubscriptionRequests
*
* @param proxyParticipantId
* @param providerParticipantId - participantId of provider producing the multicast
* subscriptionRequest incoming subscriptionRequest
* callbackDispatcher callback function to inform the caller about the handling result
* @param subscriptionRequest
* @param callbackDispatcher
* @param callbackDispatcherSettings
* @throws {Error} when no provider exists or the provider does not have the event
*/
public handleMulticastSubscriptionRequest(
proxyParticipantId: string,
providerParticipantId: string,
subscriptionRequest: MulticastSubscriptionRequest,
callbackDispatcher?: Function,
callbackDispatcherSettings?: any
): void {
return this.handleBroadcastSubscriptionRequestInternal(
proxyParticipantId,
providerParticipantId,
subscriptionRequest,
callbackDispatcher,
callbackDispatcherSettings,
true
);
}
/**
* Unregisters all attributes of a provider to handle subscription requests
*
* @param participantId of the provider handling the subsription
* @param provider
*/
public removePublicationProvider(participantId: string, provider: any): void {
if (!this.isReady()) {
throw new Error("PublicationManager is already shut down");
}
let propertyName;
// cycles over all provider members
for (propertyName in provider) {
if (provider.hasOwnProperty(propertyName)) {
// checks whether the member is a notifiable provider attribute
// and adds it if this is the case
if (this.providerAttributeIsNotifiable(provider[propertyName])) {
this.removePublicationAttribute(participantId, propertyName, provider[propertyName]);
}
// checks whether the member is an event
// and adds it if this is the case
if (this.propertyIsProviderEvent(provider[propertyName])) {
this.removePublicationEvent(participantId, propertyName, provider[propertyName]);
}
}
}
// stores the participantId to
delete this.participantIdToProvider[participantId];
}
/**
* Registers all attributes of a provider to handle subscription requests
*
* @param participantId of the provider handling the subsription
* @param provider
*/
public addPublicationProvider(participantId: string, provider: any): void {
let pendingSubscription, subscriptionObject;
if (!this.isReady()) {
throw new Error("PublicationManager is already shut down");
}
// stores the participantId to
this.participantIdToProvider[participantId] = provider;
// cycles over all provider members
for (const propertyName in provider) {
if (provider.hasOwnProperty(propertyName)) {
// checks whether the member is a notifiable provider attribute
// and adds it if this is the case
if (this.providerAttributeIsNotifiable(provider[propertyName])) {
this.addPublicationAttribute(participantId, propertyName, provider[propertyName]);
}
// checks whether the member is a event
// and adds it if this is the case
if (this.propertyIsProviderEvent(provider[propertyName])) {
this.addPublicationEvent(participantId, propertyName, provider[propertyName]);
}
}
}
const pendingSubscriptions = this.queuedProviderParticipantIdToSubscriptionRequestsMapping[participantId];
if (pendingSubscriptions !== undefined) {
for (pendingSubscription in pendingSubscriptions) {
if (pendingSubscriptions.hasOwnProperty(pendingSubscription)) {
subscriptionObject = pendingSubscriptions[pendingSubscription];
delete pendingSubscriptions[pendingSubscription];
if (subscriptionObject.subscriptionType === SubscriptionInformation.SUBSCRIPTION_TYPE_ATTRIBUTE) {
// call attribute subscription handler
this.handleSubscriptionRequest(
subscriptionObject.proxyParticipantId,
subscriptionObject.providerParticipantId,
subscriptionObject
);
} else if (
subscriptionObject.subscriptionType === SubscriptionInformation.SUBSCRIPTION_TYPE_BROADCAST
) {
this.handleBroadcastSubscriptionRequest(
subscriptionObject.proxyParticipantId,
subscriptionObject.providerParticipantId,
subscriptionObject
);
} else {
this.handleMulticastSubscriptionRequest(
subscriptionObject.proxyParticipantId,
subscriptionObject.providerParticipantId,
subscriptionObject
);
}
}
}
}
}
public hasMulticastSubscriptions(): boolean {
return Object.keys(this.multicastSubscriptions).length > 0;
}
public hasSubscriptions(): boolean {
const hasSubscriptionInfos = Object.keys(this.subscriptionInfos).length > 0;
const hasQueuedSubscriptionInfos = Object.keys(this.queuedSubscriptionInfos).length > 0;
const hasQueuedProviderParticipantIdToSubscriptionRequestsMapping =
Object.keys(this.queuedProviderParticipantIdToSubscriptionRequestsMapping).length > 0;
const hasOnChangeProviderAttributeToSubscriptions =
Object.keys(this.onChangeProviderAttributeToSubscriptions).length > 0;
const hasOnChangeProviderEventToSubscriptions =
Object.keys(this.onChangeProviderEventToSubscriptions).length > 0;
return (
hasSubscriptionInfos ||
hasQueuedSubscriptionInfos ||
hasQueuedProviderParticipantIdToSubscriptionRequestsMapping ||
hasOnChangeProviderAttributeToSubscriptions ||
hasOnChangeProviderEventToSubscriptions ||
this.hasMulticastSubscriptions()
);
}
/**
* Shutdown the publication manager
*/
public shutdown(): void {
let subscriptionId;
for (subscriptionId in this.subscriptionInfos) {
if (this.subscriptionInfos.hasOwnProperty(subscriptionId)) {
const subscriptionInfo = this.subscriptionInfos[subscriptionId];
if (subscriptionInfo.subscriptionInterval !== undefined) {
LongTimer.clearTimeout(subscriptionInfo.subscriptionInterval);
}
if (subscriptionInfo.onChangeDebounce !== undefined) {
LongTimer.clearTimeout(subscriptionInfo.onChangeDebounce);
}
}
}
this.started = false;
}
}
export = PublicationManager; | the_stack |
module txt {
export class Text extends createjs.Container{
text:string = "";
lineHeight:number = null;
width:number = 100;
height:number = 20;
align:number = txt.Align.TOP_LEFT;
characterCase:number = txt.Case.NORMAL;
size:number = 12;
font:string = "belinda";
tracking:number = 0;
ligatures:boolean = false;
fillColor:string = "#000";
strokeColor:string = null;
strokeWidth:number = null;
loaderId:number = null;
style:Style[] = null;
debug:boolean = false;
original:ConstructObj = null;
words:Word[] = [];
lines:Line[] = [];
block:createjs.Container;
missingGlyphs:any[] = null;
renderCycle:boolean = true;
//accessibility
accessibilityText:string = null;
accessibilityPriority:number = 2;
accessibilityId:number = null;
constructor( props:ConstructObj = null ){
super();
if( props ){
this.original = props;
this.set( props );
}
if( this.style == null ){
txt.FontLoader.load( this , [ this.font ] );
}else{
var fonts = [ this.font ];
var styleLength = this.style.length;
for( var i = 0; i < styleLength; ++i ){
if( this.style[ i ] != undefined ){
if( this.style[ i ].font != undefined ){
fonts.push( this.style[ i ].font );
}
}
}
txt.FontLoader.load( this , fonts );
}
}
render(){
this.getStage().update();
}
complete(){}
fontLoaded( font ){
this.layout();
}
layout(){
//accessibility api
txt.Accessibility.set( this );
this.text = this.text.replace( /([\n][ \t]+)/g , '\n' );
this.words = [];
this.lines = [];
this.missingGlyphs = null;
// TODO - remove composite layout
this.removeAllChildren();
this.block = new createjs.Container()
this.addChild( this.block );
//debug
//draw baseline, ascent, ascender, descender lines
if( this.debug == true ){
var font:txt.Font = txt.FontLoader.getFont( this.font );
//outline
var s = new createjs.Shape();
s.graphics.beginStroke( "#FF0000" );
s.graphics.setStrokeStyle( 1.2 );
s.graphics.drawRect( 0 , 0 , this.width , this.height );
this.addChild( s );
//baseline
s = new createjs.Shape();
s.graphics.beginFill( "#000" );
s.graphics.drawRect( 0 , 0 , this.width , 0.2 );
s.x = 0;
s.y = 0;
this.block.addChild( s );
s = new createjs.Shape();
s.graphics.beginFill( "#F00" );
s.graphics.drawRect( 0 , 0 , this.width , 0.2 );
s.x = 0;
s.y = -font[ 'cap-height' ] / font.units * this.size;
this.block.addChild( s );
s = new createjs.Shape();
s.graphics.beginFill( "#0F0" );
s.graphics.drawRect( 0 , 0 , this.width , 0.2 );
s.x = 0;
s.y = -font.ascent / font.units * this.size;
this.block.addChild( s );
s = new createjs.Shape();
s.graphics.beginFill( "#00F" );
s.graphics.drawRect( 0 , 0 , this.width , 0.2 );
s.x = 0;
s.y = -font.descent / font.units * this.size;
this.block.addChild( s );
}
if( this.text === "" || this.text === undefined ){
this.render();
this.complete();
return;
}
if( this.characterLayout() === false ){
this.removeAllChildren();
return;
}
if( this.renderCycle === false ){
this.removeAllChildren();
this.complete();
return;
}
this.wordLayout();
this.lineLayout();
this.render();
this.complete();
}
//place characters in words
characterLayout():boolean {
//characterlayout adds Charcters to words and measures true height. LineHeight is not a factor til Line layout.
//char layout
var len = this.text.length;
var char:Character;
var defaultStyle = {
size: this.size,
font: this.font,
tracking: this.tracking,
characterCase: this.characterCase,
fillColor: this.fillColor,
strokeColor: this.strokeColor,
strokeWidth: this.strokeWidth
};
var currentStyle = defaultStyle;
var hPosition:number = 0;
var vPosition:number = 0;
var charKern:number;
var tracking:number;
var currentWord:Word = new Word();
// push a new word to capture characters
this.words.push( currentWord );
// loop over characters
// place into words
for( var i = 0; i < len; i++ ){
if( this.style !== null && this.style[ i ] !== undefined ){
currentStyle = this.style[ i ];
// make sure style contains properties needed.
if( currentStyle.size === undefined ) currentStyle.size = defaultStyle.size;
if( currentStyle.font === undefined ) currentStyle.font = defaultStyle.font;
if( currentStyle.tracking === undefined ) currentStyle.tracking = defaultStyle.tracking;
if( currentStyle.characterCase === undefined ) currentStyle.characterCase = defaultStyle.characterCase;
if( currentStyle.fillColor === undefined ) currentStyle.fillColor = defaultStyle.fillColor;
if( currentStyle.strokeColor === undefined ) currentStyle.strokeColor = defaultStyle.strokeColor;
if( currentStyle.strokeWidth === undefined ) currentStyle.strokeWidth = defaultStyle.strokeWidth;
}
// newline
// mark word as having newline
// create new word
// new line has no character
if( this.text.charAt( i ) == "\n" ){
//only if not last char
if( i < len - 1 ){
currentWord.measuredWidth = hPosition;
currentWord.measuredHeight = vPosition;
if( currentWord.measuredHeight == 0 ){
currentWord.measuredHeight = currentStyle.size;
}
currentWord.hasNewLine = true;
currentWord = new Word();
this.words.push( currentWord );
vPosition = 0;
hPosition = 0;
}
continue;
}
//runtime test for font
if( txt.FontLoader.isLoaded( currentStyle.font ) === false ){
txt.FontLoader.load( this , [ currentStyle.font ] );
return false;
}
// create character
char = new Character( this.text.charAt( i ) , currentStyle , i );
if( this.original.character ){
if( this.original.character.added ){
char.on( 'added' , this.original.character.added );
}
if( this.original.character.click ){
char.on( 'click' , this.original.character.click );
}
if( this.original.character.dblclick ){
char.on( 'dblclick' , this.original.character.dblclick );
}
if( this.original.character.mousedown ){
char.on( 'mousedown' , this.original.character.mousedown );
}
if( this.original.character.mouseout ){
char.on( 'mouseout' , this.original.character.mouseout );
}
if( this.original.character.mouseover ){
char.on( 'mouseover' , this.original.character.mouseover );
}
if( this.original.character.pressmove ){
char.on( 'pressmove' , this.original.character.pressmove );
}
if( this.original.character.pressup ){
char.on( 'pressup' , this.original.character.pressup );
}
if( this.original.character.removed ){
char.on( 'removed' , this.original.character.removed );
}
if( this.original.character.rollout ){
char.on( 'rollout' , this.original.character.rollout );
}
if( this.original.character.rollover ){
char.on( 'rollover' , this.original.character.rollover );
}
if( this.original.character.tick ){
char.on( 'tick' , this.original.character.tick );
}
}
if( char.missing ){
if( this.missingGlyphs == null ){
this.missingGlyphs = [];
}
this.missingGlyphs.push( { position:i, character:this.text.charAt( i ), font:currentStyle.font } );
}
if( char.measuredHeight > vPosition ){
vPosition = char.measuredHeight;
}
//swap character if ligature
//ligatures removed if tracking or this.ligatures is false
if( currentStyle.tracking == 0 && this.ligatures == true ){
//1 char match
var ligTarget = this.text.substr( i , 4 );
if( char._font.ligatures[ ligTarget.charAt( 0 ) ] ){
//2 char match
if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ] ){
//3 char match
if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ] ){
//4 char match
if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ][ ligTarget.charAt( 3 ) ] ){
//swap 4 char ligature
char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ][ ligTarget.charAt( 3 ) ].glyph );
i = i+3;
}else{
//swap 3 char ligature
char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ].glyph );
i = i+2;
}
}else{
//swap 2 char ligature
char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ].glyph );
i = i+1;
}
}
}
}
char.x = hPosition;
// push character into word
currentWord.addChild( char );
// space
// mark word as having space
// create new word
// space character
if( this.text.charAt( i ) == " " ){
currentWord.hasSpace = true;
currentWord.spaceOffset = ( char._glyph.offset * char.size );
hPosition = char.x + ( char._glyph.offset * char.size ) + char.characterCaseOffset + char.trackingOffset() + char._glyph.getKerning( this.text.charCodeAt( i + 1 ) , char.size );
currentWord.measuredWidth = hPosition;
currentWord.measuredHeight = vPosition;
hPosition = 0;
vPosition = 0;
currentWord = new Word();
this.words.push( currentWord );
continue;
}
// hyphen
// mark word as having hyphen
// create new word
// space character
if( this.text.charAt( i ) == "-" ){
currentWord.hasHyphen = true;
}
hPosition = char.x + ( char._glyph.offset * char.size ) + char.characterCaseOffset + char.trackingOffset() + char._glyph.getKerning( this.text.charCodeAt( i + 1 ) , char.size );
}
//case of empty word at end.
if( currentWord.children.length == 0 ){
var lw = this.words.pop();
currentWord = this.words[ this.words.length - 1 ];
hPosition = currentWord.measuredWidth;
vPosition = currentWord.measuredHeight;
}
currentWord.measuredWidth = hPosition;
currentWord.measuredHeight = vPosition;
return true;
}
//place words in lines
wordLayout(){
// loop over words
// place into lines
var len = this.words.length;
var currentLine = new txt.Line();
this.lines.push( currentLine );
currentLine.y = 0;
var currentWord:Word;
var lastHeight:number;
this.block.addChild( currentLine );
var hPosition = 0;
var vPosition = 0;
var firstLine = true;
var lastLineWord: txt.Word;
for( var i = 0; i < len; i++ ){
currentWord = this.words[ i ];
currentWord.x = hPosition;
if( this.original.word ){
if( this.original.word.added ){
currentWord.on( 'added' , this.original.word.added );
}
if( this.original.word.click ){
currentWord.on( 'click' , this.original.word.click );
}
if( this.original.word.dblclick ){
currentWord.on( 'dblclick' , this.original.word.dblclick );
}
if( this.original.word.mousedown ){
currentWord.on( 'mousedown' , this.original.word.mousedown );
}
if( this.original.word.mouseout ){
currentWord.on( 'mouseout' , this.original.word.mouseout );
}
if( this.original.word.mouseover ){
currentWord.on( 'mouseover' , this.original.word.mouseover );
}
if( this.original.word.pressmove ){
currentWord.on( 'pressmove' , this.original.word.pressmove );
}
if( this.original.word.pressup ){
currentWord.on( 'pressup' , this.original.word.pressup );
}
if( this.original.word.removed ){
currentWord.on( 'removed' , this.original.word.removed );
}
if( this.original.word.rollout ){
currentWord.on( 'rollout' , this.original.word.rollout );
}
if( this.original.word.rollover ){
currentWord.on( 'rollover' , this.original.word.rollover );
}
if( this.original.word.tick ){
currentWord.on( 'tick' , this.original.word.tick );
}
}
if( firstLine ){
vPosition = currentWord.measuredHeight;
}else if( this.lineHeight != null ){
vPosition = this.lineHeight;
}else if( currentWord.measuredHeight > vPosition ){
vPosition = currentWord.measuredHeight;
}
//exceeds line width && has new line
if( hPosition + currentWord.measuredWidth > this.width && currentWord.hasNewLine == true && currentLine.children.length > 0 ){
if( this.lineHeight != null ){
lastHeight = currentLine.y + this.lineHeight;
}else{
lastHeight = currentLine.y + vPosition;
}
currentLine.measuredWidth = hPosition;
lastLineWord = this.words[i - 1];
if( lastLineWord != undefined && lastLineWord.hasSpace ){
currentLine.measuredWidth -= lastLineWord.spaceOffset;
}
if( firstLine == false && this.lineHeight != null ){
currentLine.measuredHeight = this.lineHeight;
}else{
currentLine.measuredHeight = vPosition;
}
firstLine = false;
currentLine = new txt.Line();
this.lines.push( currentLine );
currentLine.y = lastHeight;
hPosition = 0;
currentWord.x = 0;
this.block.addChild( currentLine );
//add word
var swapWord = this.words[ i ];
currentLine.addChild( swapWord );
if( this.lineHeight != null ){
currentLine.measuredHeight = this.lineHeight;
}else{
currentLine.measuredHeight = swapWord.measuredHeight;
}
currentLine.measuredWidth = swapWord.measuredWidth;
//add new line
currentLine = new txt.Line();
this.lines.push( currentLine );
if( this.lineHeight != null ){
currentLine.y = lastHeight + this.lineHeight;
}else{
currentLine.y = lastHeight + vPosition;
}
this.block.addChild( currentLine );
if( i < len - 1 ){
vPosition = 0;
}
continue;
}else
//wrap word to new line if length
if( hPosition + currentWord.measuredWidth > this.width && i > 0 && currentLine.children.length > 0 ){
if( this.lineHeight != null ){
lastHeight = currentLine.y + this.lineHeight;
}else{
lastHeight = currentLine.y + vPosition;
}
currentLine.measuredWidth = hPosition;
lastLineWord = this.words[ i - 1 ];
if( lastLineWord != undefined && lastLineWord.hasSpace ){
currentLine.measuredWidth -= lastLineWord.spaceOffset;
}
if( firstLine == false && this.lineHeight != null ){
currentLine.measuredHeight = this.lineHeight;
}else{
currentLine.measuredHeight = vPosition;
}
firstLine = false;
currentLine = new txt.Line();
this.lines.push( currentLine );
currentLine.y = lastHeight;
if( i < len - 1 ){
vPosition = 0;
}
hPosition = 0;
currentWord.x = hPosition;
this.block.addChild( currentLine );
}else
//wrap word to new line if newline
if( currentWord.hasNewLine == true ){
if( this.lineHeight != null ){
lastHeight = currentLine.y + this.lineHeight;
}else{
lastHeight = currentLine.y + vPosition;
}
currentLine.measuredWidth = hPosition + currentWord.measuredWidth;
if( firstLine == false && this.lineHeight != null ){
currentLine.measuredHeight = this.lineHeight;
}else{
currentLine.measuredHeight = vPosition;
}
currentLine.addChild( this.words[ i ] );
firstLine = false;
currentLine = new txt.Line();
this.lines.push( currentLine );
currentLine.y = lastHeight;
if( i < len-1 ){
vPosition = 0;
}
hPosition = 0;
this.block.addChild( currentLine );
continue;
}
hPosition = hPosition + currentWord.measuredWidth;
currentLine.addChild( this.words[ i ] );
}
//case of empty word at end.
if( currentLine.children.length == 0 ){
var lw = this.lines.pop();
currentLine = this.lines[ this.lines.length - 1 ];
}
currentLine.measuredWidth = hPosition;
currentLine.measuredHeight = vPosition;
}
lineLayout(){
// loop over lines
// place into text
var blockHeight = 0;
var measuredWidth = 0;
var measuredHeight = 0;
var line;
var a = txt.Align;
var fnt:txt.Font = txt.FontLoader.getFont( this.font );
var aHeight = this.size * fnt.ascent / fnt.units;
var cHeight = this.size * fnt[ 'cap-height' ] / fnt.units;
var xHeight = this.size * fnt[ 'x-height' ] / fnt.units;
var dHeight = this.size * fnt.descent / fnt.units;
var len = this.lines.length;
for( var i = 0; i < len; i++ ){
line = this.lines[ i ];
if( this.original.line ){
if( this.original.line.added ){
line.on( 'added' , this.original.line.added );
}
if( this.original.line.click ){
line.on( 'click' , this.original.line.click );
}
if( this.original.line.dblclick ){
line.on( 'dblclick' , this.original.line.dblclick );
}
if( this.original.line.mousedown ){
line.on( 'mousedown' , this.original.line.mousedown );
}
if( this.original.line.mouseout ){
line.on( 'mouseout' , this.original.line.mouseout );
}
if( this.original.line.mouseover ){
line.on( 'mouseover' , this.original.line.mouseover );
}
if( this.original.line.pressmove ){
line.on( 'pressmove' , this.original.line.pressmove );
}
if( this.original.line.pressup ){
line.on( 'pressup' , this.original.line.pressup );
}
if( this.original.line.removed ){
line.on( 'removed' , this.original.line.removed );
}
if( this.original.line.rollout ){
line.on( 'rollout' , this.original.line.rollout );
}
if( this.original.line.rollover ){
line.on( 'rollover' , this.original.line.rollover );
}
if( this.original.line.tick ){
line.on( 'tick' , this.original.line.tick );
}
}
//correct measuredWidth if last line character contains tracking
if( line.lastWord() != undefined && line.lastWord().lastCharacter() ){
line.measuredWidth -= line.lastWord().lastCharacter().trackingOffset();
}
measuredHeight += line.measuredHeight;
if( this.align === a.TOP_CENTER ){
//move to center
line.x = ( this.width - line.measuredWidth ) / 2;
}else if( this.align === a.TOP_RIGHT ){
//move to right
line.x = ( this.width - line.measuredWidth );
}else if( this.align === a.MIDDLE_CENTER ){
//move to center
line.x = ( this.width - line.measuredWidth ) / 2;
}else if( this.align === a.MIDDLE_RIGHT ){
//move to right
line.x = ( this.width - line.measuredWidth );
}else if( this.align === a.BOTTOM_CENTER ){
//move to center
line.x = ( this.width - line.measuredWidth ) / 2;
}else if( this.align === a.BOTTOM_RIGHT ){
//move to right
line.x = ( this.width - line.measuredWidth );
}
}
//TOP ALIGNED
if( this.align === a.TOP_LEFT || this.align === a.TOP_CENTER || this.align === a.TOP_RIGHT ){
this.block.y = this.lines[ 0 ].measuredHeight * fnt.ascent / fnt.units + this.lines[ 0 ].measuredHeight * fnt.top / fnt.units;
//MIDDLE ALIGNED
}else if( this.align === a.MIDDLE_LEFT || this.align === a.MIDDLE_CENTER || this.align === a.MIDDLE_RIGHT ){
this.block.y = this.lines[ 0 ].measuredHeight + ( this.height - measuredHeight ) / 2 + this.lines[ 0 ].measuredHeight * fnt.middle / fnt.units ;
//BOTTOM ALIGNED
}else if( this.align === a.BOTTOM_LEFT || this.align === a.BOTTOM_CENTER || this.align === a.BOTTOM_RIGHT ){
this.block.y = this.height - this.lines[ this.lines.length - 1 ].y + this.lines[ 0 ].measuredHeight* fnt.bottom / fnt.units;
}
if( this.original.block ){
if( this.original.block.added ){
this.block.on( 'added' , this.original.block.added );
}
if( this.original.block.click ){
this.block.on( 'click' , this.original.block.click );
}
if( this.original.block.dblclick ){
this.block.on( 'dblclick' , this.original.block.dblclick );
}
if( this.original.block.mousedown ){
this.block.on( 'mousedown' , this.original.block.mousedown );
}
if( this.original.block.mouseout ){
this.block.on( 'mouseout' , this.original.block.mouseout );
}
if( this.original.block.mouseover ){
this.block.on( 'mouseover' , this.original.block.mouseover );
}
if( this.original.block.pressmove ){
this.block.on( 'pressmove' , this.original.block.pressmove );
}
if( this.original.block.pressup ){
this.block.on( 'pressup' , this.original.block.pressup );
}
if( this.original.block.removed ){
this.block.on( 'removed' , this.original.block.removed );
}
if( this.original.block.rollout ){
this.block.on( 'rollout' , this.original.block.rollout );
}
if( this.original.block.rollover ){
this.block.on( 'rollover' , this.original.block.rollover );
}
if( this.original.block.tick ){
this.block.on( 'tick' , this.original.block.tick );
}
}
}
}
} | the_stack |
import { packedValue, EncodingType, FormatType } from "./custom_types";
/**
* Return type for all the *2packed functions
*/
const b64Tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const arraybuffer_error = "ARRAYBUFFER not supported by this environment";
const uint8array_error = "UINT8ARRAY not supported by this environment";
/**
* Convert a string to an array of words.
*
* There is a known bug with an odd number of existing bytes and using a UTF-16 encoding. However, this function is
* used such that the existing bytes are always a result of a previous UTF-16 str2packed call and therefore there
* should never be an odd number of existing bytes.
* @param str Unicode string to be converted to binary representation.
* @param utfType The Unicode type to use to encode the source string.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked`.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function str2packed(
str: string,
utfType: EncodingType,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let codePnt,
codePntArr,
byteCnt = 0,
i,
j,
intOffset,
byteOffset,
shiftModifier,
transposeBytes;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3;
if ("UTF8" === utfType) {
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
codePntArr = [];
if (0x80 > codePnt) {
codePntArr.push(codePnt);
} else if (0x800 > codePnt) {
codePntArr.push(0xc0 | (codePnt >>> 6));
codePntArr.push(0x80 | (codePnt & 0x3f));
} else if (0xd800 > codePnt || 0xe000 <= codePnt) {
codePntArr.push(0xe0 | (codePnt >>> 12), 0x80 | ((codePnt >>> 6) & 0x3f), 0x80 | (codePnt & 0x3f));
} else {
i += 1;
codePnt = 0x10000 + (((codePnt & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
codePntArr.push(
0xf0 | (codePnt >>> 18),
0x80 | ((codePnt >>> 12) & 0x3f),
0x80 | ((codePnt >>> 6) & 0x3f),
0x80 | (codePnt & 0x3f)
);
}
for (j = 0; j < codePntArr.length; j += 1) {
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
/* Known bug kicks in here */
packed[intOffset] |= codePntArr[j] << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 1;
}
}
} else {
/* UTF16BE or UTF16LE */
shiftModifier = bigEndianMod === -1 ? 2 : 0;
/* Internally strings are UTF-16BE so transpose bytes under two conditions:
* need LE and not switching endianness due to SHA-3
* need BE and switching endianness due to SHA-3 */
transposeBytes = ("UTF16LE" === utfType && bigEndianMod !== 1) || ("UTF16LE" !== utfType && bigEndianMod === 1);
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
if (transposeBytes === true) {
j = codePnt & 0xff;
codePnt = (j << 8) | (codePnt >>> 8);
}
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= codePnt << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 2;
}
}
return { value: packed, binLen: byteCnt * 8 + existingPackedLen };
}
/**
* Convert a hex string to an array of words.
*
* @param str Hexadecimal string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function hex2packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let i, num, intOffset, byteOffset;
if (0 !== str.length % 2) {
throw new Error("String of HEX type must be in byte increments");
}
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 2) {
num = parseInt(str.substr(i, 2), 16);
if (!isNaN(num)) {
byteOffset = (i >>> 1) + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= num << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
} else {
throw new Error("String of HEX type contains invalid characters");
}
}
return { value: packed, binLen: str.length * 4 + existingPackedLen };
}
/**
* Convert a string of raw bytes to an array of words.
*
* @param str String of raw bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function bytes2packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let codePnt, i, intOffset, byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < str.length; i += 1) {
codePnt = str.charCodeAt(i);
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= codePnt << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return { value: packed, binLen: str.length * 8 + existingPackedLen };
}
/**
* Convert a base-64 string to an array of words.
*
* @param str Base64-encoded string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function b642packed(
str: string,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let byteCnt = 0,
index,
i,
j,
tmpInt,
strPart,
intOffset,
byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0,
firstEqual = str.indexOf("=");
if (-1 === str.search(/^[a-zA-Z0-9=+/]+$/)) {
throw new Error("Invalid character in base-64 string");
}
str = str.replace(/=/g, "");
if (-1 !== firstEqual && firstEqual < str.length) {
throw new Error("Invalid '=' found in base-64 string");
}
for (i = 0; i < str.length; i += 4) {
strPart = str.substr(i, 4);
tmpInt = 0;
for (j = 0; j < strPart.length; j += 1) {
index = b64Tab.indexOf(strPart.charAt(j));
tmpInt |= index << (18 - 6 * j);
}
for (j = 0; j < strPart.length - 1; j += 1) {
byteOffset = byteCnt + existingByteLen;
intOffset = byteOffset >>> 2;
while (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |=
((tmpInt >>> (16 - j * 8)) & 0xff) << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
byteCnt += 1;
}
}
return { value: packed, binLen: byteCnt * 8 + existingPackedLen };
}
/**
* Convert an Uint8Array to an array of words.
*
* @param arr Uint8Array to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function uint8array2packed(
arr: Uint8Array,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
let i, intOffset, byteOffset;
existingPackedLen = existingPackedLen || 0;
const packed = existingPacked || [0],
existingByteLen = existingPackedLen >>> 3,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < arr.length; i += 1) {
byteOffset = i + existingByteLen;
intOffset = byteOffset >>> 2;
if (packed.length <= intOffset) {
packed.push(0);
}
packed[intOffset] |= arr[i] << (8 * (shiftModifier + bigEndianMod * (byteOffset % 4)));
}
return { value: packed, binLen: arr.length * 8 + existingPackedLen };
}
/**
* Convert an ArrayBuffer to an array of words
*
* @param arr ArrayBuffer to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Hashmap of the packed values.
*/
function arraybuffer2packed(
arr: ArrayBuffer,
existingPacked: number[] | undefined,
existingPackedLen: number | undefined,
bigEndianMod: -1 | 1
): packedValue {
return uint8array2packed(new Uint8Array(arr), existingPacked, existingPackedLen, bigEndianMod);
}
/**
* Function that takes an input format and UTF encoding and returns the appropriate function used to convert the input.
*
* @param format The format of the input to be converted
* @param utfType The string encoding to use for TEXT inputs.
* @param bigEndianMod Modifier for whether hash function is big or small endian
* @returns Function that will convert an input to a packed int array.
*/
export function getStrConverter(
format: FormatType,
utfType: EncodingType,
bigEndianMod: -1 | 1
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
): (input: any, existingBin?: number[], existingBinLen?: number) => packedValue {
/* Validate encoding */
switch (utfType) {
case "UTF8":
/* Fallthrough */
case "UTF16BE":
/* Fallthrough */
case "UTF16LE":
/* Fallthrough */
break;
default:
throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE");
}
/* Map inputFormat to the appropriate converter */
switch (format) {
case "HEX":
/**
* @param str String of hexadecimal bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return hex2packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "TEXT":
/**
* @param str Unicode string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return str2packed(str, utfType, existingBin, existingBinLen, bigEndianMod);
};
case "B64":
/**
* @param str Base64-encoded string to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return b642packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "BYTES":
/**
* @param str String of raw bytes to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (str: string, existingBin?: number[], existingBinLen?: number): packedValue {
return bytes2packed(str, existingBin, existingBinLen, bigEndianMod);
};
case "ARRAYBUFFER":
try {
new ArrayBuffer(0);
} catch (ignore) {
throw new Error(arraybuffer_error);
}
/**
* @param arr ArrayBuffer to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (arr: ArrayBuffer, existingBin?: number[], existingBinLen?: number): packedValue {
return arraybuffer2packed(arr, existingBin, existingBinLen, bigEndianMod);
};
case "UINT8ARRAY":
try {
new Uint8Array(0);
} catch (ignore) {
throw new Error(uint8array_error);
}
/**
* @param arr Uint8Array to be converted to binary representation.
* @param existingPacked A packed int array of bytes to append the results to.
* @param existingPackedLen The number of bits in `existingPacked` array.
* @returns Hashmap of the packed values.
*/
return function (arr: Uint8Array, existingBin?: number[], existingBinLen?: number): packedValue {
return uint8array2packed(arr, existingBin, existingBinLen, bigEndianMod);
};
default:
throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
}
}
/**
* Convert an array of words to a hexadecimal string.
*
* toString() won't work here because it removes preceding zeros (e.g. 0x00000001.toString === "1" rather than
* "00000001" and 0.toString(16) === "0" rather than "00").
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param formatOpts Hashmap containing validated output formatting options.
* @returns Hexadecimal representation of `packed`.
*/
export function packed2hex(
packed: number[],
outputLength: number,
bigEndianMod: -1 | 1,
formatOpts: { outputUpper: boolean; b64Pad: string }
): string {
const hex_tab = "0123456789abcdef";
let str = "",
i,
srcByte;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
/* The below is more than a byte but it gets taken care of later */
srcByte = packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)));
str += hex_tab.charAt((srcByte >>> 4) & 0xf) + hex_tab.charAt(srcByte & 0xf);
}
return formatOpts["outputUpper"] ? str.toUpperCase() : str;
}
/**
* Convert an array of words to a base-64 string.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param formatOpts Hashmap containing validated output formatting options.
* @returns Base64-encoded representation of `packed`.
*/
export function packed2b64(
packed: number[],
outputLength: number,
bigEndianMod: -1 | 1,
formatOpts: { outputUpper: boolean; b64Pad: string }
): string {
let str = "",
i,
j,
triplet,
int1,
int2;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 3) {
int1 = i + 1 < length ? packed[(i + 1) >>> 2] : 0;
int2 = i + 2 < length ? packed[(i + 2) >>> 2] : 0;
triplet =
(((packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff) << 16) |
(((int1 >>> (8 * (shiftModifier + bigEndianMod * ((i + 1) % 4)))) & 0xff) << 8) |
((int2 >>> (8 * (shiftModifier + bigEndianMod * ((i + 2) % 4)))) & 0xff);
for (j = 0; j < 4; j += 1) {
if (i * 8 + j * 6 <= outputLength) {
str += b64Tab.charAt((triplet >>> (6 * (3 - j))) & 0x3f);
} else {
str += formatOpts["b64Pad"];
}
}
}
return str;
}
/**
* Convert an array of words to raw bytes string.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns Raw bytes representation of `packed`.
*/
export function packed2bytes(packed: number[], outputLength: number, bigEndianMod: -1 | 1): string {
let str = "",
i,
srcByte;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
srcByte = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
str += String.fromCharCode(srcByte);
}
return str;
}
/**
* Convert an array of words to an ArrayBuffer.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns An ArrayBuffer containing bytes from `packed.
*/
export function packed2arraybuffer(packed: number[], outputLength: number, bigEndianMod: -1 | 1): ArrayBuffer {
let i;
const length = outputLength / 8,
retVal = new ArrayBuffer(length),
arrView = new Uint8Array(retVal),
shiftModifier = bigEndianMod === -1 ? 3 : 0;
for (i = 0; i < length; i += 1) {
arrView[i] = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
}
return retVal;
}
/**
* Convert an array of words to an Uint8Array.
*
* @param packed Array of integers to be converted.
* @param outputLength Length of output in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @returns An Uint8Array containing bytes from `packed.
*/
export function packed2uint8array(packed: number[], outputLength: number, bigEndianMod: -1 | 1): Uint8Array {
let i;
const length = outputLength / 8,
shiftModifier = bigEndianMod === -1 ? 3 : 0,
retVal = new Uint8Array(length);
for (i = 0; i < length; i += 1) {
retVal[i] = (packed[i >>> 2] >>> (8 * (shiftModifier + bigEndianMod * (i % 4)))) & 0xff;
}
return retVal;
}
/**
* Function that takes an output format and associated parameters and returns a function that converts packed integers
* to that format.
*
* @param format The desired output formatting.
* @param outputBinLen Output length in bits.
* @param bigEndianMod Modifier for whether hash function is big or small endian.
* @param outputOptions Hashmap of output formatting options
* @returns Function that will convert a packed integer array to desired format.
*/
export function getOutputConverter(
format: "HEX" | "B64" | "BYTES" | "ARRAYBUFFER" | "UINT8ARRAY",
outputBinLen: number,
bigEndianMod: -1 | 1,
outputOptions: { outputUpper: boolean; b64Pad: string }
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
): (binarray: number[]) => any {
switch (format) {
case "HEX":
return function (binarray): string {
return packed2hex(binarray, outputBinLen, bigEndianMod, outputOptions);
};
case "B64":
return function (binarray): string {
return packed2b64(binarray, outputBinLen, bigEndianMod, outputOptions);
};
case "BYTES":
return function (binarray): string {
return packed2bytes(binarray, outputBinLen, bigEndianMod);
};
case "ARRAYBUFFER":
try {
/* Need to test ArrayBuffer support */
new ArrayBuffer(0);
} catch (ignore) {
throw new Error(arraybuffer_error);
}
return function (binarray): ArrayBuffer {
return packed2arraybuffer(binarray, outputBinLen, bigEndianMod);
};
case "UINT8ARRAY":
try {
/* Need to test Uint8Array support */
new Uint8Array(0);
} catch (ignore) {
throw new Error(uint8array_error);
}
return function (binarray): Uint8Array {
return packed2uint8array(binarray, outputBinLen, bigEndianMod);
};
default:
throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY");
}
} | the_stack |
import * as t from 'io-ts';
import { RTTI_id } from '../Scalar/RTTI_id';
import { RTTI_Meta, IMeta } from './RTTI_Meta';
import { RTTI_uri } from '../Scalar/RTTI_uri';
import { RTTI_Element, IElement } from './RTTI_Element';
import { RTTI_code } from '../Scalar/RTTI_code';
import { RTTI_Narrative, INarrative } from './RTTI_Narrative';
import { RTTI_ResourceList, IResourceList } from '../Union/RTTI_ResourceList';
import { RTTI_Extension, IExtension } from './RTTI_Extension';
import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier';
import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept';
import { RTTI_Reference, IReference } from './RTTI_Reference';
import { RTTI_dateTime } from '../Scalar/RTTI_dateTime';
import { RTTI_canonical } from '../Scalar/RTTI_canonical';
import { RTTI_Annotation, IAnnotation } from './RTTI_Annotation';
import { RTTI_Dosage, IDosage } from './RTTI_Dosage';
import {
RTTI_MedicationRequest_DispenseRequest,
IMedicationRequest_DispenseRequest
} from './RTTI_MedicationRequest_DispenseRequest';
import {
RTTI_MedicationRequest_Substitution,
IMedicationRequest_Substitution
} from './RTTI_MedicationRequest_Substitution';
import { IDomainResource } from './IDomainResource';
export interface IMedicationRequest extends IDomainResource {
/**
* This is a MedicationRequest resource
*/
resourceType: 'MedicationRequest';
/**
* A link to a resource representing the person or set of individuals to whom the medication will be given.
*/
subject: IReference;
/**
* The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes.
*/
id?: string;
/**
* The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource.
*/
meta?: IMeta;
/**
* A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc.
*/
implicitRules?: string;
/**
* Extensions for implicitRules
*/
_implicitRules?: IElement;
/**
* The base language in which the resource is written.
*/
language?: string;
/**
* Extensions for language
*/
_language?: IElement;
/**
* A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety.
*/
text?: INarrative;
/**
* These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope.
*/
contained?: IResourceList[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.
*/
extension?: IExtension[];
/**
* May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.
Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).
*/
modifierExtension?: IExtension[];
/**
* Identifiers associated with this medication request that are defined by business processes and/or used to refer to it when a direct URL reference to the resource itself is not appropriate. They are business identifiers assigned to this resource by the performer or other systems and remain constant as the resource is updated and propagates from server to server.
*/
identifier?: IIdentifier[];
/**
* A code specifying the current state of the order. Generally, this will be active or completed state.
*/
status?: string;
/**
* Extensions for status
*/
_status?: IElement;
/**
* Captures the reason for the current state of the MedicationRequest.
*/
statusReason?: ICodeableConcept;
/**
* Whether the request is a proposal, plan, or an original order.
*/
intent?: string;
/**
* Extensions for intent
*/
_intent?: IElement;
/**
* Indicates the type of medication request (for example, where the medication is expected to be consumed or administered (i.e. inpatient or outpatient)).
*/
category?: ICodeableConcept[];
/**
* Indicates how quickly the Medication Request should be addressed with respect to other requests.
*/
priority?: string;
/**
* Extensions for priority
*/
_priority?: IElement;
/**
* If true indicates that the provider is asking for the medication request not to occur.
*/
doNotPerform?: boolean;
/**
* Extensions for doNotPerform
*/
_doNotPerform?: IElement;
/**
* Indicates if this record was captured as a secondary 'reported' record rather than as an original primary source-of-truth record. It may also indicate the source of the report.
*/
reportedBoolean?: boolean;
/**
* Extensions for reportedBoolean
*/
_reportedBoolean?: IElement;
/**
* Indicates if this record was captured as a secondary 'reported' record rather than as an original primary source-of-truth record. It may also indicate the source of the report.
*/
reportedReference?: IReference;
/**
* Identifies the medication being requested. This is a link to a resource that represents the medication which may be the details of the medication or simply an attribute carrying a code that identifies the medication from a known list of medications.
*/
medicationCodeableConcept?: ICodeableConcept;
/**
* Identifies the medication being requested. This is a link to a resource that represents the medication which may be the details of the medication or simply an attribute carrying a code that identifies the medication from a known list of medications.
*/
medicationReference?: IReference;
/**
* The Encounter during which this [x] was created or to which the creation of this record is tightly associated.
*/
encounter?: IReference;
/**
* Include additional information (for example, patient height and weight) that supports the ordering of the medication.
*/
supportingInformation?: IReference[];
/**
* The date (and perhaps time) when the prescription was initially written or authored on.
*/
authoredOn?: string;
/**
* Extensions for authoredOn
*/
_authoredOn?: IElement;
/**
* The individual, organization, or device that initiated the request and has responsibility for its activation.
*/
requester?: IReference;
/**
* The specified desired performer of the medication treatment (e.g. the performer of the medication administration).
*/
performer?: IReference;
/**
* Indicates the type of performer of the administration of the medication.
*/
performerType?: ICodeableConcept;
/**
* The person who entered the order on behalf of another individual for example in the case of a verbal or a telephone order.
*/
recorder?: IReference;
/**
* The reason or the indication for ordering or not ordering the medication.
*/
reasonCode?: ICodeableConcept[];
/**
* Condition or observation that supports why the medication was ordered.
*/
reasonReference?: IReference[];
/**
* The URL pointing to a protocol, guideline, orderset, or other definition that is adhered to in whole or in part by this MedicationRequest.
*/
instantiatesCanonical?: string[];
/**
* Extensions for instantiatesCanonical
*/
_instantiatesCanonical?: IElement[];
/**
* The URL pointing to an externally maintained protocol, guideline, orderset or other definition that is adhered to in whole or in part by this MedicationRequest.
*/
instantiatesUri?: string[];
/**
* Extensions for instantiatesUri
*/
_instantiatesUri?: IElement[];
/**
* A plan or request that is fulfilled in whole or in part by this medication request.
*/
basedOn?: IReference[];
/**
* A shared identifier common to all requests that were authorized more or less simultaneously by a single author, representing the identifier of the requisition or prescription.
*/
groupIdentifier?: IIdentifier;
/**
* The description of the overall patte3rn of the administration of the medication to the patient.
*/
courseOfTherapyType?: ICodeableConcept;
/**
* Insurance plans, coverage extensions, pre-authorizations and/or pre-determinations that may be required for delivering the requested service.
*/
insurance?: IReference[];
/**
* Extra information about the prescription that could not be conveyed by the other attributes.
*/
note?: IAnnotation[];
/**
* Indicates how the medication is to be used by the patient.
*/
dosageInstruction?: IDosage[];
/**
* Indicates the specific details for the dispense or medication supply part of a medication request (also known as a Medication Prescription or Medication Order). Note that this information is not always sent with the order. There may be in some settings (e.g. hospitals) institutional or system support for completing the dispense details in the pharmacy department.
*/
dispenseRequest?: IMedicationRequest_DispenseRequest;
/**
* Indicates whether or not substitution can or should be part of the dispense. In some cases, substitution must happen, in other cases substitution must not happen. This block explains the prescriber's intent. If nothing is specified substitution may be done.
*/
substitution?: IMedicationRequest_Substitution;
/**
* A link to a resource representing an earlier order related order or prescription.
*/
priorPrescription?: IReference;
/**
* Indicates an actual or potential clinical issue with or between one or more active or proposed clinical actions for a patient; e.g. Drug-drug interaction, duplicate therapy, dosage alert etc.
*/
detectedIssue?: IReference[];
/**
* Links to Provenance records for past versions of this resource or fulfilling request or event resources that identify key state transitions or updates that are likely to be relevant to a user looking at the current version of the resource.
*/
eventHistory?: IReference[];
}
export const RTTI_MedicationRequest: t.Type<IMedicationRequest> = t.recursion(
'IMedicationRequest',
() =>
t.intersection([
t.type({
resourceType: t.literal('MedicationRequest'),
subject: RTTI_Reference
}),
t.partial({
id: RTTI_id,
meta: RTTI_Meta,
implicitRules: RTTI_uri,
_implicitRules: RTTI_Element,
language: RTTI_code,
_language: RTTI_Element,
text: RTTI_Narrative,
contained: t.array(RTTI_ResourceList),
extension: t.array(RTTI_Extension),
modifierExtension: t.array(RTTI_Extension),
identifier: t.array(RTTI_Identifier),
status: RTTI_code,
_status: RTTI_Element,
statusReason: RTTI_CodeableConcept,
intent: RTTI_code,
_intent: RTTI_Element,
category: t.array(RTTI_CodeableConcept),
priority: RTTI_code,
_priority: RTTI_Element,
doNotPerform: t.boolean,
_doNotPerform: RTTI_Element,
reportedBoolean: t.boolean,
_reportedBoolean: RTTI_Element,
reportedReference: RTTI_Reference,
medicationCodeableConcept: RTTI_CodeableConcept,
medicationReference: RTTI_Reference,
encounter: RTTI_Reference,
supportingInformation: t.array(RTTI_Reference),
authoredOn: RTTI_dateTime,
_authoredOn: RTTI_Element,
requester: RTTI_Reference,
performer: RTTI_Reference,
performerType: RTTI_CodeableConcept,
recorder: RTTI_Reference,
reasonCode: t.array(RTTI_CodeableConcept),
reasonReference: t.array(RTTI_Reference),
instantiatesCanonical: t.array(RTTI_canonical),
_instantiatesCanonical: t.array(RTTI_Element),
instantiatesUri: t.array(RTTI_uri),
_instantiatesUri: t.array(RTTI_Element),
basedOn: t.array(RTTI_Reference),
groupIdentifier: RTTI_Identifier,
courseOfTherapyType: RTTI_CodeableConcept,
insurance: t.array(RTTI_Reference),
note: t.array(RTTI_Annotation),
dosageInstruction: t.array(RTTI_Dosage),
dispenseRequest: RTTI_MedicationRequest_DispenseRequest,
substitution: RTTI_MedicationRequest_Substitution,
priorPrescription: RTTI_Reference,
detectedIssue: t.array(RTTI_Reference),
eventHistory: t.array(RTTI_Reference)
})
])
); | the_stack |
import IPython = require('base/js/namespace');
import $ = require('jquery');
import gapiutils = require('./gapiutils');
import pickerutils = require('./pickerutils');
import iface = require('content-interface');
import Path = iface.Path
export var FOLDER_MIME_TYPE = 'application/vnd.google-apps.folder';
export var NOTEBOOK_MIMETYPE = 'application/ipynb';
export var MULTIPART_BOUNDARY = '-------314159265358979323846';
declare var gapi;
export enum FileType {FILE=1, FOLDER=2}
/**
* Obtains the Google Drive Files resource for a file or folder relative
* to the a given folder. The path should be a file or a subfolder, and
* should not contain multiple levels of folders (hence the name
* path_component). It should also not contain any leading or trailing
* slashes.
*
* @param {String} path_component The file/folder to find
* @param {FileType} type type of resource (file or folder)
* @param {boolean} opt_child_resource If True, fetches a child resource
* which is smaller and probably quicker to obtain the a Files resource.
* @param {String} folder_id The Google Drive folder id
* @return A promise fullfilled by either the files resource for the given
* file/folder, or rejected with an Error object.
*/
export var get_resource_for_relative_path = function(path_component:String, type:FileType, opt_child_resource:Boolean, folder_id:String): Promise<any> {
var query = 'title = \'' + path_component + '\' and trashed = false ';
if (type == FileType.FOLDER) {
query += ' and mimeType = \'' + FOLDER_MIME_TYPE + '\'';
}
var request = null;
if (opt_child_resource) {
request = gapi.client.drive.children.list({'q': query, 'folderId' : folder_id});
} else {
query += ' and \'' + folder_id + '\' in parents';
request = gapi.client.drive.files.list({'q': query});
}
return gapiutils.execute(request)
.then(function(response) {
var files = response['items'];
if (!files || files.length == 0) {
var error = new Error('The specified file/folder did not exist: ' + path_component);
error.name = 'NotFoundError';
throw error;
}
if (files.length > 1) {
var error = new Error('Multiple files/folders with the given name existed: ' + path_component);
error.name = 'BadNameError';
throw error;
}
return files[0];
});
};
/**
* Split a path into path components
*/
export var split_path = function(path:Path):Path[] {
return path.split('/').filter((s,i,a) => (Boolean(s)));
};
/**
* Gets the Google Drive Files resource corresponding to a path. The path
* is always treated as an absolute path, no matter whether it contains
* leading or trailing slashes. In fact, all leading, trailing and
* consecutive slashes are ignored.
*
* @param {String} path The path
* @param {FileType} type The type (file or folder)
* @return {Promise} fullfilled with file/folder id (string) on success
* or Error object on error.
*/
export var get_resource_for_path = function(path:Path, type?) {
var components = split_path(path);
if (components.length == 0) {
return gapiutils.execute(gapi.client.drive.about.get())
.then(function(resource) {
var id = resource['rootFolderId'];
var request = gapi.client.drive.files.get({ 'fileId': id });
return gapiutils.execute(request);
});
}
var result = Promise.resolve({id: 'root'});
for (var i = 0; i < components.length; i++) {
var component = components[i];
var t = (i == components.length - 1) ? type : FileType.FOLDER;
var child_resource = i < components.length - 1;
// IIFE or, component`, `t`, `child_resources` get shared in
// between Promises
result = ((component:String, t:FileType, child_resource:Boolean, result) => {
return result.then((data) => {
return get_resource_for_relative_path(component, t, child_resource, data['id'])
}
);
})(component, t, child_resource, result)
};
return result;
}
/**
* Gets the Google Drive file/folder ID for a file or folder. The path is
* always treated as an absolute path, no matter whether it contains leading
* or trailing slashes. In fact, all leading, trailing and consecutive
* slashes are ignored.
*
* @param {String} path The path
* @param {FileType} type The type (file or folder)
* @return {Promise} fullfilled with folder id (string) on success
* or Error object on error.
*/
export var get_id_for_path = function(path, type?) {
var components = split_path(path);
if (components.length == 0) {
return $.Deferred().resolve('root');
}
return get_resource_for_path(path, type)
.then(function(resource) { return resource['id']; });
}
/**
* Obtains the filename that should be used for a new file in a given
* folder. This is the next file in the series Untitled0, Untitled1, ... in
* the given drive folder. As a fallback, returns Untitled.
*
* @method get_new_filename
* @param {function(string)} callback Called with the name for the new file.
* @param {string} opt_folderId optinal Drive folder Id to search for
* filenames. Uses root, if none is specified.
* @param {string} ext The extension to use
* @param {string} base_name The base name of the file
* @return A promise fullfilled with the new filename. In case of errors,
* 'Untitled.ipynb' is used as a fallback.
*/
export var get_new_filename = function(opt_folderId, ext, base_name) {
/** @type {string} */
var folderId = opt_folderId || 'root';
var query = 'title contains \'' + base_name + '\'' +
' and \'' + folderId + '\' in parents' +
' and trashed = false';
var request = gapi.client.drive.files.list({
'maxResults': 1000,
'folderId' : folderId,
'q': query
});
var fallbackFilename = base_name + ext;
return gapiutils.execute(request)
.then(function(response) {
// Use 'Untitled.ipynb' as a fallback in case of error
var files = response['items'] || [];
var existingFilenames = $.map(files, function(filesResource) {
return filesResource['title'];
});
// Loop over file names Untitled0, ... , UntitledN where N is the number of
// elements in existingFilenames. Select the first file name that does not
// belong to existingFilenames. This is guaranteed to find a file name
// that does not belong to existingFilenames, since there are N + 1 file
// names tried, and existingFilenames contains N elements.
for (var i = 0; i <= existingFilenames.length; i++) {
/** @type {string} */
var filename = base_name + i + ext;
if (existingFilenames.indexOf(filename) == -1) {
return filename;
}
}
// Control should not reach this point, so an error has occured
return fallbackFilename;
})
.catch(function(error) { return Promise.resolve(fallbackFilename); });
};
/**
* Uploads a notebook to Drive, either creating a new one or saving an
* existing one.
*
* @method upload_to_drive
* @param {string} data The file contents as a string
* @param {Object} metadata File metadata
* @param {string=} opt_fileId file Id. If false, a new file is created.
* @param {Object?} opt_params a dictionary containing the following keys
* pinned: whether this save should be pinned
* @return {Promise} A promise resolved with the Google Drive Files
* resource for the uploaded file, or rejected with an Error object.
*/
export var upload_to_drive = function(data, metadata, opt_fileId?, opt_params?: any) {
var params:Object = opt_params || {};
var delimiter = '\r\n--' + MULTIPART_BOUNDARY + '\r\n';
var close_delim = '\r\n--' + MULTIPART_BOUNDARY + '--';
var body = delimiter +
'Content-Type: application/json\r\n\r\n';
var mime;
if (metadata) {
mime = metadata.mimeType;
body += JSON.stringify(metadata);
}
body += delimiter;
if (mime) {
body += 'Content-Type: ' + mime + '\r\n';
if (mime === 'application/octet-stream') {
body += 'Content-Transfer-Encoding: base64\r\n';
}
}
body +='\r\n' +
data +
close_delim;
var path = '/upload/drive/v2/files';
var method = 'POST';
if (opt_fileId) {
path += '/' + opt_fileId;
method = 'PUT';
}
var request = gapi.client.request({
'path': path,
'method': method,
'params': {
'uploadType': 'multipart',
'pinned' : params['pinned']
},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' +
MULTIPART_BOUNDARY + '"'
},
'body': body
});
return gapiutils.execute(request);
};
export var GET_CONTENTS_INITIAL_DELAY = 200; // 200 ms
export var GET_CONTENTS_MAX_TRIES = 5;
export var GET_CONTENTS_EXPONENTIAL_BACKOFF_FACTOR = 2.0;
/**
* Attempt to get the contents of a file with the given id. This may
* involve requesting the user to open the file in a FilePicker.
* @param {Object} resource The files resource of the file.
* @param {Boolean} already_picked Set to true if this file has already
* been selected by the FilePicker
* @param {Number?} opt_num_tries The number tries left to open this file.
* Should be set when already_picked is true.
* @return {Promise} A promise fullfilled by file contents.
*/
export var get_contents = function(resource, already_picked:boolean, opt_num_tries?) {
if (resource['downloadUrl']) {
return gapiutils.download(resource['downloadUrl']);
} else if (already_picked) {
if (opt_num_tries == 0) {
return Promise.reject(new Error('Max retries of file load reached'));
}
var request = gapi.client.drive.files.get({ 'fileId': resource['id'] });
var reply = gapiutils.execute(request);
var delay = GET_CONTENTS_INITIAL_DELAY *
Math.pow(GET_CONTENTS_EXPONENTIAL_BACKOFF_FACTOR, GET_CONTENTS_MAX_TRIES - opt_num_tries);
var delayed_reply = new Promise(function(resolve, reject) {
window.setTimeout(function() {
resolve(reply);
}, delay);
});
return delayed_reply.then(function(new_resource) {
return get_contents(new_resource, true, opt_num_tries - 1);
});
} else {
// If downloadUrl field is missing, this means that we do not have
// access to the file using drive.file scope. Therefore we prompt
// the user to open a FilePicker window that allows them to indicate
// to Google Drive that they intend to open that file with this
// app.
return pickerutils.pick_file(resource.parents[0]['id'], resource['title'])
.then(function() {
return get_contents(resource, true, GET_CONTENTS_MAX_TRIES);
});
}
};
/**
* Fetch user avatar url and put it in the header
* optionally take a selector into which to insert the img tag
*
*
*
**/
export var set_user_info = function(selector:string):Promise<any>{
selector = selector || '#header-container';
var request = gapi.client.drive.about.get()
return gapiutils.execute(request).then(function(result){
var user = result.user;
var image = $('<img/>').attr('src', result.user.picture.url)
.addClass('pull-right')
.css('border-radius','32px')
.css('width','32px')
.css('margin-top','-1px')
.css('margin-bottom','-1px');
image.attr('title', 'Logged in to Google Drive as '+user.displayName);
$('#header-container').prepend($('<span/>').append(image));
})
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormCustomer_Asset {
interface tab__B3F36061_1F16_4BBB_BD74_44FAC42C9094_Sections {
_216040C1_499B_4120_8175_2EFB7536E940: DevKit.Controls.Section;
_576663BB_EA91_486D_8F88_DA4CD98DF0EB: DevKit.Controls.Section;
_B3F36061_1F16_4BBB_BD74_44FAC42C9094_SECTION_3: DevKit.Controls.Section;
_B3F36061_1F16_4BBB_BD74_44FAC42C9094_SECTION_7: DevKit.Controls.Section;
Asset_WorkOrder: DevKit.Controls.Section;
Connected_Device_Readings: DevKit.Controls.Section;
ConnectedDeviceAttributes: DevKit.Controls.Section;
Device_Summary_Visualization: DevKit.Controls.Section;
fstab_summary_location: DevKit.Controls.Section;
knowledgesection: DevKit.Controls.Section;
}
interface tab_AlertsTab_Sections {
AlertsSection: DevKit.Controls.Section;
}
interface tab_CommandsTab_Sections {
CommandsSection: DevKit.Controls.Section;
}
interface tab_DeviceInsightsTab_Sections {
DeviceInsightsSection: DevKit.Controls.Section;
}
interface tab__B3F36061_1F16_4BBB_BD74_44FAC42C9094 extends DevKit.Controls.ITab {
Section: tab__B3F36061_1F16_4BBB_BD74_44FAC42C9094_Sections;
}
interface tab_AlertsTab extends DevKit.Controls.ITab {
Section: tab_AlertsTab_Sections;
}
interface tab_CommandsTab extends DevKit.Controls.ITab {
Section: tab_CommandsTab_Sections;
}
interface tab_DeviceInsightsTab extends DevKit.Controls.ITab {
Section: tab_DeviceInsightsTab_Sections;
}
interface Tabs {
_B3F36061_1F16_4BBB_BD74_44FAC42C9094: tab__B3F36061_1F16_4BBB_BD74_44FAC42C9094;
AlertsTab: tab_AlertsTab;
CommandsTab: tab_CommandsTab;
DeviceInsightsTab: tab_DeviceInsightsTab;
}
interface Body {
Tab: Tabs;
/** Parent Customer of this Asset */
msdyn_Account: DevKit.Controls.Lookup;
/** The category of the customer asset */
msdyn_CustomerAssetCategory: DevKit.Controls.Lookup;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId: DevKit.Controls.String;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId_1: DevKit.Controls.String;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId_2: DevKit.Controls.String;
msdyn_Latitude: DevKit.Controls.Double;
msdyn_Longitude: DevKit.Controls.Double;
/** Top-Level Asset, (if this asset is a sub asset) */
msdyn_MasterAsset: DevKit.Controls.Lookup;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Parent Asset */
msdyn_ParentAsset: DevKit.Controls.Lookup;
/** Reference to Product associated with this Asset */
msdyn_Product: DevKit.Controls.Lookup;
/** A status field that denotes whether all the devices connected to this asset are registered with the IoT provider. */
msdyn_RegistrationStatus: DevKit.Controls.OptionSet;
/** Indicates a link to the Work Order Product from where this Asset was auto created by the system. */
msdyn_WorkOrderProduct: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
WebResource_PowerBIConnectedDevices: DevKit.Controls.WebResource;
}
interface Navigation {
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_customerasset_MasterAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_customerasset_ParentAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_rmaproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorder_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
KnowledgeArticlesSubGrid: DevKit.Controls.Grid;
ConnectedDevices: DevKit.Controls.Grid;
Asset_SubAsset: DevKit.Controls.Grid;
Asset_WorkOrder: DevKit.Controls.Grid;
CommandsGrid: DevKit.Controls.Grid;
AlertsGrid: DevKit.Controls.Grid;
}
}
class FormCustomer_Asset extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Customer_Asset
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Customer_Asset */
Body: DevKit.FormCustomer_Asset.Body;
/** The Navigation of form Customer_Asset */
Navigation: DevKit.FormCustomer_Asset.Navigation;
/** The Grid of form Customer_Asset */
Grid: DevKit.FormCustomer_Asset.Grid;
}
namespace FormCustomer_Asset_Mobile {
interface tab_CommandsTab_Sections {
CommandsSection: DevKit.Controls.Section;
}
interface tab_DeviceInsightsTab_Sections {
DeviceInsightsSection: DevKit.Controls.Section;
}
interface tab_fstab_AssetHierarchy_Sections {
AssetHierarchySection: DevKit.Controls.Section;
}
interface tab_fstab_sub_grids_Sections {
fstab_sub_grids_section: DevKit.Controls.Section;
}
interface tab_fstab_summary_Sections {
_576663BB_EA91_486D_8F88_DA4CD98DF0EB: DevKit.Controls.Section;
ConnectedDeviceAttributes: DevKit.Controls.Section;
Device_Summary_Visualization: DevKit.Controls.Section;
fstab_summary_column_2_section_1: DevKit.Controls.Section;
fstab_summary_column_3_section_1: DevKit.Controls.Section;
fstab_summary_location: DevKit.Controls.Section;
fstab_summary_section_general: DevKit.Controls.Section;
KnowledgeSection: DevKit.Controls.Section;
}
interface tab_PropertyLogsTab_Sections {
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_CommandsTab extends DevKit.Controls.ITab {
Section: tab_CommandsTab_Sections;
}
interface tab_DeviceInsightsTab extends DevKit.Controls.ITab {
Section: tab_DeviceInsightsTab_Sections;
}
interface tab_fstab_AssetHierarchy extends DevKit.Controls.ITab {
Section: tab_fstab_AssetHierarchy_Sections;
}
interface tab_fstab_sub_grids extends DevKit.Controls.ITab {
Section: tab_fstab_sub_grids_Sections;
}
interface tab_fstab_summary extends DevKit.Controls.ITab {
Section: tab_fstab_summary_Sections;
}
interface tab_PropertyLogsTab extends DevKit.Controls.ITab {
Section: tab_PropertyLogsTab_Sections;
}
interface Tabs {
CommandsTab: tab_CommandsTab;
DeviceInsightsTab: tab_DeviceInsightsTab;
fstab_AssetHierarchy: tab_fstab_AssetHierarchy;
fstab_sub_grids: tab_fstab_sub_grids;
fstab_summary: tab_fstab_summary;
PropertyLogsTab: tab_PropertyLogsTab;
}
interface Body {
Tab: Tabs;
/** Parent Customer of this Asset */
msdyn_Account: DevKit.Controls.Lookup;
/** The category of the customer asset */
msdyn_CustomerAssetCategory: DevKit.Controls.Lookup;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId: DevKit.Controls.String;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId_1: DevKit.Controls.String;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId_2: DevKit.Controls.String;
msdyn_FunctionalLocation: DevKit.Controls.Lookup;
msdyn_Latitude: DevKit.Controls.Double;
msdyn_Longitude: DevKit.Controls.Double;
/** Top-Level Asset, (if this asset is a sub asset) */
msdyn_MasterAsset: DevKit.Controls.Lookup;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Enter the name of the custom entity. */
msdyn_name_1: DevKit.Controls.String;
/** Parent Asset */
msdyn_ParentAsset: DevKit.Controls.Lookup;
/** Reference to Product associated with this Asset */
msdyn_Product: DevKit.Controls.Lookup;
/** A status field that denotes whether all the devices connected to this asset are registered with the IoT provider. */
msdyn_RegistrationStatus: DevKit.Controls.OptionSet;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_agreementbookingservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_customerasset_MasterAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_customerasset_ParentAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_quotebookingservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_rmaproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorder_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderincident_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderproduct_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderservice_CustomerAsset: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_customerasset_msdyn_workorderservicetask_CustomerAsset: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
Asset_SubAsset: DevKit.Controls.Grid;
ConnectedDevices: DevKit.Controls.Grid;
KnowledgeArticlesSubGrid: DevKit.Controls.Grid;
CommandsGrid: DevKit.Controls.Grid;
WORKORDERS: DevKit.Controls.Grid;
CurrentPropertyValuesSubgrid: DevKit.Controls.Grid;
PropertyLogsSubGrid: DevKit.Controls.Grid;
}
}
class FormCustomer_Asset_Mobile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Customer_Asset_Mobile
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Customer_Asset_Mobile */
Body: DevKit.FormCustomer_Asset_Mobile.Body;
/** The Navigation of form Customer_Asset_Mobile */
Navigation: DevKit.FormCustomer_Asset_Mobile.Navigation;
/** The Grid of form Customer_Asset_Mobile */
Grid: DevKit.FormCustomer_Asset_Mobile.Grid;
}
namespace FormCustomer_Asset_Quick_Create {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Parent Customer of this Asset */
msdyn_Account: DevKit.Controls.Lookup;
/** The category of the customer asset */
msdyn_CustomerAssetCategory: DevKit.Controls.Lookup;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Reference to Product associated with this Asset */
msdyn_Product: DevKit.Controls.Lookup;
}
}
class FormCustomer_Asset_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Customer_Asset_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Customer_Asset_Quick_Create */
Body: DevKit.FormCustomer_Asset_Quick_Create.Body;
}
class msdyn_customerassetApi {
/**
* DynamicsCrm.DevKit msdyn_customerassetApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Parent Customer of this Asset */
msdyn_Account: DevKit.WebApi.LookupValue;
/** If active parent alerts exist for the device */
msdyn_alert: DevKit.WebApi.BooleanValueReadonly;
/** Count of parent alerts for this device */
msdyn_alertcount: DevKit.WebApi.IntegerValueReadonly;
/** Last Updated time of rollup field Alert Count. */
msdyn_alertcount_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Alert Count. */
msdyn_alertcount_State: DevKit.WebApi.IntegerValueReadonly;
/** The category of the customer asset */
msdyn_CustomerAssetCategory: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_customerassetId: DevKit.WebApi.GuidValue;
/** Device ID used to register with the IoT provider. This will not be used if there are two or more connected devices for this asset. This value will be updated based on the connected devices. */
msdyn_DeviceId: DevKit.WebApi.StringValue;
msdyn_FunctionalLocation: DevKit.WebApi.LookupValue;
msdyn_LastAlertTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Last Updated time of rollup field Last active alert time. */
msdyn_LastAlertTime_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Last active alert time. */
msdyn_LastAlertTime_State: DevKit.WebApi.IntegerValueReadonly;
/** The last command sent to any of the connected devices for this asset. */
msdyn_LastCommandSent: DevKit.WebApi.LookupValue;
/** The timestamp of the last command sent for any of the connected devices for this asset. */
msdyn_LastCommandSentTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
msdyn_Latitude: DevKit.WebApi.DoubleValue;
msdyn_Longitude: DevKit.WebApi.DoubleValue;
/** Top-Level Asset, (if this asset is a sub asset) */
msdyn_MasterAsset: DevKit.WebApi.LookupValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Parent Asset */
msdyn_ParentAsset: DevKit.WebApi.LookupValue;
/** Reference to Product associated with this Asset */
msdyn_Product: DevKit.WebApi.LookupValue;
/** A status field that denotes whether all the devices connected to this asset are registered with the IoT provider. */
msdyn_RegistrationStatus: DevKit.WebApi.OptionSetValue;
/** Indicates a link to the Work Order Product from where this Asset was auto created by the system. */
msdyn_WorkOrderProduct: DevKit.WebApi.LookupValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Customer Asset */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Customer Asset */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_customerasset {
enum msdyn_RegistrationStatus {
/** 192350004 */
Error,
/** 192350002 */
In_Progress,
/** 192350003 */
Registered,
/** 192350000 */
Unknown,
/** 192350001 */
Unregistered
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Customer Asset','Customer Asset - Mobile','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import * as fs from 'fs';
import * as SZIP from 'node-stream-zip';
import got = require('got');
import HTTPService from '../HttpService';
import BungieResource from './BungieResoure';
import { ServerResponse } from '../type-definitions/common';
import {
BungieMembershipType,
DestinyCharacterResponse,
DestinyActivityHistoryResults,
DestinyManifest,
DestinyDefinition,
DestinyLinkedProfilesResponse,
DestinyProfileResponse,
DestinyMilestone,
DestinyItemResponse,
DestinyVendorsResponse,
DestinyVendorResponse,
DestinyCollectibleNodeDetailResponse,
DestinyPostGameCarnageReportData,
DestinyHistoricalStatsDefinition,
DestinyClanAggregateStat,
DestinyEntitySearchResult,
DestinyHistoricalStatsByPeriod,
DestinyHistoricalStatsAccountResult,
DestinyActivity,
DestinyHistoricalWeaponStatsData,
DestinyAggregateActivityResults,
DestinyMilestoneContent,
DestinyPublicMilestone
} from '../type-definitions/destiny2';
import { UserInfoCard } from '../type-definitions/user';
import { QueryStringParameters, DictionaryResponse, TypeDefinition } from '../type-definitions/additions';
import { resolveQueryStringParameters } from '../util';
export default class Destiny2Resource extends BungieResource {
protected resourcePath: string;
constructor(httpService: HTTPService) {
super(httpService);
this.resourcePath = `${this.basePath}/Destiny2`;
}
/**
* Returns the current version of the manifest as a json object.
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getDestinyManifest()
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @returns {Promise<ServerResponse<DestinyManifest>>} When fulfilled returns an object containing the current Destiny 2 manifest
* @memberof Destiny2Resource
*/
public getDestinyManifest(): Promise<ServerResponse<DestinyManifest>> {
return new Promise<ServerResponse<DestinyManifest>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Manifest/`)
.then((response: ServerResponse<DestinyManifest>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Returns the static definition of an entity of the given Type and hash identifier. Examine the API Documentation for the Type Names of entities that have their own definitions.
* Note that the return type will always *inherit from* DestinyDefinition, but the specific type returned will be the requested entity type if it can be found.
* Please don't use this as a chatty alternative to the Manifest database if you require large sets of data, but for simple and one-off accesses this should be handy.
*
* ```js
* import Traveler from './Traveler';
* import { TypeDefinition } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getDestinyEntityDefinition(
* TypeDefinition.DestinyInventoryItemDefinition,
* 'hashIdentifier'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
* @param {string} typeDefinition
* @param {string} hashIdentifier
* @returns {Promise<ServerResponse<DestinyDefinition>>}
* @memberof Destiny2Resource
*/
public getDestinyEntityDefinition(
typeDefinition: string,
hashIdentifier: string
): Promise<ServerResponse<DestinyDefinition>> {
return new Promise<ServerResponse<DestinyDefinition>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Manifest/${typeDefinition}/${hashIdentifier}/`)
.then((response: ServerResponse<DestinyDefinition>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Search for a Destiny 2 player by name
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .searchDestinyPlayer(
* BungieMembershipType.All,
* 'displayName'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} displayName The full gamertag or PSN id of the player. Spaces and case are ignored
* @returns {Promise<ServerResponse<UserInfoCard[]>>}
* @memberof Destiny2Resource
*/
public searchDestinyPlayer(
membershipType: BungieMembershipType,
displayName: string
): Promise<ServerResponse<UserInfoCard[]>> {
return new Promise<ServerResponse<UserInfoCard[]>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/SearchDestinyPlayer/${membershipType}/${displayName}/`)
.then((response: ServerResponse<UserInfoCard[]>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Returns a summary information about all profiles linked to the requesting membership type/membership ID that have valid Destiny information.
* The passed-in Membership Type/Membership ID may be a Bungie.Net membership or a Destiny membership.
* It only returns the minimal amount of data to begin making more substantive requests, but will hopefully serve as a useful alternative to UserServices for people who just care about Destiny data.
* Note that it will only return linked accounts whose linkages you are allowed to view.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getLinkedProfiles(
* BungieMembershipType.TigerPSN,
* 'destinyMembershipId'
* );
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType
* @param {string} destinyMembershipId
* @returns {Promise<ServerResponse<DestinyLinkedProfilesResponse>>}
* @memberof Destiny2Resource
*/
public getLinkedProfiles(
membershipType: BungieMembershipType,
destinyMembershipId: string
): Promise<ServerResponse<DestinyLinkedProfilesResponse>> {
return new Promise<ServerResponse<DestinyLinkedProfilesResponse>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/${membershipType}/Profile/${destinyMembershipId}/LinkedProfiles/`)
.then((response: ServerResponse<DestinyLinkedProfilesResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Returns Destiny Profile information for the supplied membership.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getProfile(
* BungieMembershipType.TigerPsn,
* 'membershipId',
* {components: [DestinyComponentType.Profiles]}
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny ID (Account ID)
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @param {string} [oauthAccesstoken] Optional access token to request data with an oauth scopes
* @returns {Promise<ServerResponse<DestinyProfileResponse>>}
* @memberof Destiny2Resource
*
*/
public getProfile(
membershipType: BungieMembershipType,
destinyMembershipId: string,
queryStringParameters: QueryStringParameters,
oauthAccesstoken?: string
): Promise<ServerResponse<DestinyProfileResponse>> {
return new Promise<ServerResponse<DestinyProfileResponse>>((resolve, reject) => {
this.httpService
.get(
`${this.resourcePath}/${membershipType}/Profile/${destinyMembershipId}/${resolveQueryStringParameters(
queryStringParameters
)}`,
oauthAccesstoken
)
.then((response: ServerResponse<DestinyProfileResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Retrieve aggregrated details about a Destiny Characters
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getCharacter(
* BungieMembershipType.TigerPSN,
* 'destinyMembershipId',
* 'characterId',
* {
* components: [
* DestinyComponentType.Characters,
* DestinyComponentType.CharacterInventories,
* DestinyComponentType.CharacterProgressions,
* DestinyComponentType.CharacterRenderData,
* DestinyComponentType.CharacterActivities,
* DestinyComponentType.CharacterEquipment
* ]
* })
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId Destiny membership ID.
* @param {string} characterId ID of the character.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @param {string} [oauthAccesstoken] Optional oauth access token
* @returns {Promise<ServerResponse<DestinyCharacterResponse>>}
* @memberof Destiny2Resource
*/
public getCharacter(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
queryStringParameters: QueryStringParameters,
oauthAccesstoken?: string
): Promise<ServerResponse<DestinyCharacterResponse>> {
return new Promise<ServerResponse<DestinyCharacterResponse>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Profile/${destinyMembershipId}/Character/${characterId}/${resolveQueryStringParameters(
queryStringParameters
)}`,
oauthAccesstoken
)
.then((response: ServerResponse<DestinyCharacterResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Returns information on the weekly clan rewards and if the clan has earned them or not. Note that this will always report rewards as not redeemed.
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', // used to identify your request to the API
* });
*
* traveler.destiny2
* .getClanWeeklyRewardState('groupId')
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} groupId A valid group id of the clan
* @returns {Promise<ServerResponse<DestinyMilestone>>} When fulfilled returns an object containing information about the weekly clan results
* @memberof Destiny2Resource
*/
public getClanWeeklyRewardState(groupId: string): Promise<ServerResponse<DestinyMilestone>> {
return new Promise<ServerResponse<DestinyMilestone>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Clan/${groupId}/WeeklyRewardState/`)
.then((response: ServerResponse<DestinyMilestone>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Get the details of an instanced Destiny Item. Materials and other non-instanced items can not be queried with this endpoint.
* The items are coupled with an specific Destiny Account
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getItem(
* BungieMembershipType.PSN,
* 'destinyMembershipId',
* 'itemInstanceId',
* { components: [DestinyComponentType.ItemCommonData] }
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny ID (Account ID)
* @param {string} itemInstanceId ID of the Destiny Item
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DestinyItemResponse>>} When fulfilled returns an object containing stats about the queried item
* @memberof Destiny2Resource
*/
public getItem(
membershipType: BungieMembershipType,
destinyMembershipId: string,
itemInstanceId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyItemResponse>> {
return new Promise<ServerResponse<DestinyItemResponse>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Profile/${destinyMembershipId}/Item/${itemInstanceId}/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DestinyItemResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Get currently available vendors from the list of vendors that can possibly have rotating inventory.
* Note that this does not include things like preview vendors and vendors-as-kiosks, neither of whom have rotating/dynamic inventories. Use their definitions as-is for those.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getVendors(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* {
* components: [DestinyComponentType.VendorReceipts]
* },
* 'oauthAccesstoken'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId Destiny membership ID of another user. You may be denied.
* @param {string} characterId The Destiny Character ID of the character for whom we're getting vendor info.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @param {string} [oauthAccesstoken] Optional oauth access toen
* @returns {Promise<ServerResponse<DestinyVendorsResponse>>} When fulfilled returns an object containing all available vendors
* @memberof Destiny2Resource
*/
public getVendors(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
queryStringParameters: QueryStringParameters,
oauthAccesstoken: string
): Promise<ServerResponse<DestinyVendorsResponse>> {
return new Promise<ServerResponse<DestinyVendorsResponse>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Profile/${destinyMembershipId}/Character/${characterId}/Vendors/${resolveQueryStringParameters(
queryStringParameters
)}`,
oauthAccesstoken
)
.then((response: ServerResponse<DestinyVendorsResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Get items available from vendors where the vendors have items for sale that are common for everyone.
* If any portion of the Vendor's available inventory is character or account specific, we will be unable to return their data from this endpoint due to the way that available inventory is computed.
* As I am often guilty of saying: 'It's a long story...'
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getPublicVendors(
* {
* components: [DestinyComponentType.Vendors]
* }
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DestinyVendorsResponse>>} When fulfilled returns an object containing all valid components for the public Vendors endpoint
* @memberof Destiny2Resource
*/
public getPublicVendors(
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyVendorsResponse>> {
return new Promise<ServerResponse<DestinyVendorsResponse>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Vendors/${resolveQueryStringParameters(queryStringParameters)}`)
.then((response: ServerResponse<DestinyVendorsResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Retrieve all currently available vendors for a specific character
* @async
* @param membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param destinyMembershipId The Destiny ID (Account ID)
* @param characterId ID of the character for whom to get the vendor info
* @param vendorHash Hash identifier of the vendor to retreieve
* @param queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @return {Promise.IAPIResponse<DestinyVendorResponse>} When fulfilled returns an object containing all available vendors
*/
/**
* Get the details of a specific Vendor.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2.
* .getVendor(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* 'vendorHash'
* {
* components: [DestinyComponentType.VendorReceipts, DestinyComponentType.VendorSales]
* },
* 'oauthAccesstoken'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId Destiny membership ID of another user. You may be denied.
* @param {string} characterId The Destiny Character ID of the character for whom we're getting vendor info.
* @param {string} vendorHash The Hash identifier of the Vendor to be returned.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<IAPIResponse<DestinyVendorResponse>>}
* @memberof Destiny2Resource
*/
public getVendor(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
vendorHash: string,
queryStringParameters: QueryStringParameters,
oauthAccesstoken: string
): Promise<ServerResponse<DestinyVendorResponse>> {
return new Promise<ServerResponse<DestinyVendorResponse>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Profile/${destinyMembershipId}/Character/${characterId}/Vendors/${vendorHash}/${resolveQueryStringParameters(
queryStringParameters
)}`,
oauthAccesstoken
)
.then((response: ServerResponse<DestinyVendorResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Given a Presentation Node that has Collectibles as direct descendants, this will return item details about those descendants in the context of the requesting character.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyComponentType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getCollectibleNodeDetails(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* 1234567890,
* {components: [DestinyComponentType.Collectibles]},
* 'oauthAccesstoken'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.PSN` for this endpoint.
* @param {string} destinyMembershipId Destiny membership ID of another user. You may be denied.
* @param {string} characterId The Destiny Character ID of the character for whom we're getting collectible detail info.
* @param {number} collectiblePresentationNodeHash The hash identifier of the Presentation Node for whom we should return collectible details. Details will only be returned for collectibles that are direct descendants of this node.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>components {string[]}: See {@link https://bungie-net.github.io/multi/schema_Destiny-DestinyComponentType.html#schema_Destiny-DestinyComponentType|DestinyComponentType} for the different enum types.</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DestinyCollectibleNodeDetailResponse>>} When fulfilled returns the detailed information about a Collectible Presentation Node and any Collectibles that are direct descendants.
* @memberof Destiny2Resource
*/
public getCollectibleNodeDetails(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
collectiblePresentationNodeHash: number,
queryStringParameters: QueryStringParameters,
oauthAccesstoken: string
): Promise<ServerResponse<DestinyCollectibleNodeDetailResponse>> {
return new Promise<ServerResponse<DestinyCollectibleNodeDetailResponse>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Profile/${destinyMembershipId}/Character/${characterId}/Collectibles/${collectiblePresentationNodeHash}/${resolveQueryStringParameters(
queryStringParameters
)}`,
oauthAccesstoken
)
.then((response: ServerResponse<DestinyCollectibleNodeDetailResponse>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets the available post game carnage report for the activity ID.
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getPostGameCarnageReport('activityId')
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} activityId The ID of the activity whose PGCR is requested.
* @returns {Promise<ServerResponse<DestinyPostGameCarnageReportData>>} When fulfilled returns an object containing the carnage report for the specified activity
* @memberof Destiny2Resource
*/
public getPostGameCarnageReport(activityId: string): Promise<ServerResponse<DestinyPostGameCarnageReportData>> {
return new Promise<ServerResponse<DestinyPostGameCarnageReportData>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Stats/PostGameCarnageReport/${activityId}/`)
.then((response: ServerResponse<DestinyPostGameCarnageReportData>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets historical stats definitions.
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2.getHistoricalStatsDefinition()
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @returns {Promise<ServerResponse<{ [key: string]: DestinyHistoricalStatsDefinition }>>}
* @memberof Destiny2Resource
*/
public getHistoricalStatsDefinition(): Promise<ServerResponse<DictionaryResponse<DestinyHistoricalStatsDefinition>>> {
return new Promise<ServerResponse<{ [key: string]: DestinyHistoricalStatsDefinition }>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Stats/Definition/`)
.then((response: ServerResponse<DictionaryResponse<DestinyHistoricalStatsDefinition>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets leaderboards with the signed in user's friends and the supplied destinyMembershipId as the focus.
* PREVIEW: This endpoint is still in beta, and may experience rough edges. The schema is in final form, but there may be bugs that prevent desirable operation.
*
* ```js
* import Traveler from './Traveler';
* import { DestinyActivityModeType } from 'the-traveler/type-definitions/destiny2';
* import { StatId } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getClanLeaderboards('groupId', {
* modes: [DestinyActivityModeType.AllPvP, DestinyActivityModeType.AllPvE],
* maxtop: 10,
* statid: StatId.ActivitiesWon
* })
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} groupId Group ID of the clan whose leaderboards you wish to fetch.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>modes {strings[]} Different gameMode IDs for which to get the stats <br />
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs
* </li>
* <li>maxtop {number}: Maximum number of top players to return. Use a large number to get entire leaderboard
* <li><statId {string}: ID of stat to return rather than returning all Leaderboard stats. <br />
* {@link https://alexanderwe.github.io/the-traveler/enums/statid.html|StatIds} for available ids</li>
* </ul>
* @returns {Promise<ServerResponse<DictionaryResponse<object>>} When fulfilled returns an object containing leaderboards for a clan
* @memberof Destiny2Resource
*/
public getClanLeaderboards(
groupId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DictionaryResponse<object>>> {
return new Promise<ServerResponse<DictionaryResponse<object>>>((resolve, reject) => {
this.httpService
.get(
`${this.resourcePath}/Stats/Leaderboards/Clans/${groupId}/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DictionaryResponse<object>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets aggregated stats for a clan using the same categories as the clan leaderboards. PREVIEW: This endpoint is still in beta, and may experience rough edges. The schema is in final form, but there may be bugs that prevent desirable operation.
*
* ```js
* import Traveler from './Traveler';
* import { DestinyActivityModeType } from 'the-traveler/type-definitions/destiny2';
* import { StatId } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getClanAggregateStats('groupId', {
* modes: [DestinyActivityModeType.AllPvP, DestinyActivityModeType.AllPvE]
* })
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} groupId Group ID of the clan whose leaderboards you wish to fetch.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>modes {string[]}: Array of game modes for which to get stats <br />
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DestinyClanAggregateStat[]>>}
* @memberof Destiny2Resource
*/
public getClanAggregateStats(
groupId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyClanAggregateStat[]>> {
return new Promise<ServerResponse<DestinyClanAggregateStat[]>>((resolve, reject) => {
this.httpService
.get(
`${this.resourcePath}/Stats/AggregateClanStats/${groupId}/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DestinyClanAggregateStat[]>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets leaderboards with the signed in user's friends and the supplied destinyMembershipId as the focus.
* PREVIEW: This endpoint has not yet been implemented. It is being returned for a preview of future functionality, and for public comment/suggestion/preparation.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyActivityModeType } from 'the-traveler/type-definitions/destiny2';
* import { StatId } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getLeaderboards(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* {
* modes: [DestinyActivityModeType.AllPvP, DestinyActivityModeType.AllPvE],
* maxtop: 10,
* statid: StatId.ActivitiesWon
* }
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType The Destiny membershipId of the user to retrieve.
* @param {string} destinyMembershipId A valid non-BungieNet membership type.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>modes {strings[]} Different gameMode IDs for which to get the stats <br />
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs
* </li>
* <li>maxtop {number}: Maximum number of top players to return. Use a large number to get entire leaderboard
* <li><statId {string}: ID of stat to return rather than returning all Leaderboard stats. <br />
* See {@link https://alexanderwe.github.io/the-traveler/enums/statid.html|StatIds} for available ids</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DictionaryResponse<object>>>}
* @memberof Destiny2Resource
*/
public getLeaderboards(
membershipType: BungieMembershipType,
destinyMembershipId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DictionaryResponse<object>>> {
return new Promise<ServerResponse<DictionaryResponse<object>>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Account/${destinyMembershipId}/Stats/Leaderboards/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DictionaryResponse<object>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets leaderboards with the signed in user's friends and the supplied destinyMembershipId as the focus. PREVIEW: This endpoint is still in beta, and may experience rough edges. The schema is in final form, but there may be bugs that prevent desirable operation.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyActivityModeType } from 'the-traveler/type-definitions/destiny2';
* import { StatId } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getLeaderboardsForCharacter(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* {
* modes: [DestinyActivityModeType.AllPvP, DestinyActivityModeType.AllPvE],
* maxtop: 10,
* statid: StatId.ActivitiesWon
* }
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {string} characterId The specific character to build the leaderboard around for the provided Destiny Membership.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>modes {strings[]} Different gameMode IDs for which to get the stats <br />
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs
* </li>
* <li>maxtop {number}: Maximum number of top players to return. Use a large number to get entire leaderboard
* <li><statId {string}: ID of stat to return rather than returning all Leaderboard stats. <br />
* //TODO: Change the link of all enums
* See {@link https://alexanderwe.github.io/the-traveler/enums/statid.html|StatIds} for available ids</li>
* </ul> You must request at least one component to receive results.
* @returns {Promise<ServerResponse<DictionaryResponse<object>>>}
* @memberof Destiny2Resource
*/
public getLeaderboardsForCharacter(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DictionaryResponse<object>>> {
return new Promise<ServerResponse<DictionaryResponse<object>>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/Stats/Leaderboards/${membershipType}/${destinyMembershipId}/${characterId}/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DictionaryResponse<object>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets a page list of Destiny items.
*
* ```js
* import Traveler from './Traveler';
* import { TypeDefinition } from 'the-traveler/type-definitions/additions';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .searchDestinyEntities(
* 'moon',
* TypeDefinition.DestinyInventoryItemDefinition,
* { page: 0 })
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} searchTerm The string to use when searching for Destiny entities.
* @param {TypeDefinition} typeDefinition The type of entity for whom you would like results. These correspond to the entity's definition contract name. For instance, if you are looking for items, this property should be 'DestinyInventoryItemDefinition'.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>page {number} Page number to return, starting with 0</li>
* </ul>
* @returns {Promise<ServerResponse<DestinyEntitySearchResult>>} The entities search result
* @memberof Destiny2Resource
*/
public searchDestinyEntities(
searchTerm: string,
typeDefinition: TypeDefinition,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyEntitySearchResult>> {
return new Promise<ServerResponse<DestinyEntitySearchResult>>((resolve, reject) => {
this.httpService
.get(
`${this.resourcePath}/Armory/Search/${typeDefinition}/${searchTerm}/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DestinyEntitySearchResult>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets historical stats for indicated character.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyStatsGroupType, PeriodType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getHistoricalStats(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* {
* dayend: '2017-09-30',
* daystart: '2017-09-20',
* groups: [DestinyStatsGroupType.Activity],
* periodType: PeriodType.Activity
* }
* )
* .then(response => {
* console.log(response);
* })
*.catch(err => {
* console.log(err);
*});
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {string} characterId The id of the character to retrieve. You can omit this character ID or set it to 0 to get aggregate stats across all characters.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>dayend {string}: Last day to return when daily stats are requested. Use the format YYYY-MM-DD</li>
* <li>daystart {string}: First day to return when daily stats are requested. Use the format YYYY-MM-DD</li>
* <li>groups {string[]}: Group of stats to include, otherwise only general stats are returned. Use the numbers.<br >
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType.html#schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType|DestinyStatsGroupType} for the different IDs
* </li>
* <li>modes {strings[]} Different gameMode IDs for which to get the stats.<br >
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs
* </li>
* <li>periodType {number}: Indicates a specific period type to return. <br >
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-PeriodType.html#schema_Destiny-HistoricalStats-Definitions-PeriodType|PeriodType} for the different period type numbers
* </li>
* </ul>
* @returns {Promise<ServerResponse<DictionaryResponse<DestinyHistoricalStatsByPeriod>>>}
* @memberof Destiny2Resource
*/
public getHistoricalStats(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DictionaryResponse<DestinyHistoricalStatsByPeriod>>> {
return new Promise<ServerResponse<DictionaryResponse<DestinyHistoricalStatsByPeriod>>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Account/${destinyMembershipId}/Character/${characterId}/Stats/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DictionaryResponse<DestinyHistoricalStatsByPeriod>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Retrieve aggregrated details about a Destiny account's characters
* @async
* @param membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.PSN` for this endpoint.
* @param destinyMembershipId The Destiny ID (Account ID)
* @param queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li> groups {string[]}: Group of stats to include, otherwise only general stats are returned. Use the numbers. <br >/
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType.html#schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType|DestinyStatsGroupType} for the different IDs
* </ul>
* @return {Promise.IAPIResponse<DestinyHistoricalStatsAccountResult>} When fulfilled returns an object containing stats about the found user's account
*/
/**
* Gets aggregate historical stats organized around each character for a given account.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyStatsGroupType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getHistoricalStatsForAccount(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* {groups: [DestinyStatsGroupType.Activity]}
* )
* .then(response => {
* console.log(response);
* })
*.catch(err => {
* console.log(err);
*});
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li> groups {string[]}: Group of stats to include, otherwise only general stats are returned. Use the numbers. <br >/
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType.html#schema_Destiny-HistoricalStats-Definitions-DestinyStatsGroupType|DestinyStatsGroupType} for the different IDs
* </ul>
* @returns {Promise<ServerResponse<DestinyHistoricalStatsAccountResult>>}
* @memberof Destiny2Resource
*/
public getHistoricalStatsForAccount(
membershipType: BungieMembershipType,
destinyMembershipId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyHistoricalStatsAccountResult>> {
return new Promise<ServerResponse<DestinyHistoricalStatsAccountResult>>((resolve, reject) => {
this.httpService
.get(
`${this.resourcePath}/${membershipType}/Account/${destinyMembershipId}/Stats/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DestinyHistoricalStatsAccountResult>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets activity history stats for indicated character.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
* import { DestinyActivityModeType } from 'the-traveler/type-definitions/destiny2';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getActivityHistory(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId',
* {
* count: 10,
* mode: DestinyActivityModeType.AllPvE,
* page: 0
* })
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {string} characterId The id of the character to retrieve.
* @param {QueryStringParameters} queryStringParameters An object containing key/value query parameters for this endpoint. Following keys are valid:
* <ul>
* <li>count {number}: Number of rows to return</li>
* <li>mode {number} A single game mode to get the history for the specified character. <br />
* See {@link https://bungie-net.github.io/multi/schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType.html#schema_Destiny-HistoricalStats-Definitions-DestinyActivityModeType|DestinyActivityModeType} for the different game mode IDs
* </li>
* <li>page {number}: Page number to return, starting with 0</li>
* </ul>
* @returns {Promise<ServerResponse<DestinyActivityHistoryResults>>}
* @memberof Destiny2Resource
*/
public getActivityHistory(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string,
queryStringParameters: QueryStringParameters
): Promise<ServerResponse<DestinyActivityHistoryResults>> {
return new Promise<ServerResponse<DestinyActivityHistoryResults>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Account/${destinyMembershipId}/Character/${characterId}/Stats/Activities/${resolveQueryStringParameters(
queryStringParameters
)}`
)
.then((response: ServerResponse<DestinyActivityHistoryResults>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets details about unique weapon usage, including all exotic weapons.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getUniqueWeaponHistory(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {string} characterId The id of the character to retrieve.
* @returns {Promise<ServerResponse<DestinyHistoricalWeaponStatsData>>}
* @memberof Destiny2Resource
*/
public getUniqueWeaponHistory(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string
): Promise<ServerResponse<DestinyHistoricalWeaponStatsData>> {
return new Promise<ServerResponse<DestinyHistoricalWeaponStatsData>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Account/${destinyMembershipId}/Character/${characterId}/Stats/UniqueWeapons/`
)
.then((response: ServerResponse<DestinyHistoricalWeaponStatsData>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets all activities the character has participated in together with aggregate statistics for those activities.
*
* ```js
* import Traveler from './Traveler';
* import { BungieMembershipType } from 'the-traveler/type-definitions/app';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getDestinyAggregateActivityStats(
* BungieMembershipType.TigerPsn,
* 'destinyMembershipId',
* 'characterId'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {BungieMembershipType} membershipType A valid non-BungieNet membership type. It has to match the type which the `destinyMembershipId` is belonging to. <br />
* Keep in mind that `-1 / MembershipType.All` is <strong> not applicable here </strong> <br/>
* Ex: If the `destinyMembershipId` is a PSN account then use `'2'` or `MembershipType.TigerPSN` for this endpoint.
* @param {string} destinyMembershipId The Destiny membershipId of the user to retrieve.
* @param {string} characterId The specific character whose activities should be returned.
* @returns {Promise<ServerResponse<DestinyAggregateActivityResults>>}
* @memberof Destiny2Resource
*/
public getDestinyAggregateActivityStats(
membershipType: BungieMembershipType,
destinyMembershipId: string,
characterId: string
): Promise<ServerResponse<DestinyAggregateActivityResults>> {
return new Promise<ServerResponse<DestinyAggregateActivityResults>>((resolve, reject) => {
this.httpService
.get(
`${
this.resourcePath
}/${membershipType}/Account/${destinyMembershipId}/Character/${characterId}/Stats/AggregateActivityStats/`
)
.then((response: ServerResponse<DestinyAggregateActivityResults>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets custom localized content for the milestone of the given hash, if it exists.
* @async
* @param milestoneHash The identifier for the milestone to be returned
* @return {Promise.IAPIResponse<DestinyMilestoneContent>} When fulfilled returns an object containing aggregated information about recent activities
*/
/**
* Gets custom localized content for the milestone of the given hash, if it exists.
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getPublicMilestoneContent(
* 'milestoneHash'
* )
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} milestoneHash The identifier for the milestone to be returned.
* @returns {Promise<ServerResponse<DestinyMilestoneContent>>}
* @memberof Destiny2Resource
*/
public getPublicMilestoneContent(milestoneHash: string): Promise<ServerResponse<DestinyMilestoneContent>> {
return new Promise<ServerResponse<DestinyMilestoneContent>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Milestones/${milestoneHash}/Content/`)
.then((response: ServerResponse<DestinyMilestoneContent>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Gets public information about currently available Milestones.
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getPublicMilestones()
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @returns {Promise<ServerResponse<DictionaryResponse<DestinyPublicMilestone>>}
* @memberof Destiny2Resource
*/
public getPublicMilestones(): Promise<ServerResponse<DictionaryResponse<DestinyPublicMilestone>>> {
return new Promise<ServerResponse<DictionaryResponse<DestinyPublicMilestone>>>((resolve, reject) => {
this.httpService
.get(`${this.resourcePath}/Milestones/`)
.then((response: ServerResponse<DictionaryResponse<DestinyPublicMilestone>>) => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
}
/**
* Download the specified manifest file, extract the zip and also deleting the zip afterwards
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getDestinyManifest()
* .then(response => {
* traveler.destiny2
* .downloadManifest(response.Response.mobileWorldContentPaths['en'])
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} manifestUrl The url of the manifest you want to download
* @param {string} [filename] The filename of the final unzipped file. This is used for the constructor of [[Manifest]]
* @returns {Promise<string>} When fulfilled returns the path of the saved manifest file
* @memberof Destiny2Resource
*/
public downloadManifest(manifestUrl: string, filename?: string): Promise<string> {
const downloadFileName = manifestUrl.substring(manifestUrl.lastIndexOf('/') + 1);
const outputFileName = `${filename ? filename : manifestUrl.substring(manifestUrl.lastIndexOf('/') + 1)}`;
const outStream = fs.createWriteStream(`${downloadFileName}.zip`);
return new Promise<string>((resolve, reject) => {
got
.stream(`https://www.bungie.net/${manifestUrl}`)
.pipe(outStream)
.on('finish', () => {
const zip = new SZIP({
file: `${downloadFileName}.zip`,
storeEntries: true
});
zip.on('ready', () => {
zip.extract(downloadFileName, outputFileName, (err: object, count: number) => {
if (err) {
reject(new Error('Error extracting zip'));
} else {
zip.close();
fs.unlink(`${downloadFileName}.zip`, err => {
if (err) {
reject(new Error('Error deleting .zip file'));
}
resolve(outputFileName);
});
}
});
});
});
});
}
/**
* Download the specified json manifest file
*
* ```js
* import Traveler from './Traveler';
*
* let traveler = new Traveler({
* apikey: 'apikey',
* userAgent: 'useragent', //used to identify your request to the API
* });
*
* traveler.destiny2
* .getDestinyManifest()
* .then(response => {
* traveler.destiny2
* .downloadManifestJSON(response.Response.jsonWorldContentPaths['en'])
* .then(response => {
* console.log(response);
* })
* .catch(err => {
* console.log(err);
* });
* })
* .catch(err => {
* console.log(err);
* });
* ```
*
* @param {string} manifestUrl The url of the manifest you want to download
* @param {string} [filename] The filename of the final .json file downloaded
* @returns {Promise<string>} When fulfilled returns the path of the saved manifest file
* @memberof Destiny2Resource
*/
public downloadManifestJSON(manifestUrl: string, filename?: string): Promise<string> {
const outStream = fs.createWriteStream(
`${filename ? filename : manifestUrl.substring(manifestUrl.lastIndexOf('/') + 1)}`
);
return new Promise<string>((resolve, reject) => {
got
.stream(`https://www.bungie.net/${manifestUrl}`)
.pipe(outStream)
.on('finish', () => {
resolve(filename);
});
});
}
} | the_stack |
import { Functor } from "@siteimprove/alfa-functor";
import { Serializable } from "@siteimprove/alfa-json";
import { Mapper } from "@siteimprove/alfa-mapper";
import { Option, None } from "@siteimprove/alfa-option";
import { Parser } from "@siteimprove/alfa-parser";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Result, Err } from "@siteimprove/alfa-result";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Thunk } from "@siteimprove/alfa-thunk";
import * as json from "@siteimprove/alfa-json";
import * as parser from "@siteimprove/alfa-parser";
/**
* @public
*/
export class Flag<T = unknown> implements Functor<T>, Serializable<Flag.JSON> {
public static of<T>(
name: string,
description: string,
parse: Flag.Parser<T, [Predicate<string>]>
): Flag<T> {
const options: Flag.Options = {
type: None,
aliases: [],
optional: false,
repeatable: false,
negatable: false,
default: None,
};
return new Flag(
name,
description.replace(/\s+/g, " ").trim(),
options,
parse
);
}
private readonly _name: string;
private readonly _description: string;
private readonly _options: Flag.Options;
private readonly _parse: Flag.Parser<T, [Predicate<string>]>;
private constructor(
name: string,
description: string,
options: Flag.Options,
parse: Flag.Parser<T, [Predicate<string>]>
) {
this._name = name;
this._description = description;
this._options = options;
this._parse = parse;
}
public get name(): string {
return this._name;
}
public get description(): string {
return this._description;
}
public get options(): Flag.Options {
return this._options;
}
public get parse(): Flag.Parser<T> {
return (argv) => this._parse(argv, (name) => this.matches(name));
}
public matches(name: string): boolean {
name = name.length === 2 ? name.replace(/^-/, "") : name.replace(/^--/, "");
if (this._options.negatable) {
name = name.replace(/^no-/, "");
}
return (
this._name === name ||
this._options.aliases.some((alias) => alias === name)
);
}
public map<U>(mapper: Mapper<T, U>): Flag<U> {
return new Flag(
this._name,
this._description,
this._options,
Parser.map(this._parse, (set) => set.map(mapper))
);
}
public filter<U extends T>(
refinement: Refinement<T, U>,
ifError?: Thunk<string>
): Flag<U>;
public filter(predicate: Predicate<T>, ifError?: Thunk<string>): Flag<T>;
public filter(
predicate: Predicate<T>,
ifError: Thunk<string> = () => "Incorrect value"
): Flag<T> {
const filter = (previous: Flag.Set<T>): Flag.Parser<T> => (argv) =>
previous
.parse(argv)
.flatMap(([argv, set]) =>
predicate(set.value)
? Result.of([
argv,
Flag.Set.of(set.value, (argv) => filter(set)(argv)),
])
: Err.of(ifError())
);
const parse: Flag.Parser<T, [Predicate<string>]> = (argv, matches) =>
this._parse(argv, matches).flatMap(([argv, set]) =>
predicate(set.value)
? Result.of([
argv,
Flag.Set.of(set.value, (argv) => filter(set)(argv)),
])
: Err.of(ifError())
);
return new Flag(this._name, this._description, this._options, parse);
}
public type(type: string): Flag<T> {
return new Flag(
this._name,
this._description,
{
...this._options,
type: Option.of(type),
},
this._parse
);
}
public alias(alias: string): Flag<T> {
return new Flag(
this._name,
this._description,
{
...this._options,
aliases: [...this._options.aliases, alias],
},
this._parse
);
}
public default(value: T, label: string = `${value}`): Flag<T> {
label = label.replace(/\s+/g, " ").trim();
const options = {
...this._options,
optional: true,
default: label === "" ? None : Option.of(label),
};
const missing = (
previous: Flag.Set<T>
): Flag.Parser<T, [Predicate<string>]> => (argv, matches) => {
const [name] = argv;
if (name === undefined || !matches(name)) {
return Result.of([
argv,
Flag.Set.of(previous.value, (argv) =>
missing(previous)(argv, matches)
),
]);
}
return previous
.parse(argv)
.map(([argv, set]) => [
argv,
Flag.Set.of(set.value, (argv) => missing(set)(argv, matches)),
]);
};
const parse: Flag.Parser<T, [Predicate<string>]> = (argv, matches) => {
const [name] = argv;
if (name === undefined || !matches(name)) {
return Result.of([
argv,
Flag.Set.of(value, (argv) => parse(argv, matches)),
]);
}
return this._parse(argv, matches).map(([argv, set]) => [
argv,
Flag.Set.of(set.value, (argv) => missing(set)(argv, matches)),
]);
};
return new Flag(this._name, this._description, options, parse);
}
public optional(): Flag<Option<T>> {
const options = { ...this._options, optional: true };
const missing = (
previous: Flag.Set<Option<T>>
): Flag.Parser<Option<T>, [Predicate<string>]> => (argv, matches) => {
const [name] = argv;
if (name === undefined || !matches(name)) {
return Result.of([
argv,
Flag.Set.of(previous.value, (argv) =>
missing(previous)(argv, matches)
),
]);
}
return previous
.parse(argv)
.map(([argv, set]) => [
argv,
Flag.Set.of(set.value, (argv) => missing(set)(argv, matches)),
]);
};
const parse: Flag.Parser<Option<T>, [Predicate<string>]> = (
argv,
matches
) => {
const [name] = argv;
if (name === undefined || !matches(name)) {
return Result.of([
argv,
Flag.Set.of(Option.empty(), (argv) => parse(argv, matches)),
]);
}
return this._parse(argv, matches).map(([argv, set]) => [
argv,
Flag.Set.of(Option.of(set.value), (argv) =>
missing(set.map(Option.of))(argv, matches)
),
]);
};
return new Flag(this._name, this._description, options, parse);
}
public repeatable(): Flag<Array<T>> {
const options = { ...this._options, repeatable: true };
const repeat = (previous: Flag.Set<Array<T>>): Flag.Parser<Array<T>> => (
argv
) =>
previous
.parse(argv)
.map(([argv, set]) => [
argv,
Flag.Set.of([...previous.value, ...set.value], (argv) =>
repeat(set)(argv)
),
]);
const parse: Flag.Parser<Array<T>, [Predicate<string>]> = (argv, matches) =>
this._parse(argv, matches).map(([argv, set]) => [
argv,
Flag.Set.of([set.value], (argv) =>
repeat(set.map((value) => [value]))(argv)
),
]);
return new Flag(this._name, this._description, options, parse);
}
public negatable(mapper: Mapper<T>): Flag<T> {
const options = { ...this._options, negatable: true };
const negate = (
previous: Flag.Set<T>
): Flag.Parser<T, [Predicate<string>]> => (argv, matches) => {
const [name] = argv;
const isNegated = name !== undefined && name.startsWith("--no-");
if (isNegated) {
argv = [name.replace("--no-", "--"), ...argv.slice(1)];
}
return previous
.parse(argv)
.map(([argv, set]) => [
argv,
Flag.Set.of(isNegated ? mapper(set.value) : set.value, (argv) =>
negate(set)(argv, matches)
),
]);
};
const parse: Flag.Parser<T, [Predicate<string>]> = (argv, matches) => {
const [name] = argv;
const isNegated = name !== undefined && name.startsWith("--no-");
if (isNegated) {
argv = [name.replace("--no-", "--"), ...argv.slice(1)];
}
return this._parse(argv, matches).map(([argv, set]) => [
argv,
Flag.Set.of(isNegated ? mapper(set.value) : set.value, (argv) =>
negate(set)(argv, matches)
),
]);
};
return new Flag(this._name, this._description, options, parse);
}
public choices<U extends T>(...choices: Array<U>): Flag<U> {
return this.filter(
Refinement.equals(...choices),
() =>
`Incorrect value, expected one of ${choices
.map((choice) => `"${choice}"`)
.join(", ")}`
).type(choices.join("|"));
}
public toJSON(): Flag.JSON {
return {
name: this._name,
description: this._description,
options: {
...this._options,
type: this._options.type.getOr(null),
default: this._options.default.map(Serializable.toJSON).getOr(null),
},
};
}
}
/**
* @public
*/
export namespace Flag {
export interface JSON {
[key: string]: json.JSON;
name: string;
description: string;
options: {
[key: string]: json.JSON;
type: string | null;
aliases: Array<string>;
default: json.JSON | null;
optional: boolean;
repeatable: boolean;
};
}
export type Parser<T, A extends Array<unknown> = []> = parser.Parser<
Array<string>,
Set<T>,
string,
A
>;
export interface Options {
readonly type: Option<string>;
readonly aliases: Array<string>;
readonly default: Option<string>;
readonly optional: boolean;
readonly repeatable: boolean;
readonly negatable: boolean;
}
/**
* The `Set<T>` class, from the concept of "flag sets", acts as a container
* for parsed flag values. As flags can be specified multiple times, this
* class allows us to encapsulate the current value of a given flag and a
* parser to parse another instance of the flag value and determine how to
* combine the two.
*/
export class Set<T> implements Functor<T> {
public static of<T>(value: T, parse: Flag.Parser<T>) {
return new Set(value, parse);
}
private readonly _value: T;
private readonly _parse: Flag.Parser<T>;
private constructor(value: T, parse: Flag.Parser<T>) {
this._value = value;
this._parse = parse;
}
public get value(): T {
return this._value;
}
public get parse(): Flag.Parser<T> {
return this._parse;
}
public map<U>(mapper: Mapper<T, U>): Set<U> {
return new Set(mapper(this._value), (argv) =>
this._parse(argv).map(([argv, set]) => [argv, set.map(mapper)])
);
}
}
export function string(name: string, description: string): Flag<string> {
const parse: Flag.Parser<string, [Predicate<string>]> = (argv, matches) => {
const [name, value] = argv;
if (name === undefined || !matches(name)) {
return Err.of("Missing flag");
}
if (value === undefined) {
return Err.of("Missing value");
}
return Result.of([
argv.slice(2),
Flag.Set.of(value, (argv) => parse(argv, matches)),
]);
};
return Flag.of(name, description, parse).type("string");
}
export function number(name: string, description: string): Flag<number> {
const parse: Flag.Parser<number, [Predicate<string>]> = (argv, matches) => {
const [name, value] = argv;
if (name === undefined || !matches(name)) {
return Err.of("Missing flag");
}
if (value === undefined) {
return Err.of("Missing value");
}
const number = Number(value);
if (!Number.isFinite(number)) {
return Err.of(`${value} is not a number`);
}
return Result.of([
argv.slice(2),
Flag.Set.of(number, (argv) => parse(argv, matches)),
]);
};
return Flag.of(name, description, parse).type("number");
}
export function integer(name: string, description: string): Flag<number> {
const parse: Flag.Parser<number, [Predicate<string>]> = (argv, matches) => {
const [name, value] = argv;
if (name === undefined || !matches(name)) {
return Err.of("Missing flag");
}
if (value === undefined) {
return Err.of("Missing value");
}
const number = Number(value);
if (!Number.isInteger(number)) {
return Err.of(`${value} is not an integer`);
}
return Result.of([
argv.slice(2),
Flag.Set.of(number, (argv) => parse(argv, matches)),
]);
};
return Flag.of(name, description, parse).type("integer");
}
export function boolean(name: string, description: string): Flag<boolean> {
const parse: Flag.Parser<boolean, [Predicate<string>]> = (
argv,
matches
) => {
const [name, value] = argv;
if (name === undefined || !matches(name)) {
return Err.of("Missing flag");
}
if (value === undefined || (value !== "true" && value !== "false")) {
return Result.of([
argv.slice(1),
Flag.Set.of(true, (argv) => parse(argv, matches)),
]);
}
return Result.of([
argv.slice(2),
Flag.Set.of(value === "true", (argv) => parse(argv, matches)),
]);
};
return Flag.of(name, description, parse)
.type("boolean")
.negatable((value) => !value);
}
export function empty(name: string, description: string): Flag<void> {
const parse: Flag.Parser<void, [Predicate<string>]> = (argv, matches) => {
const [name] = argv;
if (name === undefined || !matches(name)) {
return Err.of("Missing flag");
}
return Result.of([
argv.slice(1),
Flag.Set.of(undefined, (argv) => parse(argv, matches)),
]);
};
return Flag.of(name, description, parse);
}
export const Help = Symbol("--help");
export function help(description: string): Flag<Option<symbol>> {
return empty("help", description)
.map(() => Help)
.optional();
}
export const Version = Symbol("--version");
export function version(description: string): Flag<Option<symbol>> {
return empty("version", description)
.map(() => Version)
.optional();
}
} | the_stack |
import React, { Component, useEffect, useState } from "react";
import memoize from "memoize-one";
import "./DataPreviewMap.scss";
import DataPreviewMapOpenInNationalMapButton from "./DataPreviewMapOpenInNationalMapButton";
import {
config,
DATASETS_BUCKET,
RawPreviewMapFormatPerferenceItem
} from "config";
import { Medium, Small } from "./Responsive";
import Spinner from "Components/Common/Spinner";
import { ParsedDistribution } from "helpers/record";
import sortBy from "lodash/sortBy";
import {
checkFileForPreview,
FileSizeCheckStatus,
FileSizeCheckResult
} from "helpers/DistributionPreviewUtils";
import DataPreviewSizeWarning from "./DataPreviewSizeWarning";
import urijs from "urijs";
import isStorageApiUrl from "helpers/isStorageApiUrl";
import { useAsync } from "react-async-hook";
import fetch from "isomorphic-fetch";
import xml2json from "../../helpers/xml2json";
import ReactSelect from "react-select";
import CustomStyles from "../Common/react-select/ReactSelectStyles";
const DEFAULT_DATA_SOURCE_PREFERENCE: RawPreviewMapFormatPerferenceItem[] = [
{
format: "WMS",
urlRegex: "^(?!.*(SceneServer)).*$"
},
{
format: "ESRI MAPSERVER",
urlRegex: "MapServer"
},
{
format: "WFS",
urlRegex: "^(?!.*(SceneServer)).*$"
},
{
format: "ESRI FEATURESERVER",
urlRegex: "FeatureServer"
},
{
format: "GeoJSON",
isDataFile: true
},
{
format: "csv-geo-au",
isDataFile: true
},
{
format: "KML",
isDataFile: true
},
{
format: "KMZ",
isDataFile: true
}
];
interface PreviewMapFormatPerferenceItem {
format: string;
isDataFile?: boolean;
urlRegex?: RegExp;
}
let DATA_SOURCE_PREFERENCE: PreviewMapFormatPerferenceItem[];
function getDataSourcePreference(): PreviewMapFormatPerferenceItem[] {
if (DATA_SOURCE_PREFERENCE) {
return DATA_SOURCE_PREFERENCE;
}
const preferenceList: RawPreviewMapFormatPerferenceItem[] = config
?.previewMapFormatPerference?.map
? config?.previewMapFormatPerference
: DEFAULT_DATA_SOURCE_PREFERENCE;
DATA_SOURCE_PREFERENCE = preferenceList.map((item) => {
const { urlRegex, ...newItem } = item;
if (!urlRegex) {
return newItem as PreviewMapFormatPerferenceItem;
}
try {
const regex = new RegExp(item.urlRegex as string);
(newItem as PreviewMapFormatPerferenceItem).urlRegex = regex;
} catch (e) {
console.error(
"Incorrect PreviewMapFormatPerferenceItem Regex: " +
(newItem as PreviewMapFormatPerferenceItem).urlRegex
);
}
return newItem;
});
return DATA_SOURCE_PREFERENCE;
}
export const isSupportedFormat = function (format) {
const dataSourcePreference = getDataSourcePreference().map(
(preferenceItem) => preferenceItem.format
);
return (
dataSourcePreference
.map((item) => item.toLowerCase())
.filter((item) => format.trim().toLowerCase() === item).length !== 0
);
};
type BestDist = {
dist: ParsedDistribution;
index: number;
};
// React 16.3 advice for replacing prop -> state updates for computations
/**
* Determines the best distribution to try to use for mapping
*/
const determineBestDistribution: (
distributions: ParsedDistribution[]
) => BestDist | null = memoize(function determineDistribution(
distributions: ParsedDistribution[]
) {
const distsWithPreferences = distributions
.map((dist) => {
const format = dist.format.toLowerCase().trim();
const dataUrl = dist.downloadURL
? dist.downloadURL
: dist.accessURL;
const distributionPreferenceIndex = getDataSourcePreference().findIndex(
(preferenceItem) => {
if (preferenceItem.format.toLowerCase() !== format) {
return false;
}
if (preferenceItem.urlRegex) {
if (dataUrl && dataUrl.match(preferenceItem.urlRegex)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
);
if (distributionPreferenceIndex === -1) {
return null;
} else {
return { dist, index: distributionPreferenceIndex };
}
})
.filter((x) => !!x) as { dist: ParsedDistribution; index: number }[];
const sorted = sortBy(distsWithPreferences, ({ index }) => index);
if (sorted.length === 0) {
return null;
} else {
return sorted[0];
}
});
type WmsWfsGroupItemType = {
name: string;
title: string;
};
async function fetchWmsWfsItemList(
url?: string,
format?: string
): Promise<WmsWfsGroupItemType[]> {
if (!url || typeof url !== "string") {
return [];
}
if (!format || typeof format !== "string") {
return [];
}
const stdFormatStr = format.trim().toLowerCase();
if (stdFormatStr !== "wms" && stdFormatStr !== "wfs") {
return [];
}
if (url.match(/\W*SceneServer\W*/i)) {
// when url contains `SceneServer`, it will not be valid WFS / WMS url.
// some upstream crawler might incorrectly produce this
return [];
}
const isWms = stdFormatStr === "wms" ? true : false;
try {
const requestUrl = `${config.proxyUrl}_1d/${url}`;
const res = await fetch(requestUrl);
if (!res.ok) {
return [];
}
const resText = await res.text();
const jsonData = xml2json(resText.trim());
if (isWms) {
if (!jsonData?.Capability?.Layer?.Layer?.length) {
// even only one layer, we will return [] as no need to render layer selection dropdown
return [];
}
return jsonData.Capability.Layer.Layer.map((item) => ({
name: item?.Name ? item.Name : "",
title: item?.Title ? item.Title : ""
})).filter((item) => !!item.name);
} else {
if (!jsonData?.FeatureTypeList?.FeatureType?.length) {
// even only one layer, we will return [] as no need to render layer selection dropdown
return [];
}
return jsonData.FeatureTypeList.FeatureType.map((item) => ({
name: item?.Name ? item.Name : "",
title: item?.Title ? item.Title : ""
})).filter((item) => !!item.name);
}
} catch (e) {
return [];
}
}
export default function DataPreviewMapWrapper(props: {
distributions: ParsedDistribution[];
}) {
const [
selectedWmsWfsGroupItemName,
setSelectedWmsWfsGroupItemName
] = useState("");
const bestDist = determineBestDistribution(props.distributions);
let format = bestDist?.dist?.format;
if (!format || typeof format !== "string") {
format = "";
}
format = format.toLocaleLowerCase().trim();
const isWms = format === "wms" ? true : false;
const dataUrl = bestDist?.dist?.downloadURL
? bestDist.dist.downloadURL
: bestDist?.dist?.accessURL;
const { result: wmsWfsGroupItems } = useAsync(fetchWmsWfsItemList, [
dataUrl,
format
]);
if (!bestDist) {
return null;
} else {
return (
<div className="no-print data-preview-map-wrapper">
<h3 className="section-heading">Map Preview</h3>
{wmsWfsGroupItems?.length ? (
<div className="wms-wfs-group-item-selection">
<ReactSelect
placeholder={
isWms
? "Select WMS Layer..."
: "Select WFS Feature Type..."
}
className="accrual-periodicity-select"
styles={CustomStyles}
isSearchable={true}
options={
wmsWfsGroupItems.map((item) => ({
label: item?.title ? item.title : item.name,
value: item.name
})) as any
}
value={
selectedWmsWfsGroupItemName
? {
label: wmsWfsGroupItems.find(
(item) =>
item.name ===
selectedWmsWfsGroupItemName
)?.title,
value: selectedWmsWfsGroupItemName
}
: null
}
onChange={(option) =>
setSelectedWmsWfsGroupItemName(
(option as any).value
)
}
/>
</div>
) : null}
<Small>
<DataPreviewMapOpenInNationalMapButton
distribution={bestDist.dist}
style={{
position: "relative",
top: "10px",
visibility: "visible"
}}
buttonText="View in NationalMap"
/>
</Small>
<Medium>
<DataPreviewMap
bestDist={bestDist}
selectedWmsWfsGroupItemName={
selectedWmsWfsGroupItemName
}
isWms={isWms}
/>
</Medium>
</div>
);
}
}
function DataPreviewMap(props: {
bestDist: BestDist;
selectedWmsWfsGroupItemName: string;
isWms: boolean;
}) {
const [loading, setLoading] = useState(true);
const [overrideFileSizeCheck, setOverrideFileSizeCheck] = useState(false);
const [
fileSizeCheckResult,
setFileSizeCheckResult
] = useState<FileSizeCheckResult | null>(null);
useEffect(() => {
(async () => {
setLoading(true);
// If previewing this data involves downloading a single (potentially massive)
// file, check the file size first. If it's a service, just display it.
if (getDataSourcePreference()[props.bestDist.index].isDataFile) {
setFileSizeCheckResult(
await checkFileForPreview(props.bestDist.dist)
);
} else {
setFileSizeCheckResult({
fileSizeCheckStatus: FileSizeCheckStatus.Ok
});
}
setLoading(false);
})();
}, [props.bestDist]);
if (loading) {
return <Spinner />;
} else if (
!overrideFileSizeCheck &&
fileSizeCheckResult &&
fileSizeCheckResult.fileSizeCheckStatus !== FileSizeCheckStatus.Ok
) {
return (
<DataPreviewSizeWarning
fileSizeCheckResult={fileSizeCheckResult}
preview={() => setOverrideFileSizeCheck(true)}
/>
);
} else {
return (
<DataPreviewMapTerria
key={props.selectedWmsWfsGroupItemName}
distribution={props.bestDist.dist}
isWms={props.isWms}
selectedWmsWfsGroupItemName={props.selectedWmsWfsGroupItemName}
/>
);
}
}
type State = {
loaded: boolean;
errorMessage: string;
isMapInteractive: boolean;
fileSizeCheckResult: FileSizeCheckResult | null;
};
class DataPreviewMapTerria extends Component<
{
distribution: ParsedDistribution;
selectedWmsWfsGroupItemName: string;
isWms: boolean;
},
State
> {
private iframeRef: React.RefObject<HTMLIFrameElement> = React.createRef();
state = {
loaded: false,
errorMessage: "",
isMapInteractive: false,
fileSizeCheckResult: null
};
componentDidMount() {
window.addEventListener("message", this.onIframeMessageReceived);
}
componentWillUnmount() {
window.removeEventListener("message", this.onIframeMessageReceived);
}
componentDidUpdate(prevProps) {
if (
this.props.distribution !== prevProps.distribution &&
this.props.distribution
) {
this.setState({
loaded: false,
errorMessage: ""
});
}
}
handleMapClick = () => {
this.setState({ isMapInteractive: true });
};
handleMapMouseLeave = () => {
this.setState({ isMapInteractive: false });
};
createCatalogItemFromDistribution(
selectedDistribution,
selectedWmsWfsGroupItemName: string,
isWms: boolean
) {
const catalogData: any = {
name: selectedDistribution.title,
type: "magda-item",
url: config.baseUrl,
storageApiUrl: config.storageApiUrl,
distributionId: selectedDistribution.identifier,
// --- default internal storage bucket name
defaultBucket: DATASETS_BUCKET,
isEnabled: true,
zoomOnEnable: true
};
if (selectedWmsWfsGroupItemName) {
if (isWms) {
catalogData.selectedWmsLayerName = selectedWmsWfsGroupItemName;
} else {
catalogData.selectedWfsFeatureTypeName = selectedWmsWfsGroupItemName;
}
}
return {
initSources: [
{
catalog: [catalogData],
baseMapName: "Positron (Light)",
homeCamera: {
north: -8,
east: 158,
south: -45,
west: 109
},
corsDomains: [urijs(config.baseExternalUrl).hostname()]
}
]
};
}
onIframeMessageReceived = (e) => {
const selectedDistribution = this.props.distribution;
if (!selectedDistribution || !this.iframeRef.current) return;
const iframeWindow = this.iframeRef.current.contentWindow;
if (!iframeWindow || iframeWindow !== e.source) return;
if (e.data === "ready") {
iframeWindow.postMessage(
this.createCatalogItemFromDistribution(
selectedDistribution,
this.props.selectedWmsWfsGroupItemName,
this.props.isWms
),
"*"
);
this.setState({
loaded: false,
errorMessage: ""
});
return;
} else if (e.data === "loading complete") {
this.setState({
loaded: true,
errorMessage: ""
});
return;
} else {
try {
const data = JSON.parse(e.data);
if (data?.type === "error") {
this.setState({
loaded: true,
errorMessage: data.message
});
}
} catch (e) {}
}
};
render() {
const shouldHideOpenNationalMapButton =
this.props.distribution.downloadURL &&
isStorageApiUrl(this.props.distribution.downloadURL);
if (this.state.loaded && this.state.errorMessage) {
return (
<div className="error-message-box au-body au-page-alerts au-page-alerts--warning">
<h3>Map Preview Experienced an Error:</h3>
{this.state.errorMessage
.toLowerCase()
.indexOf("status code") !== -1 ? (
<p>
The requested data source might not be available at
this moment.
</p>
) : (
<p>
The requested data source is not in the valid format
or might not be available at this moment.
</p>
)}
</div>
);
}
return (
<div
className="data-preview-map"
onClick={this.handleMapClick}
onMouseLeave={this.handleMapMouseLeave}
>
{!this.state.loaded && <Spinner width="100%" height="420px" />}
{shouldHideOpenNationalMapButton ? null : (
<DataPreviewMapOpenInNationalMapButton
distribution={this.props.distribution}
buttonText="Open in NationalMap"
style={{
position: "absolute",
right: "10px",
top: "10px"
}}
/>
)}
{this.props.distribution.identifier != null && (
<iframe
key={this.props.distribution.identifier}
title={this.props.distribution.title}
width="100%"
height="420px"
frameBorder="0"
src={
config.previewMapUrl +
"#mode=preview&hideExplorerPanel=1"
}
ref={this.iframeRef}
className={[
!this.state.loaded &&
"data-preview-map-iframe_loading",
!this.state.isMapInteractive &&
"data-preview-map-iframe_no-scroll"
]
.filter((c) => !!c)
.join(" ")}
/>
)}
</div>
);
}
} | the_stack |
declare const describe: any;
declare const it: any;
declare const expect: any;
import * as Immutable from "immutable";
import { event, Event, timeEvent } from "../src/event";
import { avg, sum } from "../src/functions";
import { index } from "../src/index";
import { time } from "../src/time";
import { timerange } from "../src/timerange";
const DATE = new Date("2015-04-22T03:30:00Z");
const DEEP_EVENT_DATA = Immutable.fromJS({
NorthRoute: { in: 123, out: 456 },
SouthRoute: { in: 654, out: 223 }
});
const ALT_DEEP_EVENT_DATA = Immutable.fromJS({
NorthRoute: { in: 100, out: 456 },
SouthRoute: { in: 654, out: 200 }
});
const OUTAGE_EVENT_LIST = {
status: "OK",
outageList: [
{
start_time: "2015-04-22T03:30:00Z",
end_time: "2015-04-22T13:00:00Z",
description: "At 13:33 pacific circuit 06519 went down.",
title: "STAR-CR5 < 100 ge 06519 > ANL - Outage",
completed: true,
external_ticket: "",
esnet_ticket: "ESNET-20150421-013",
organization: "Internet2 / Level 3",
type: "U"
},
{
start_time: "2015-04-22T03:30:00Z",
end_time: "2015-04-22T16:50:00Z",
title: "STAR-CR5 < 100 ge 06519 > ANL - Outage",
description: `The listed circuit was unavailable...`,
completed: true,
external_ticket: "3576:144",
esnet_ticket: "ESNET-20150421-013",
organization: "Internet2 / Level 3",
type: "U"
},
{
start_time: "2015-03-04T09:00:00Z",
end_time: "2015-03-04T14:00:00Z",
title: "ANL Scheduled Maintenance",
description: "ANL will be switching border routers...",
completed: true,
external_ticket: "",
esnet_ticket: "ESNET-20150302-002",
organization: "ANL",
type: "P"
}
]
};
describe("Event static", () => {
it("can tell if two events are the same with Event.is()", () => {
const event1 = event(time(DATE), DEEP_EVENT_DATA);
const event2 = event(time(DATE), DEEP_EVENT_DATA);
const event3 = event(time(DATE), ALT_DEEP_EVENT_DATA);
expect(Event.is(event1, event2)).toBeTruthy();
expect(Event.is(event1, event3)).toBeFalsy();
});
it("can detect duplicated event", () => {
const e1 = event(time(DATE), Immutable.Map({ a: 5, b: 6, c: 7 }));
const e2 = event(time(DATE), Immutable.Map({ a: 5, b: 6, c: 7 }));
const e3 = event(time(DATE), Immutable.Map({ a: 6, b: 6, c: 7 }));
// Just check times and type
expect(Event.isDuplicate(e1, e2)).toBeTruthy();
expect(Event.isDuplicate(e1, e3)).toBeTruthy();
// Check times, type and values
expect(Event.isDuplicate(e1, e3, false)).toBeFalsy();
expect(Event.isDuplicate(e1, e2, false)).toBeTruthy();
});
});
describe("Time Events", () => {
it("can create a time event", () => {
const t = time(new Date(1487983075328));
const e = event(t, Immutable.Map({ name: "bob" }));
expect(e.toString()).toEqual(`{"time":1487983075328,"data":{"name":"bob"}}`);
});
it("can create a time event with a serialized object", () => {
const e = timeEvent({
time: 1487983075328,
data: { a: 2, b: 3 }
});
expect(e.toString()).toEqual(`{\"time\":1487983075328,\"data\":{\"a\":2,\"b\":3}}`);
});
it("can set a new value", () => {
const t = time(new Date(1487983075328));
const e = event(t, Immutable.Map({ name: "bob" }));
const ee = e.set("name", "fred");
expect(ee.toString()).toEqual(`{"time":1487983075328,"data":{"name":"fred"}}`);
});
it("can create a Event<Time>, with deep data", () => {
const timestamp = time(DATE);
const event1 = event(timestamp, DEEP_EVENT_DATA);
expect(event1.get("NorthRoute").toJS()).toEqual({ in: 123, out: 456 });
expect(event1.get("SouthRoute").toJS()).toEqual({ in: 654, out: 223 });
});
it("can use dot notation to get values in deep data", () => {
const timestamp = time(new Date("2015-04-22T03:30:00Z"));
const event1 = event(timestamp, DEEP_EVENT_DATA);
const eventValue = event1.get(["NorthRoute", "in"]);
expect(eventValue).toBe(123);
});
});
describe("Indexed Events", () => {
it("can create an IndexedEvent using a existing Index and data", () => {
const event1 = event(index("1d-12355"), Immutable.Map({ value: 42 }));
const expected = "[Thu, 30 Oct 2003 00:00:00 GMT, Fri, 31 Oct 2003 00:00:00 GMT]";
const e = event1.getKey().toTimeRange();
expect(e.toUTCString()).toBe(expected);
expect(event1.get("value")).toBe(42);
});
});
describe("TimeRange Events", () => {
it("can create a TimeRange Event using a object", () => {
// Pick one event
const sampleEvent = Immutable.Map(OUTAGE_EVENT_LIST.outageList[0]);
// Extract the begin and end times TODO: Fix the ts warning here
// @ts-ignore
const beginTime = new Date(sampleEvent.get("start_time"));
// @ts-ignore
const endTime = new Date(sampleEvent.get("end_time"));
const e = event(timerange(beginTime, endTime), sampleEvent);
// tslint:disable-next-line:max-line-length
const expected = `{"timerange":[1429673400000,1429707600000],"data":{"external_ticket":"","start_time":"2015-04-22T03:30:00Z","completed":true,"end_time":"2015-04-22T13:00:00Z","organization":"Internet2 / Level 3","title":"STAR-CR5 < 100 ge 06519 > ANL - Outage","type":"U","esnet_ticket":"ESNET-20150421-013","description":"At 13:33 pacific circuit 06519 went down."}}`;
expect(`${e}`).toBe(expected);
expect(e.begin().getTime()).toBe(1429673400000);
expect(e.end().getTime()).toBe(1429707600000);
expect(e.getKey().humanizeDuration()).toBe("10 hours");
expect(e.get("title")).toBe("STAR-CR5 < 100 ge 06519 > ANL - Outage");
});
});
describe("Event list merge", () => {
it("can merge multiple events together", () => {
const t = time(new Date("2015-04-22T03:30:00Z"));
const event1 = event(t, Immutable.Map({ a: 5, b: 6 }));
const event2 = event(t, Immutable.Map({ c: 2 }));
const merged = Event.merge(Immutable.List([event1, event2]));
expect(merged.get(0).get("a")).toBe(5);
expect(merged.get(0).get("b")).toBe(6);
expect(merged.get(0).get("c")).toBe(2);
});
it("can merge multiple indexed events together", () => {
const event1 = event(index("1h-396206"), Immutable.Map({ a: 5, b: 6 }));
const event2 = event(index("1h-396206"), Immutable.Map({ c: 2 }));
const merged = Event.merge(Immutable.List([event1, event2]));
expect(merged.get(0).get("a")).toBe(5);
expect(merged.get(0).get("b")).toBe(6);
expect(merged.get(0).get("c")).toBe(2);
});
it("can merge multiple timerange events together", () => {
const beginTime = new Date("2015-04-22T03:30:00Z");
const endTime = new Date("2015-04-22T13:00:00Z");
const tr = timerange(beginTime, endTime);
const event1 = event(tr, Immutable.Map({ a: 5, b: 6 }));
const event2 = event(tr, Immutable.Map({ c: 2 }));
const merged = Event.merge(Immutable.List([event1, event2]));
expect(merged.get(0).get("a")).toBe(5);
expect(merged.get(0).get("b")).toBe(6);
expect(merged.get(0).get("c")).toBe(2);
});
it("can deeply merge multiple events together", () => {
const t = time(new Date("2015-04-22T03:30:00Z"));
const event1 = event(t, Immutable.fromJS({ a: 5, b: { c: 6 } }));
const event2 = event(t, Immutable.fromJS({ d: 2, b: { e: 4 } }));
const merged = Event.merge(Immutable.List([event1, event2]), true);
expect(merged.get(0).get("a")).toBe(5);
expect(merged.get(0).get("b.c")).toBe(6);
expect(merged.get(0).get("d")).toBe(2);
expect(merged.get(0).get("b.e")).toBe(4);
});
});
describe("Event field collapsing", () => {
it("can collapse fields down to a single field using an aggregation function", () => {
const t = time(new Date("2015-04-22T03:30:00Z"));
const e = event(t, Immutable.Map({ a: 5, b: 6, c: 7 }));
const result = e.collapse(["a", "b"], "result", avg());
expect(result.get(["result"])).toBe(5.5);
});
it("can sum multiple events together using an Immutable.List", () => {
const t = time(new Date("2015-04-22T03:30:00Z"));
const e = event(t, Immutable.Map({ in: 5, out: 6, status: "ok" }));
const result = e.collapse(["in", "out"], "total", sum(), true);
expect(result.get(["in"])).toBe(5);
expect(result.get(["out"])).toBe(6);
expect(result.get(["status"])).toBe("ok");
expect(result.get(["total"])).toBe(11);
});
});
describe("Event field selecting", () => {
it("can select a subset of fields", () => {
const t = time(new Date("2015-04-22T03:30:00Z"));
const e = event(t, Immutable.Map({ a: 5, b: 6, c: 7 }));
const result = e.select(["a", "b"]);
expect(result.get("a")).toBe(5);
expect(result.get("b")).toBe(6);
expect(result.get("c")).toBeUndefined();
});
});
describe("Event list combining", () => {
it("can sum multiple events together using an Immutable.List", () => {
const t = time("2015-04-22T03:30:00Z");
const events = [
event(t, Immutable.Map({ a: 5, b: 6, c: 7 })),
event(t, Immutable.Map({ a: 2, b: 3, c: 4 })),
event(t, Immutable.Map({ a: 1, b: 2, c: 3 }))
];
const result = Event.combine(Immutable.List(events), sum());
expect(result.get(0).get("a")).toBe(8);
expect(result.get(0).get("b")).toBe(11);
expect(result.get(0).get("c")).toBe(14);
});
it("can pass no events to sum and get back an empty list", () => {
const t = new Date("2015-04-22T03:30:00Z");
const events = Immutable.List();
const result1 = Event.combine(events, sum());
expect(result1.size).toBe(0);
const result2 = Event.combine(Immutable.List(events), sum());
expect(result2.size).toBe(0);
});
it("can sum multiple indexed events together", () => {
const events = Immutable.List([
event(index("1d-1234"), Immutable.Map({ a: 5, b: 6, c: 7 })),
event(index("1d-1234"), Immutable.Map({ a: 2, b: 3, c: 4 })),
event(index("1d-1235"), Immutable.Map({ a: 1, b: 2, c: 3 }))
]);
const result = Event.combine(events, sum());
expect(result.size).toEqual(2);
expect(`${result.get(0).getKey()}`).toBe("1d-1234");
expect(result.get(0).get("a")).toBe(7);
expect(result.get(0).get("b")).toBe(9);
expect(result.get(0).get("c")).toBe(11);
expect(`${result.get(1).getKey()}`).toBe("1d-1235");
expect(result.get(1).get("a")).toBe(1);
expect(result.get(1).get("b")).toBe(2);
expect(result.get(1).get("c")).toBe(3);
});
it("can sum multiple events together if they have different timestamps", () => {
const ts1 = time("2015-04-22T03:30:00Z");
const ts2 = time("2015-04-22T04:00:00Z");
const ts3 = time("2015-04-22T04:30:00Z");
const events = Immutable.List([
event(ts1, Immutable.Map({ a: 5, b: 6, c: 7 })),
event(ts1, Immutable.Map({ a: 2, b: 3, c: 4 })),
event(ts3, Immutable.Map({ a: 1, b: 2, c: 3 }))
]);
const result = Event.combine(events, sum());
expect(result.get(0).get("a")).toBe(7);
});
});
const t1 = time(1445449170000);
const t2 = time(1445449200000);
const t3 = time(1445449230000);
const t4 = time(1445449260000);
const EVENTS = [];
EVENTS.push(
event(
t1,
Immutable.Map({
name: "source1",
in: 2,
out: 11
})
)
);
EVENTS.push(
event(
t2,
Immutable.Map({
name: "source1",
in: 4,
out: 13
})
)
);
EVENTS.push(
event(
t3,
Immutable.Map({
name: "source1",
in: 6,
out: 15
})
)
);
EVENTS.push(
event(
t4,
Immutable.Map({
name: "source1",
in: 8,
out: 18
})
)
);
const EVENT_LIST = Immutable.List(EVENTS);
describe("Event list map generation", () => {
it("should generate the correct key values for a string selector", () => {
expect(Event.map(EVENT_LIST, ["in"])).toEqual({ in: [2, 4, 6, 8] });
});
it("should generate the correct key values for a string selector", () => {
expect(Event.map(EVENT_LIST, ["in", "out"])).toEqual({
in: [2, 4, 6, 8],
out: [11, 13, 15, 18]
});
});
it("should be able to run a simple aggregation calculation", () => {
const result = Event.aggregate(EVENT_LIST, avg(), ["in", "out"]);
expect(result).toEqual({ in: 5, out: 14.25 });
});
}); | the_stack |
import { DebugFlags } from '../debug';
import { EncodedTokenAttributes, OptionalStandardTokenType, StandardTokenType, toOptionalTokenType } from '../encodedTokenAttributes';
import { IEmbeddedLanguagesMap, IGrammar, IToken, ITokenizeLineResult, ITokenizeLineResult2, ITokenTypeMap, StateStack as StackElementDef } from '../main';
import { createMatchers, Matcher } from '../matcher';
import { disposeOnigString, IOnigLib, OnigScanner, OnigString } from '../onigLib';
import { IRawGrammar, IRawRepository, IRawRule } from '../rawGrammar';
import { ruleIdFromNumber, IRuleFactoryHelper, IRuleRegistry, Rule, RuleFactory, RuleId, ruleIdToNumber } from '../rule';
import { FontStyle, ScopeName, ScopePath, ScopeStack, StyleAttributes } from '../theme';
import { clone } from '../utils';
import { BasicScopeAttributes, BasicScopeAttributesProvider } from './basicScopesAttributeProvider';
import { ScopeDependencyProcessor } from './grammarDependencies';
import { _tokenizeString } from './tokenizeString';
export function createGrammar(
scopeName: ScopeName,
grammar: IRawGrammar,
initialLanguage: number,
embeddedLanguages: IEmbeddedLanguagesMap | null,
tokenTypes: ITokenTypeMap | null,
balancedBracketSelectors: BalancedBracketSelectors | null,
grammarRepository: IGrammarRepository & IThemeProvider,
onigLib: IOnigLib
): Grammar {
return new Grammar(
scopeName,
grammar,
initialLanguage,
embeddedLanguages,
tokenTypes,
balancedBracketSelectors,
grammarRepository,
onigLib
); //TODO
}
export interface IThemeProvider {
themeMatch(scopePath: ScopeStack): StyleAttributes | null;
getDefaults(): StyleAttributes;
}
export interface IGrammarRepository {
lookup(scopeName: ScopeName): IRawGrammar | undefined;
injections(scopeName: ScopeName): ScopeName[];
}
export interface Injection {
readonly debugSelector: string;
readonly matcher: Matcher<string[]>;
readonly priority: -1 | 0 | 1; // 0 is the default. -1 for 'L' and 1 for 'R'
readonly ruleId: RuleId;
readonly grammar: IRawGrammar;
}
function collectInjections(result: Injection[], selector: string, rule: IRawRule, ruleFactoryHelper: IRuleFactoryHelper, grammar: IRawGrammar): void {
const matchers = createMatchers(selector, nameMatcher);
const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);
for (const matcher of matchers) {
result.push({
debugSelector: selector,
matcher: matcher.matcher,
ruleId: ruleId,
grammar: grammar,
priority: matcher.priority
});
}
}
function nameMatcher(identifers: ScopeName[], scopes: ScopeName[]): boolean {
if (scopes.length < identifers.length) {
return false;
}
let lastIndex = 0;
return identifers.every(identifier => {
for (let i = lastIndex; i < scopes.length; i++) {
if (scopesAreMatching(scopes[i], identifier)) {
lastIndex = i + 1;
return true;
}
}
return false;
});
}
function scopesAreMatching(thisScopeName: string, scopeName: string): boolean {
if (!thisScopeName) {
return false;
}
if (thisScopeName === scopeName) {
return true;
}
const len = scopeName.length;
return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === '.';
}
export class Grammar implements IGrammar, IRuleFactoryHelper, IOnigLib {
private _rootId: RuleId | -1;
private _lastRuleId: number;
private readonly _ruleId2desc: Rule[];
private readonly _includedGrammars: { [scopeName: string]: IRawGrammar };
private readonly _grammarRepository: IGrammarRepository & IThemeProvider;
private readonly _grammar: IRawGrammar;
private _injections: Injection[] | null;
private readonly _basicScopeAttributesProvider: BasicScopeAttributesProvider;
private readonly _tokenTypeMatchers: TokenTypeMatcher[];
public get themeProvider(): IThemeProvider { return this._grammarRepository; }
constructor(
private readonly _rootScopeName: ScopeName,
grammar: IRawGrammar,
initialLanguage: number,
embeddedLanguages: IEmbeddedLanguagesMap | null,
tokenTypes: ITokenTypeMap | null,
private readonly balancedBracketSelectors: BalancedBracketSelectors | null,
grammarRepository: IGrammarRepository & IThemeProvider,
private readonly _onigLib: IOnigLib
) {
this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(
initialLanguage,
embeddedLanguages
);
this._rootId = -1;
this._lastRuleId = 0;
this._ruleId2desc = [null!];
this._includedGrammars = {};
this._grammarRepository = grammarRepository;
this._grammar = initGrammar(grammar, null);
this._injections = null;
this._tokenTypeMatchers = [];
if (tokenTypes) {
for (const selector of Object.keys(tokenTypes)) {
const matchers = createMatchers(selector, nameMatcher);
for (const matcher of matchers) {
this._tokenTypeMatchers.push({
matcher: matcher.matcher,
type: tokenTypes[selector],
});
}
}
}
}
public dispose(): void {
for (const rule of this._ruleId2desc) {
if (rule) {
rule.dispose();
}
}
}
public createOnigScanner(sources: string[]): OnigScanner {
return this._onigLib.createOnigScanner(sources);
}
public createOnigString(sources: string): OnigString {
return this._onigLib.createOnigString(sources);
}
public getMetadataForScope(scope: string): BasicScopeAttributes {
return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);
}
private _collectInjections(): Injection[] {
const grammarRepository: IGrammarRepository = {
lookup: (scopeName: string): IRawGrammar | undefined => {
if (scopeName === this._rootScopeName) {
return this._grammar;
}
return this.getExternalGrammar(scopeName);
},
injections: (scopeName: string): string[] => {
return this._grammarRepository.injections(scopeName);
},
};
const result: Injection[] = [];
const scopeName = this._rootScopeName;
const grammar = grammarRepository.lookup(scopeName);
if (grammar) {
// add injections from the current grammar
const rawInjections = grammar.injections;
if (rawInjections) {
for (let expression in rawInjections) {
collectInjections(
result,
expression,
rawInjections[expression],
this,
grammar
);
}
}
// add injection grammars contributed for the current scope
const injectionScopeNames = this._grammarRepository.injections(scopeName);
if (injectionScopeNames) {
injectionScopeNames.forEach((injectionScopeName) => {
const injectionGrammar =
this.getExternalGrammar(injectionScopeName);
if (injectionGrammar) {
const selector = injectionGrammar.injectionSelector;
if (selector) {
collectInjections(
result,
selector,
injectionGrammar,
this,
injectionGrammar
);
}
}
});
}
}
result.sort((i1, i2) => i1.priority - i2.priority); // sort by priority
return result;
}
public getInjections(): Injection[] {
if (this._injections === null) {
this._injections = this._collectInjections();
if (DebugFlags.InDebugMode && this._injections.length > 0) {
console.log(
`Grammar ${this._rootScopeName} contains the following injections:`
);
for (const injection of this._injections) {
console.log(` - ${injection.debugSelector}`);
}
}
}
return this._injections;
}
public registerRule<T extends Rule>(factory: (id: RuleId) => T): T {
const id = ++this._lastRuleId;
const result = factory(ruleIdFromNumber(id));
this._ruleId2desc[id] = result;
return result;
}
public getRule(ruleId: RuleId): Rule {
return this._ruleId2desc[ruleIdToNumber(ruleId)];
}
public getExternalGrammar(
scopeName: string,
repository?: IRawRepository
): IRawGrammar | undefined {
if (this._includedGrammars[scopeName]) {
return this._includedGrammars[scopeName];
} else if (this._grammarRepository) {
const rawIncludedGrammar =
this._grammarRepository.lookup(scopeName);
if (rawIncludedGrammar) {
// console.log('LOADED GRAMMAR ' + pattern.include);
this._includedGrammars[scopeName] = initGrammar(
rawIncludedGrammar,
repository && repository.$base
);
return this._includedGrammars[scopeName];
}
}
return undefined;
}
public tokenizeLine(
lineText: string,
prevState: StateStack | null,
timeLimit: number = 0
): ITokenizeLineResult {
const r = this._tokenize(lineText, prevState, false, timeLimit);
return {
tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),
ruleStack: r.ruleStack,
stoppedEarly: r.stoppedEarly,
};
}
public tokenizeLine2(
lineText: string,
prevState: StateStack | null,
timeLimit: number = 0
): ITokenizeLineResult2 {
const r = this._tokenize(lineText, prevState, true, timeLimit);
return {
tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),
ruleStack: r.ruleStack,
stoppedEarly: r.stoppedEarly,
};
}
private _tokenize(
lineText: string,
prevState: StateStack | null,
emitBinaryTokens: boolean,
timeLimit: number
): {
lineLength: number;
lineTokens: LineTokens;
ruleStack: StateStack;
stoppedEarly: boolean;
} {
if (this._rootId === -1) {
this._rootId = RuleFactory.getCompiledRuleId(
this._grammar.repository.$self,
this,
this._grammar.repository
);
}
let isFirstLine: boolean;
if (!prevState || prevState === StateStack.NULL) {
isFirstLine = true;
const rawDefaultMetadata =
this._basicScopeAttributesProvider.getDefaultAttributes();
const defaultStyle = this.themeProvider.getDefaults();
const defaultMetadata = EncodedTokenAttributes.set(
0,
rawDefaultMetadata.languageId,
rawDefaultMetadata.tokenType,
null,
defaultStyle.fontStyle,
defaultStyle.foregroundId,
defaultStyle.backgroundId
);
const rootScopeName = this.getRule(this._rootId).getName(
null,
null
);
let scopeList: AttributedScopeStack;
if (rootScopeName) {
scopeList = AttributedScopeStack.createRootAndLookUpScopeName(
rootScopeName,
defaultMetadata,
this
);
} else {
scopeList = AttributedScopeStack.createRoot(
"unknown",
defaultMetadata
);
}
prevState = new StateStack(
null,
this._rootId,
-1,
-1,
false,
null,
scopeList,
scopeList
);
} else {
isFirstLine = false;
prevState.reset();
}
lineText = lineText + "\n";
const onigLineText = this.createOnigString(lineText);
const lineLength = onigLineText.content.length;
const lineTokens = new LineTokens(
emitBinaryTokens,
lineText,
this._tokenTypeMatchers,
this.balancedBracketSelectors
);
const r = _tokenizeString(
this,
onigLineText,
isFirstLine,
0,
prevState,
lineTokens,
true,
timeLimit
);
disposeOnigString(onigLineText);
return {
lineLength: lineLength,
lineTokens: lineTokens,
ruleStack: r.stack,
stoppedEarly: r.stoppedEarly,
};
}
}
function initGrammar(grammar: IRawGrammar, base: IRawRule | null | undefined): IRawGrammar {
grammar = clone(grammar);
grammar.repository = grammar.repository || <any>{};
grammar.repository.$self = {
$vscodeTextmateLocation: grammar.$vscodeTextmateLocation,
patterns: grammar.patterns,
name: grammar.scopeName
};
grammar.repository.$base = base || grammar.repository.$self;
return grammar;
}
export class AttributedScopeStack {
public static createRoot(scopeName: ScopeName, tokenAttributes: EncodedTokenAttributes): AttributedScopeStack {
return new AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);
}
public static createRootAndLookUpScopeName(scopeName: ScopeName, tokenAttributes: EncodedTokenAttributes, grammar: Grammar): AttributedScopeStack {
const rawRootMetadata = grammar.getMetadataForScope(scopeName);
const scopePath = new ScopeStack(null, scopeName);
const rootStyle = grammar.themeProvider.themeMatch(scopePath);
const resolvedTokenAttributes = AttributedScopeStack.mergeAttributes(
tokenAttributes,
rawRootMetadata,
rootStyle
);
return new AttributedScopeStack(null, scopePath, resolvedTokenAttributes);
}
public get scopeName(): ScopeName { return this.scopePath.scopeName; }
private constructor(
public readonly parent: AttributedScopeStack | null,
public readonly scopePath: ScopeStack,
public readonly tokenAttributes: EncodedTokenAttributes
) {
}
public equals(other: AttributedScopeStack): boolean {
return AttributedScopeStack._equals(this, other);
}
private static _equals(
a: AttributedScopeStack | null,
b: AttributedScopeStack | null
): boolean {
do {
if (a === b) {
return true;
}
if (!a && !b) {
// End of list reached for both
return true;
}
if (!a || !b) {
// End of list reached only for one
return false;
}
if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {
return false;
}
// Go to previous pair
a = a.parent;
b = b.parent;
} while (true);
}
private static mergeAttributes(
existingTokenAttributes: EncodedTokenAttributes,
basicScopeAttributes: BasicScopeAttributes,
styleAttributes: StyleAttributes | null
): EncodedTokenAttributes {
let fontStyle = FontStyle.NotSet;
let foreground = 0;
let background = 0;
if (styleAttributes !== null) {
fontStyle = styleAttributes.fontStyle;
foreground = styleAttributes.foregroundId;
background = styleAttributes.backgroundId;
}
return EncodedTokenAttributes.set(
existingTokenAttributes,
basicScopeAttributes.languageId,
basicScopeAttributes.tokenType,
null,
fontStyle,
foreground,
background
);
}
public pushAttributed(scopePath: ScopePath | null, grammar: Grammar): AttributedScopeStack {
if (scopePath === null) {
return this;
}
if (scopePath.indexOf(' ') === -1) {
// This is the common case and much faster
return AttributedScopeStack._pushAttributed(this, scopePath, grammar);
}
const scopes = scopePath.split(/ /g);
let result: AttributedScopeStack = this;
for (const scope of scopes) {
result = AttributedScopeStack._pushAttributed(result, scope, grammar);
}
return result;
}
private static _pushAttributed(
target: AttributedScopeStack,
scopeName: ScopeName,
grammar: Grammar,
): AttributedScopeStack {
const rawMetadata = grammar.getMetadataForScope(scopeName);
const newPath = target.scopePath.push(scopeName);
const scopeThemeMatchResult =
grammar.themeProvider.themeMatch(newPath);
const metadata = AttributedScopeStack.mergeAttributes(
target.tokenAttributes,
rawMetadata,
scopeThemeMatchResult
);
return new AttributedScopeStack(target, newPath, metadata);
}
public getScopeNames(): string[] {
return this.scopePath.getSegments();
}
}
/**
* Represents a "pushed" state on the stack (as a linked list element).
*/
export class StateStack implements StackElementDef {
_stackElementBrand: void = undefined;
// TODO remove me
public static NULL = new StateStack(
null,
0 as any,
0,
0,
false,
null,
null!,
null!
);
/**
* The position on the current line where this state was pushed.
* This is relevant only while tokenizing a line, to detect endless loops.
* Its value is meaningless across lines.
*/
private _enterPos: number;
/**
* The captured anchor position when this stack element was pushed.
* This is relevant only while tokenizing a line, to restore the anchor position when popping.
* Its value is meaningless across lines.
*/
private _anchorPos: number;
/**
* The depth of the stack.
*/
public readonly depth: number;
constructor(
/**
* The previous state on the stack (or null for the root state).
*/
public readonly parent: StateStack | null,
/**
* The state (rule) that this element represents.
*/
private readonly ruleId: RuleId,
enterPos: number,
anchorPos: number,
/**
* The state has entered and captured \n. This means that the next line should have an anchorPosition of 0.
*/
public readonly beginRuleCapturedEOL: boolean,
/**
* The "pop" (end) condition for this state in case that it was dynamically generated through captured text.
*/
public readonly endRule: string | null,
/**
* The list of scopes containing the "name" for this state.
*/
public readonly nameScopesList: AttributedScopeStack,
/**
* The list of scopes containing the "contentName" (besides "name") for this state.
* This list **must** contain as an element `scopeName`.
*/
public readonly contentNameScopesList: AttributedScopeStack
) {
this.depth = this.parent ? this.parent.depth + 1 : 1;
this._enterPos = enterPos;
this._anchorPos = anchorPos;
}
public equals(other: StateStack): boolean {
if (other === null) {
return false;
}
return StateStack._equals(this, other);
}
private static _equals(a: StateStack, b: StateStack): boolean {
if (a === b) {
return true;
}
if (!this._structuralEquals(a, b)) {
return false;
}
return a.contentNameScopesList.equals(b.contentNameScopesList);
}
/**
* A structural equals check. Does not take into account `scopes`.
*/
private static _structuralEquals(
a: StateStack | null,
b: StateStack | null
): boolean {
do {
if (a === b) {
return true;
}
if (!a && !b) {
// End of list reached for both
return true;
}
if (!a || !b) {
// End of list reached only for one
return false;
}
if (
a.depth !== b.depth ||
a.ruleId !== b.ruleId ||
a.endRule !== b.endRule
) {
return false;
}
// Go to previous pair
a = a.parent;
b = b.parent;
} while (true);
}
public clone(): StateStack {
return this;
}
private static _reset(el: StateStack | null): void {
while (el) {
el._enterPos = -1;
el._anchorPos = -1;
el = el.parent;
}
}
public reset(): void {
StateStack._reset(this);
}
public pop(): StateStack | null {
return this.parent;
}
public safePop(): StateStack {
if (this.parent) {
return this.parent;
}
return this;
}
public push(
ruleId: RuleId,
enterPos: number,
anchorPos: number,
beginRuleCapturedEOL: boolean,
endRule: string | null,
nameScopesList: AttributedScopeStack,
contentNameScopesList: AttributedScopeStack
): StateStack {
return new StateStack(
this,
ruleId,
enterPos,
anchorPos,
beginRuleCapturedEOL,
endRule,
nameScopesList,
contentNameScopesList
);
}
public getEnterPos(): number {
return this._enterPos;
}
public getAnchorPos(): number {
return this._anchorPos;
}
public getRule(grammar: IRuleRegistry): Rule {
return grammar.getRule(this.ruleId);
}
public toString(): string {
const r: string[] = [];
this._writeString(r, 0);
return "[" + r.join(",") + "]";
}
private _writeString(res: string[], outIndex: number): number {
if (this.parent) {
outIndex = this.parent._writeString(res, outIndex);
}
res[
outIndex++
] = `(${this.ruleId}, TODO-${this.nameScopesList}, TODO-${this.contentNameScopesList})`;
return outIndex;
}
public withContentNameScopesList(
contentNameScopeStack: AttributedScopeStack
): StateStack {
if (this.contentNameScopesList === contentNameScopeStack) {
return this;
}
return this.parent!.push(
this.ruleId,
this._enterPos,
this._anchorPos,
this.beginRuleCapturedEOL,
this.endRule,
this.nameScopesList,
contentNameScopeStack
);
}
public withEndRule(endRule: string): StateStack {
if (this.endRule === endRule) {
return this;
}
return new StateStack(
this.parent,
this.ruleId,
this._enterPos,
this._anchorPos,
this.beginRuleCapturedEOL,
endRule,
this.nameScopesList,
this.contentNameScopesList
);
}
// Used to warn of endless loops
public hasSameRuleAs(other: StateStack): boolean {
let el: StateStack | null = this;
while (el && el._enterPos === other._enterPos) {
if (el.ruleId === other.ruleId) {
return true;
}
el = el.parent;
}
return false;
}
}
interface TokenTypeMatcher {
readonly matcher: Matcher<string[]>;
readonly type: StandardTokenType;
}
export class BalancedBracketSelectors {
private readonly balancedBracketScopes: Matcher<string[]>[];
private readonly unbalancedBracketScopes: Matcher<string[]>[];
private allowAny = false;
constructor(
balancedBracketScopes: string[],
unbalancedBracketScopes: string[],
) {
this.balancedBracketScopes = balancedBracketScopes.flatMap((selector) => {
if (selector === '*') {
this.allowAny = true;
return [];
}
return createMatchers(selector, nameMatcher).map((m) => m.matcher);
}
);
this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap((selector) =>
createMatchers(selector, nameMatcher).map((m) => m.matcher)
);
}
public get matchesAlways(): boolean {
return this.allowAny && this.unbalancedBracketScopes.length === 0;
}
public get matchesNever(): boolean {
return this.balancedBracketScopes.length === 0 && !this.allowAny;
}
public match(scopes: string[]): boolean {
for (const excluder of this.unbalancedBracketScopes) {
if (excluder(scopes)) {
return false;
}
}
for (const includer of this.balancedBracketScopes) {
if (includer(scopes)) {
return true;
}
}
return this.allowAny;
}
}
export class LineTokens {
private readonly _emitBinaryTokens: boolean;
/**
* defined only if `DebugFlags.InDebugMode`.
*/
private readonly _lineText: string | null;
/**
* used only if `_emitBinaryTokens` is false.
*/
private readonly _tokens: IToken[];
/**
* used only if `_emitBinaryTokens` is true.
*/
private readonly _binaryTokens: number[];
private _lastTokenEndIndex: number;
private readonly _tokenTypeOverrides: TokenTypeMatcher[];
constructor(
emitBinaryTokens: boolean,
lineText: string,
tokenTypeOverrides: TokenTypeMatcher[],
private readonly balancedBracketSelectors: BalancedBracketSelectors | null,
) {
this._emitBinaryTokens = emitBinaryTokens;
this._tokenTypeOverrides = tokenTypeOverrides;
if (DebugFlags.InDebugMode) {
this._lineText = lineText;
} else {
this._lineText = null;
}
this._tokens = [];
this._binaryTokens = [];
this._lastTokenEndIndex = 0;
}
public produce(stack: StateStack, endIndex: number): void {
this.produceFromScopes(stack.contentNameScopesList, endIndex);
}
public produceFromScopes(
scopesList: AttributedScopeStack,
endIndex: number
): void {
if (this._lastTokenEndIndex >= endIndex) {
return;
}
if (this._emitBinaryTokens) {
let metadata = scopesList.tokenAttributes;
let containsBalancedBrackets = false;
if (this.balancedBracketSelectors?.matchesAlways) {
containsBalancedBrackets = true;
}
if (this._tokenTypeOverrides.length > 0 || (this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever)) {
// Only generate scope array when required to improve performance
const scopes = scopesList.getScopeNames();
for (const tokenType of this._tokenTypeOverrides) {
if (tokenType.matcher(scopes)) {
metadata = EncodedTokenAttributes.set(
metadata,
0,
toOptionalTokenType(tokenType.type),
null,
FontStyle.NotSet,
0,
0
);
}
}
if (this.balancedBracketSelectors) {
containsBalancedBrackets = this.balancedBracketSelectors.match(scopes);
}
}
if (containsBalancedBrackets) {
metadata = EncodedTokenAttributes.set(
metadata,
0,
OptionalStandardTokenType.NotSet,
containsBalancedBrackets,
FontStyle.NotSet,
0,
0
);
}
if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {
// no need to push a token with the same metadata
this._lastTokenEndIndex = endIndex;
return;
}
if (DebugFlags.InDebugMode) {
const scopes = scopesList.getScopeNames();
console.log(' token: |' + this._lineText!.substring(this._lastTokenEndIndex, endIndex).replace(/\n$/, '\\n') + '|');
for (let k = 0; k < scopes.length; k++) {
console.log(' * ' + scopes[k]);
}
}
this._binaryTokens.push(this._lastTokenEndIndex);
this._binaryTokens.push(metadata);
this._lastTokenEndIndex = endIndex;
return;
}
const scopes = scopesList.getScopeNames();
if (DebugFlags.InDebugMode) {
console.log(' token: |' + this._lineText!.substring(this._lastTokenEndIndex, endIndex).replace(/\n$/, '\\n') + '|');
for (let k = 0; k < scopes.length; k++) {
console.log(' * ' + scopes[k]);
}
}
this._tokens.push({
startIndex: this._lastTokenEndIndex,
endIndex: endIndex,
// value: lineText.substring(lastTokenEndIndex, endIndex),
scopes: scopes
});
this._lastTokenEndIndex = endIndex;
}
public getResult(stack: StateStack, lineLength: number): IToken[] {
if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {
// pop produced token for newline
this._tokens.pop();
}
if (this._tokens.length === 0) {
this._lastTokenEndIndex = -1;
this.produce(stack, lineLength);
this._tokens[this._tokens.length - 1].startIndex = 0;
}
return this._tokens;
}
public getBinaryResult(stack: StateStack, lineLength: number): Uint32Array {
if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {
// pop produced token for newline
this._binaryTokens.pop();
this._binaryTokens.pop();
}
if (this._binaryTokens.length === 0) {
this._lastTokenEndIndex = -1;
this.produce(stack, lineLength);
this._binaryTokens[this._binaryTokens.length - 2] = 0;
}
const result = new Uint32Array(this._binaryTokens.length);
for (let i = 0, len = this._binaryTokens.length; i < len; i++) {
result[i] = this._binaryTokens[i];
}
return result;
}
} | the_stack |
async function GithubStats(username: string): Promise<GithubStats> {
const GITHUB_API_URL = 'https://api.github.com';
const LanguageColorMap: {[key in DefinedLanguage]: string } = {
'1C Enterprise': '#814CCC',
ABAP: '#E8274B',
ActionScript: '#882B0F',
Ada: '#02f88c',
Agda: '#315665',
'AGS Script': '#B9D9FF',
Alloy: '#64C800',
AMPL: '#E6EFBB',
AngelScript: '#C7D7DC',
ANTLR: '#9DC3FF',
'API Blueprint': '#2ACCA8',
APL: '#5A8164',
AppleScript: '#101F1F',
Arc: '#aa2afe',
ASP: '#6a40fd',
AspectJ: '#a957b0',
Assembly: '#6E4C13',
ATS: '#1ac620',
AutoHotkey: '#6594b9',
AutoIt: '#1C3552',
Ballerina: '#FF5000',
Batchfile: '#C1F12E',
BlitzMax: '#cd6400',
Boo: '#d4bec1',
Brainfuck: '#2F2530',
C: '#555555',
'C#': '#178600',
'C++': '#f34b7d',
Ceylon: '#dfa535',
Chapel: '#8dc63f',
Cirru: '#ccccff',
Clarion: '#db901e',
Clean: '#3F85AF',
Click: '#E4E6F3',
Clojure: '#db5855',
CoffeeScript: '#244776',
ColdFusion: '#ed2cd6',
'Common Lisp': '#3fb68b',
'Common Workflow Language': '#B5314C',
'Component Pascal': '#B0CE4E',
Crystal: '#776791',
CSS: '#563d7c',
Cuda: '#3A4E3A',
D: '#ba595e',
Dart: '#00B4AB',
DataWeave: '#003a52',
DM: '#447265',
Dockerfile: '#0db7ed',
Dogescript: '#cca760',
Dylan: '#6c616e',
E: '#ccce35',
eC: '#913960',
ECL: '#8a1267',
Eiffel: '#946d57',
Elixir: '#6e4a7e',
Elm: '#60B5CC',
'Emacs Lisp': '#c065db',
EmberScript: '#FFF4F3',
EQ: '#a78649',
Erlang: '#B83998',
'F#': '#b845fc',
Factor: '#636746',
Fancy: '#7b9db4',
Fantom: '#14253c',
FLUX: '#88ccff',
Forth: '#341708',
Fortran: '#4d41b1',
FreeMarker: '#0050b2',
Frege: '#00cafe',
'Game Maker Language': '#8fb200',
Genie: '#fb855d',
Gherkin: '#5B2063',
Glyph: '#e4cc98',
Gnuplot: '#f0a9f0',
Go: '#375eab',
Golo: '#88562A',
Gosu: '#82937f',
'Grammatical Framework': '#79aa7a',
Groovy: '#e69f56',
Hack: '#878787',
Harbour: '#0e60e3',
Haskell: '#5e5086',
Haxe: '#df7900',
HiveQL: '#dce200',
HTML: '#e34c26',
Hy: '#7790B2',
IDL: '#a3522f',
Idris: '#b30000',
Io: '#a9188d',
Ioke: '#078193',
Isabelle: '#FEFE00',
J: '#9EEDFF',
Java: '#b07219',
JavaScript: '#f1e05a',
Jolie: '#843179',
JSONiq: '#40d47e',
Julia: '#a270ba',
'Jupyter Notebook': '#DA5B0B',
Kotlin: '#F18E33',
KRL: '#28431f',
Lasso: '#999999',
Lex: '#DBCA00',
LFE: '#4C3023',
LiveScript: '#499886',
LLVM: '#185619',
LOLCODE: '#cc9900',
LookML: '#652B81',
LSL: '#3d9970',
Lua: '#000080',
Makefile: '#427819',
Mask: '#f97732',
Matlab: '#e16737',
Max: '#c4a79c',
MAXScript: '#00a6a6',
Mercury: '#ff2b2b',
Meson: '#007800',
Metal: '#8f14e9',
Mirah: '#c7a938',
MQL4: '#62A8D6',
MQL5: '#4A76B8',
MTML: '#b7e1f4',
NCL: '#28431f',
Nearley: '#990000',
Nemerle: '#3d3c6e',
nesC: '#94B0C7',
NetLinx: '#0aa0ff',
'NetLinx+ERB': '#747faa',
NetLogo: '#ff6375',
NewLisp: '#87AED7',
Nextflow: '#3ac486',
Nim: '#37775b',
Nit: '#009917',
Nix: '#7e7eff',
Nu: '#c9df40',
'Objective-C': '#438eff',
'Objective-C++': '#6866fb',
'Objective-J': '#ff0c5a',
OCaml: '#3be133',
Omgrofl: '#cabbff',
ooc: '#b0b77e',
Opal: '#f7ede0',
Oxygene: '#cdd0e3',
Oz: '#fab738',
P4: '#7055b5',
Pan: '#cc0000',
Papyrus: '#6600cc',
Parrot: '#f3ca0a',
Pascal: '#E3F171',
PAWN: '#dbb284',
Pep8: '#C76F5B',
Perl: '#0298c3',
'Perl 6': '#0000fb',
PHP: '#4F5D95',
PigLatin: '#fcd7de',
Pike: '#005390',
PLSQL: '#dad8d8',
PogoScript: '#d80074',
PostScript: '#da291c',
PowerBuilder: '#8f0f8d',
PowerShell: '#012456',
Processing: '#0096D8',
Prolog: '#74283c',
'Propeller Spin': '#7fa2a7',
Puppet: '#302B6D',
PureBasic: '#5a6986',
PureScript: '#1D222D',
Python: '#3572A5',
q: '#0040cd',
QML: '#44a51c',
R: '#198CE7',
Racket: '#22228f',
Ragel: '#9d5200',
RAML: '#77d9fb',
Rascal: '#fffaa0',
Rebol: '#358a5b',
Red: '#f50000',
'Ren\'Py': '#ff7f7f',
Ring: '#0e60e3',
Roff: '#ecdebe',
Rouge: '#cc0088',
Ruby: '#701516',
RUNOFF: '#665a4e',
Rust: '#dea584',
SaltStack: '#646464',
SAS: '#B34936',
Scala: '#c22d40',
Scheme: '#1e4aec',
sed: '#64b970',
Self: '#0579aa',
Shell: '#89e051',
Shen: '#120F14',
Slash: '#007eff',
Smalltalk: '#596706',
Solidity: '#AA6746',
SourcePawn: '#5c7611',
SQF: '#3F3F3F',
Squirrel: '#800000',
'SRecode Template': '#348a34',
Stan: '#b2011d',
'Standard ML': '#dc566d',
SuperCollider: '#46390b',
Swift: '#ffac45',
SystemVerilog: '#DAE1C2',
Tcl: '#e4cc98',
Terra: '#00004c',
TeX: '#3D6117',
'TI Program': '#A0AA87',
Turing: '#cf142b',
TypeScript: '#2b7489',
UnrealScript: '#a54c4d',
Vala: '#fbe5cd',
VCL: '#0298c3',
Verilog: '#b2b7f8',
VHDL: '#adb2cb',
'Vim script': '#199f4b',
'Visual Basic': '#945db7',
Volt: '#1F1F1F',
Vue: '#2c3e50',
wdl: '#42f1f4',
WebAssembly: '#04133b',
wisp: '#7582D1',
X10: '#4B6BEF',
xBase: '#403a40',
XC: '#99DA07',
XQuery: '#5232e7',
XSLT: '#EB8CEB',
Yacc: '#4B6C4B',
Zephir: '#118f9e',
};
/* We cache http response to prevent reaching rate limit & to load the page faster */
function getCache(key: string): string | null {
return localStorage.getItem(`github-stats-${key}`);
}
function saveCache(key: string , value: string): void {
localStorage.setItem(`github-stats-${key}`, value);
}
// TODO: typesafe key-value pairs
function getJSONCache<T extends JsonCacheType>(key: T): JsonCacheOptionsMap[T] {
const value = getCache(key);
return value ? JSON.parse(value) : null;
}
// TODO: typesage key-value pairs
function saveJSONCache<T extends JsonCacheType>(key: T, value: JsonCacheOptionsMap[T]): void {
saveCache(key, JSON.stringify(value));
}
function getJSON<T>(url: string): Promise<T | null> {
return fetch(url)
.then((response: Response) => {
if (response.status !== 200) {
return null;
}
return response.json();
});
}
function getText(url: string): Promise<string> {
return fetch(url)
.then((response: Response) => {
if (response.status !== 200) {
return '';
}
return response.text();
});
}
function countBytesWrittenInLanguage(languages: DefinedLanguage[]): LanguageCountMap {
const languageCountMap: LanguageCountMap = {};
languages.forEach((repoLanguage: DefinedLanguage) =>
Object.keys(repoLanguage)
.forEach((language: string) =>
languageCountMap[language] = (languageCountMap[language] || 0) + repoLanguage[language]));
return languageCountMap;
}
function isUsernameChanged(user: string): boolean {
return getCache('username') !== user;
}
const cachedHomepageHTML = getCache('homepageHTML');
const homepageHTML = !isUsernameChanged(username) && cachedHomepageHTML ?
cachedHomepageHTML :
await getText(`https://urlreq.appspot.com/req?method=GET&url=https://github.com/${username}`);
saveCache('homepageHTML', homepageHTML);
const parser = new DOMParser();
const doc = parser.parseFromString(homepageHTML, 'text/html');
const calendarSvg: Element | null = doc.querySelector('.js-calendar-graph-svg')!;
const days: NodeListOf<SVGElementTagNameMap['rect']> = calendarSvg.querySelectorAll(('g > g > rect'));
const commitsByDay = Array.from(days).map((day: SVGElementTagNameMap['rect']) => {
return ({
numCommits: parseInt(day.dataset.count || '0'),
date: day.dataset.date,
});
});
const cachedRepos = getJSONCache('repos');
const repos: Repo[] = !isUsernameChanged(username) && cachedRepos ?
cachedRepos :
(await getJSON(`${GITHUB_API_URL}/users/${username}/repos?per_page=100`) || []);
let percentages;
let repoLanguages: DefinedLanguage[];
let languageCounts: LanguageCountMap;
let sortedLanguages: DefinedLanguage[];
if (repos) {
saveJSONCache('repos', repos);
const cachedRepoLanguages = getJSONCache('repoLanguages');
repoLanguages = !isUsernameChanged(username) && cachedRepoLanguages ?
cachedRepoLanguages :
await Promise.all(repos
.filter((repo: Repo) => !repo.private)
.map((repo: Repo) =>
getJSON(`${GITHUB_API_URL}/repos/${repo.full_name}/languages`))) as DefinedLanguage[];
if (repoLanguages) {
repoLanguages = repoLanguages.filter((repoLanguage: DefinedLanguage) => repoLanguage);
saveJSONCache('repoLanguages', repoLanguages);
languageCounts = countBytesWrittenInLanguage(repoLanguages);
let maxBytes = 0;
for (const language in languageCounts) {
if (languageCounts.hasOwnProperty(language) && languageCounts[language] > maxBytes) {
maxBytes = languageCounts[language];
}
}
sortedLanguages = Object.keys(languageCounts).sort((languageA: DefinedLanguage, languageB: DefinedLanguage) => languageCounts[languageB]! - languageCounts[languageA]!) as DefinedLanguage[];
percentages = sortedLanguages.map((language: DefinedLanguage) => (languageCounts[language]! / maxBytes));
}
}
saveCache('username', username);
return {
commitsContribSVG: (configOptions: Partial<CommitsSVG> = {}) => {
const config: CommitsSVG = {
rows: configOptions.rows || 7,
space: configOptions.space || 2,
rectWidth: configOptions.rectWidth || 12,
levelColors: configOptions.levelColors || [
{
minCommits: 0,
color: '#ebedf0',
},
{
minCommits: 1,
color: '#c6e48b',
},
{
minCommits: 9,
color: '#7bc96f',
},
{
minCommits: 17,
color: '#239a3b',
},
{
minCommits: 26,
color: '#196127',
},
],
};
const cols = Math.ceil(commitsByDay.length / config.rows);
const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgEl.setAttribute('width', `${cols * (config.rectWidth + config.space) - config.space}`);
svgEl.setAttribute('height', `${config.rows * (config.rectWidth + config.space) - config.space}`);
const groupEl = document.createElementNS('http://www.w3.org/2000/svg', 'g');
for (let i = 0; i < commitsByDay.length; i++) {
const col = Math.floor(i / config.rows);
const row = i % config.rows;
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', `${col * (config.rectWidth + config.space)}`);
rect.setAttribute('y', `${row * (config.rectWidth + config.space)}`);
rect.setAttribute('width', `${config.rectWidth}`);
rect.setAttribute('height', `${config.rectWidth}`);
let color = '';
let minCommits = -1;
const mumCommits = commitsByDay[i].numCommits;
// TODO: levelcolor interface
config.levelColors.forEach((levelColor: LevelColor) => {
if (mumCommits >= levelColor.minCommits && levelColor.minCommits > minCommits) {
minCommits = levelColor.minCommits;
color = levelColor.color;
}
});
rect.setAttribute('fill', color);
groupEl.appendChild(rect);
}
svgEl.appendChild(groupEl);
return svgEl;
},
// TODO: config interface
languagesContribSVG: (configOptions: Partial<LanguageSVGConfig> = {}) => {
const config: LanguageSVGConfig = {
barHeight: configOptions.barHeight || 20,
barWidth: configOptions.barWidth || 500,
lineSpacing: configOptions.lineSpacing || 4,
languageNameWidth: configOptions.languageNameWidth || 100,
fontSize: configOptions.fontSize || 14,
};
const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
if (sortedLanguages) {
const svgHeight = (config.barHeight + config.lineSpacing) * sortedLanguages.length - config.lineSpacing;
svgEl.setAttribute('width', `${config.barWidth + 100}`);
svgEl.setAttribute('height', `${svgHeight}`);
svgEl.setAttribute('viewport', `0 0 ${config.barWidth + 100} ${svgHeight}`);
const languages = document.createElementNS('http://www.w3.org/2000/svg', 'g');
languages.setAttribute('transform', `translate(${config.languageNameWidth},0)`);
const bars = document.createElementNS('http://www.w3.org/2000/svg', 'g');
bars.setAttribute('transform', `translate(${config.languageNameWidth},0)`);
for (let i = 0; i < sortedLanguages.length; i++) {
const language = sortedLanguages[i];
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
const top = i * (config.barHeight + config.lineSpacing);
rect.setAttribute('y', `${top}`);
rect.setAttribute('width', `${percentages[i] * config.barWidth}`);
rect.setAttribute('height', `${config.barHeight}`);
rect.setAttribute('fill', LanguageColorMap[language] || 'black');
bars.appendChild(rect);
const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.setAttribute('font-size', config.fontSize.toString());
text.style.fontWeight = 'bolder';
text.setAttribute('text-anchor', 'end');
text.setAttribute('dx', '-10');
text.setAttribute('y', `${config.barHeight / 2 + 4 + top}`);
text.textContent = `${language}`;
languages.appendChild(text);
}
svgEl.appendChild(languages);
svgEl.appendChild(bars);
}
return svgEl;
},
};
} | the_stack |
import {inject} from 'aurelia-dependency-injection';
import {EventAggregator, Subscription} from 'aurelia-event-aggregator';
import {bindable, computedFrom} from 'aurelia-framework';
import {IModdleElement, IShape} from '@process-engine/bpmn-elements_contracts';
import * as bundle from '@process-engine/bpmn-js-custom-bundle';
import {IDiagram} from '@process-engine/solutionexplorer.contracts';
import {diff} from 'bpmn-js-differ';
import {
DiffMode,
IBpmnModdle,
IBpmnModeler,
IBpmnXmlSaveOptions,
ICanvas,
IChangeListEntry,
IChangedElement,
IChangedElementList,
IColorPickerColor,
IDefinition,
IDiffChangeListData,
IDiffChanges,
IDiffElementList,
IElementRegistry,
IEventFunction,
IModeling,
ISolutionEntry,
IViewbox,
NotificationType,
defaultBpmnColors,
} from '../../../contracts/index';
import environment from '../../../environment';
import {ElementNameService} from '../../../services/elementname-service/elementname.service';
import {NotificationService} from '../../../services/notification-service/notification.service';
import {SolutionService} from '../../../services/solution-service/solution.service';
import {getIllegalIdErrors, getValidXml} from '../../../services/xml-id-validation-module/xml-id-validation-module';
@inject('NotificationService', EventAggregator, 'SolutionService')
export class BpmnDiffView {
public currentXml: string;
public previousXml: string;
@bindable() public unconvertedPreviousXml: string;
@bindable() public unconvertedCurrentXml: string;
@bindable() public savedXml: string;
@bindable() public processModelId: string;
@bindable() public deployedXml: string;
public xmlChanges: IDiffChanges;
public leftCanvasModel: HTMLElement;
public rightCanvasModel: HTMLElement;
public lowerCanvasModel: HTMLElement;
public currentDiffMode: DiffMode = DiffMode.NewVsOld;
public showChangeList: boolean;
public noChangesExisting: boolean = true;
public noChangesReason: string;
public totalAmountOfChange: number;
public previousXmlIdentifier: string;
public currentXmlIdentifier: string;
public changeListData: IDiffChangeListData = {
removed: [],
changed: [],
added: [],
layoutChanged: [],
};
public showSavedXml: boolean = true;
private notificationService: NotificationService;
private eventAggregator: EventAggregator;
private leftViewer: IBpmnModeler;
private rightViewer: IBpmnModeler;
private lowerViewer: IBpmnModeler;
private diffModeler: IBpmnModeler;
private currentXmlModeler: IBpmnModeler;
private previousXmlModeler: IBpmnModeler;
private modeling: IModeling;
private elementRegistry: IElementRegistry;
private subscriptions: Array<Subscription>;
private elementNameService: ElementNameService;
private diffDestination: string = 'lastSaved';
private diagramName: string | undefined;
private solutionService: SolutionService;
constructor(
notificationService: NotificationService,
eventAggregator: EventAggregator,
solutionService: SolutionService,
) {
this.notificationService = notificationService;
this.eventAggregator = eventAggregator;
this.elementNameService = new ElementNameService();
this.solutionService = solutionService;
}
public created(): void {
this.leftViewer = this.createNewViewer();
this.rightViewer = this.createNewViewer();
this.lowerViewer = this.createNewViewer();
this.diffModeler = new bundle.modeler();
this.previousXmlModeler = new bundle.modeler();
this.currentXmlModeler = new bundle.modeler();
this.modeling = this.diffModeler.get('modeling');
this.elementRegistry = this.diffModeler.get('elementRegistry');
this.startSynchronizingViewers();
}
public async attached(): Promise<void> {
this.leftViewer.attachTo(this.leftCanvasModel);
this.rightViewer.attachTo(this.rightCanvasModel);
this.lowerViewer.attachTo(this.lowerCanvasModel);
this.syncAllViewers();
this.subscriptions = [
this.eventAggregator.subscribe(environment.events.diffView.changeDiffMode, (diffMode: DiffMode) => {
this.currentDiffMode = diffMode;
this.updateDiffView();
}),
this.eventAggregator.subscribe(environment.events.diffView.toggleChangeList, () => {
this.showChangeList = !this.showChangeList;
}),
this.eventAggregator.subscribe(environment.events.diffView.setDiffDestination, async (data: Array<string>) => {
[this.diffDestination, this.diagramName] = data;
const diffLastSavedXml: boolean = this.diffDestination === 'lastSaved';
if (diffLastSavedXml) {
this.setSavedProcessModelAsPreviousXml();
} else {
const updatingDeployedXmlWasSuccessful: boolean = await this.updateDeployedXml();
const diagramNameIsSet: boolean = this.diagramName !== undefined;
if (updatingDeployedXmlWasSuccessful && diagramNameIsSet) {
this.setCustomProcessModelAsPreviousXml();
return;
}
if (updatingDeployedXmlWasSuccessful) {
this.setDeployedProcessModelAsPreviousXml();
}
}
}),
];
}
public detached(): void {
for (const subscription of this.subscriptions) {
subscription.dispose();
}
}
public savedXmlChanged(): void {
if (this.showSavedXml) {
this.setSavedProcessModelAsPreviousXml();
}
}
public async processModelIdChanged(): Promise<void> {
const hasNoProcessModelId: boolean = this.processModelId === undefined;
if (hasNoProcessModelId) {
this.deployedXml = undefined;
return;
}
const updatingDeploydedXmlWasSuccessfull: boolean = await this.updateDeployedXml();
if (updatingDeploydedXmlWasSuccessfull) {
return;
}
this.diffDestination = 'lastSaved';
this.setSavedProcessModelAsPreviousXml();
}
public deployedXmlChanged(): void {
const processModelIsDeployed: boolean = this.deployedXml !== undefined;
this.eventAggregator.publish(environment.events.bpmnio.showDiffDestinationButton, processModelIsDeployed);
}
public async unconvertedPreviousXmlChanged(): Promise<void> {
await this.importXml(this.unconvertedPreviousXml, this.previousXmlModeler);
this.previousXml = await this.exportXml(this.previousXmlModeler);
this.importXml(this.previousXml, this.rightViewer);
await this.updateXmlChanges();
this.updateDiffView();
}
public async unconvertedCurrentXmlChanged(): Promise<void> {
await this.importXml(this.unconvertedCurrentXml, this.currentXmlModeler);
this.currentXml = await this.exportXml(this.currentXmlModeler);
this.importXml(this.currentXml, this.leftViewer);
await this.updateXmlChanges();
this.updateDiffView();
}
public togglePreviousXml(): void {
this.showSavedXml = !this.showSavedXml;
if (this.showSavedXml) {
this.setSavedProcessModelAsPreviousXml();
} else {
this.setDeployedProcessModelAsPreviousXml();
}
}
@computedFrom('currentDiffMode')
public get diffModeIsNewVsOld(): boolean {
return this.currentDiffMode === DiffMode.NewVsOld;
}
@computedFrom('currentDiffMode')
public get diffModeIsOldVsNew(): boolean {
return this.currentDiffMode === DiffMode.OldVsNew;
}
private syncAllViewers(): void {
const lowerCanvas: ICanvas = this.lowerViewer.get('canvas');
const leftCanvas: ICanvas = this.leftViewer.get('canvas');
const rightCanvas: ICanvas = this.rightViewer.get('canvas');
const changedViewbox: IViewbox = lowerCanvas.viewbox();
leftCanvas.viewbox(changedViewbox);
rightCanvas.viewbox(changedViewbox);
}
private setDeployedProcessModelAsPreviousXml(): void {
this.unconvertedPreviousXml = this.deployedXml;
this.previousXmlIdentifier = 'Deployed';
this.currentXmlIdentifier = 'Filesystem';
this.eventAggregator.publish(environment.events.statusBar.setXmlIdentifier, [
this.previousXmlIdentifier,
this.currentXmlIdentifier,
]);
}
private setCustomProcessModelAsPreviousXml(): void {
this.unconvertedPreviousXml = this.deployedXml;
this.previousXmlIdentifier = this.diagramName;
this.currentXmlIdentifier = this.processModelId;
this.eventAggregator.publish(environment.events.statusBar.setXmlIdentifier, [
this.previousXmlIdentifier,
this.currentXmlIdentifier,
]);
this.diagramName = undefined;
}
private setSavedProcessModelAsPreviousXml(): void {
this.unconvertedPreviousXml = this.savedXml;
this.previousXmlIdentifier = 'Old';
this.currentXmlIdentifier = 'New';
this.eventAggregator.publish(environment.events.statusBar.setXmlIdentifier, [
this.previousXmlIdentifier,
this.currentXmlIdentifier,
]);
}
private async updateDeployedXml(): Promise<boolean> {
const activeSolutionEntry: ISolutionEntry = this.solutionService.getSolutionEntryForUri(this.diffDestination);
const activeSolutionEntryNotFound: boolean = activeSolutionEntry === undefined;
if (activeSolutionEntryNotFound) {
return false;
}
const diagramName: string = this.diagramName ? this.diagramName : this.processModelId;
const getXmlFromDeployed: () => Promise<string> = async (): Promise<string> => {
try {
const diagram: IDiagram = await activeSolutionEntry.service.loadDiagram(diagramName);
const diagramFound: boolean = diagram !== undefined;
return diagramFound ? diagram.xml : undefined;
} catch {
return undefined;
}
};
this.deployedXml = await getXmlFromDeployed();
const diagramIsNotDeployed: boolean = this.deployedXml === undefined;
const diffingAgainstDeployed: boolean = this.diffDestination !== 'lastSaved';
if (diagramIsNotDeployed && diffingAgainstDeployed) {
const errorMessage: string =
'Could not diff against the deployed version: This diagram is not deployed to the ProcessEngine.';
this.notificationService.showNotification(NotificationType.ERROR, errorMessage);
return false;
}
return true;
}
private async updateXmlChanges(): Promise<void> {
/**
* TODO: This is a dirty fix, so that the model parser does not
* get an undefined string.
*
* We need to find out, where this value gets set to undefined
* and prevent this issue there.
*/
const previousXmlIsNotDefined: boolean = this.previousXml === undefined;
if (previousXmlIsNotDefined) {
this.previousXml = this.currentXml;
}
const previousDefinitions: IDefinition = await this.getDefintionsFromXml(this.previousXml);
const newDefinitions: IDefinition = await this.getDefintionsFromXml(this.currentXml);
this.xmlChanges = diff(previousDefinitions, newDefinitions);
this.prepareChangesForChangeList();
}
private async getDefintionsFromXml(xml: string): Promise<any> {
const moddle: IBpmnModdle = this.diffModeler.get('moddle');
const {rootElement: definitions} = await moddle.fromXML(xml);
return definitions;
}
private getChangeListEntriesFromChanges(
elementChanges: IDiffElementList | IChangedElementList,
): Array<IChangeListEntry> {
const changeListEntries: Array<IChangeListEntry> = [];
const elementIds: Array<string> = Object.keys(elementChanges);
for (const elementId of elementIds) {
const elementChange: any = elementChanges[elementId];
const isElementAChangedElement: boolean = elementChange.$type === undefined;
const changeListEntry: IChangeListEntry = isElementAChangedElement
? this.createChangeListEntry(elementChange.model.name, elementChange.model.$type)
: this.createChangeListEntry(elementChange.name, elementChange.$type);
changeListEntries.push(changeListEntry);
}
return changeListEntries;
}
/*
* This function converts the object from the bpmn-differ into an object with arrays
* to make it loopable in the html.
*/
private prepareChangesForChangeList(): void {
this.changeListData.removed = [];
this.changeListData.changed = [];
this.changeListData.added = [];
this.changeListData.layoutChanged = [];
const changedElement: IChangedElementList = this.removeElementsWithoutChanges(this.xmlChanges._changed);
this.changeListData.removed = this.getChangeListEntriesFromChanges(this.xmlChanges._removed);
this.changeListData.changed = this.getChangeListEntriesFromChanges(changedElement);
this.changeListData.added = this.getChangeListEntriesFromChanges(this.xmlChanges._added);
this.changeListData.layoutChanged = this.getChangeListEntriesFromChanges(this.xmlChanges._layoutChanged);
this.totalAmountOfChange =
this.changeListData.removed.length +
this.changeListData.changed.length +
this.changeListData.added.length +
this.changeListData.layoutChanged.length;
this.noChangesExisting = this.totalAmountOfChange === 0;
if (this.noChangesExisting) {
this.setNoChangesReason();
} else {
this.noChangesReason = '';
}
}
private setNoChangesReason(): void {
/*
* This Regex removes all newlines and spaces to make sure that both xml
* are not formatted.
*/
const whitespaceAndNewLineRegex: RegExp = /\r?\n|\r|\s/g;
const unformattedXml: string = this.currentXml.replace(whitespaceAndNewLineRegex, '');
const unformattedSaveXml: string = this.previousXml.replace(whitespaceAndNewLineRegex, '');
const diagramIsUnchanged: boolean = unformattedSaveXml === unformattedXml;
if (diagramIsUnchanged) {
this.noChangesReason = 'The two diagrams are identical.';
} else {
this.noChangesReason = 'The two diagrams are incomparable.';
}
}
private createChangeListEntry(elementName: string, elementType: string): IChangeListEntry {
const humanReadableElementName: string = this.elementNameService.getHumanReadableName(elementName);
const humanReadableElementType: string = this.elementNameService.getHumanReadableType(elementType);
const changeListEntry: IChangeListEntry = {
name: humanReadableElementName,
type: humanReadableElementType,
};
return changeListEntry;
}
private startSynchronizingViewers(): void {
const lowerCanvas: ICanvas = this.lowerViewer.get('canvas');
const leftCanvas: ICanvas = this.leftViewer.get('canvas');
const rightCanvas: ICanvas = this.rightViewer.get('canvas');
this.setEventFunctions(lowerCanvas, leftCanvas, rightCanvas);
this.setEventFunctions(leftCanvas, rightCanvas, lowerCanvas);
this.setEventFunctions(rightCanvas, lowerCanvas, leftCanvas);
}
private setEventFunctions(changingCanvas: ICanvas, firstCanvas: ICanvas, secondCanvas: ICanvas): void {
const changingCanvasContainer: HTMLElement = changingCanvas._container;
const adjustViewboxes: IEventFunction = (): void => {
const changedViewbox: IViewbox = changingCanvas.viewbox();
firstCanvas.viewbox(changedViewbox);
secondCanvas.viewbox(changedViewbox);
};
const startCheckingForMouseMovement: IEventFunction = (): void => {
window.onmousemove = adjustViewboxes;
};
const stopCheckingForMousemovement: IEventFunction = (): void => {
window.onmousemove = null;
};
changingCanvasContainer.onwheel = adjustViewboxes;
changingCanvasContainer.onmousedown = startCheckingForMouseMovement;
changingCanvasContainer.onmouseup = stopCheckingForMousemovement;
}
private markAddedElements(addedElements: IDiffElementList): void {
const elementsToBeColored: Array<IShape> = this.getElementsToBeColored(addedElements);
this.colorizeElements(elementsToBeColored, defaultBpmnColors.green);
}
private markRemovedElements(deletedElements: IDiffElementList): void {
const elementsToBeColored: Array<IShape> = this.getElementsToBeColored(deletedElements);
this.colorizeElements(elementsToBeColored, defaultBpmnColors.red);
}
private markElementsWithLayoutChanges(elementsWithLayoutChanges: IDiffElementList): void {
const elementsToBeColored: Array<IShape> = this.getElementsToBeColored(elementsWithLayoutChanges);
this.colorizeElements(elementsToBeColored, defaultBpmnColors.purple);
}
private markChangedElements(changedElements: IChangedElementList): void {
const changedElementsWithChanges: IChangedElementList = this.removeElementsWithoutChanges(changedElements);
const elementsToBeColored: Array<IShape> = this.getChangedElementsToBeColored(changedElementsWithChanges);
this.colorizeElements(elementsToBeColored, defaultBpmnColors.orange);
}
/*
* This function removes all elements without any changes from the changedElement object
* and returns an object without these elements.
*
* This is needed because the diff function always adds the start event
* to the changed Elements even though it has no changes.
*
* @param changedElement The _changed object of the object that gets returned by the bpmn-differ.
* @returns The same object without the elements that did not get changed.
*/
private removeElementsWithoutChanges(changedElements: IChangedElementList): IChangedElementList {
const copyOfChangedElements: IChangedElementList = Object.assign({}, changedElements);
Object.keys(copyOfChangedElements).forEach((element: string) => {
const currentElementHasNoChanges: boolean = Object.keys(copyOfChangedElements[element].attrs).length === 0;
if (currentElementHasNoChanges) {
delete copyOfChangedElements[element];
}
});
return copyOfChangedElements;
}
private updateDiffView(): void {
if (this.diffModeIsNewVsOld) {
this.updateLowerDiff(this.currentXml);
} else if (this.diffModeIsOldVsNew) {
this.updateLowerDiff(this.previousXml);
}
}
private async updateLowerDiff(xml: string): Promise<void> {
const xmlIsNotLoaded: boolean = xml === undefined || xml === null;
if (xmlIsNotLoaded) {
const notificationMessage: string =
'The xml could not be loaded. Please try to reopen the Diff View or reload the Detail View.';
this.notificationService.showNotification(NotificationType.ERROR, notificationMessage);
return;
}
const addedElements: IDiffElementList = this.xmlChanges._added;
const removedElements: IDiffElementList = this.xmlChanges._removed;
const changedElements: IChangedElementList = this.xmlChanges._changed;
const layoutChangedElements: IDiffElementList = this.xmlChanges._layoutChanged;
const diffModeIsCurrentVsPrevious: boolean = this.currentDiffMode === DiffMode.NewVsOld;
await this.importXml(xml, this.diffModeler);
this.clearColors();
this.markElementsWithLayoutChanges(layoutChangedElements);
this.markChangedElements(changedElements);
if (diffModeIsCurrentVsPrevious) {
this.markAddedElements(addedElements);
} else {
this.markRemovedElements(removedElements);
}
const coloredXml: string = await this.exportXml(this.diffModeler);
await this.importXml(coloredXml, this.lowerViewer);
}
private async importXml(xml: string, viewer: IBpmnModeler): Promise<void> {
const xmlIsNotLoaded: boolean = xml === undefined || xml === null;
if (xmlIsNotLoaded) {
const notificationMessage: string =
'The xml could not be loaded. Please try to reopen the Diff View or reload the Detail View.';
this.notificationService.showNotification(NotificationType.ERROR, notificationMessage);
return;
}
const result = await viewer.importXML(xml);
const {warnings} = result;
const illegalIdErrors = getIllegalIdErrors(warnings);
if (illegalIdErrors.length > 0) {
const {xml: newXml} = getValidXml(xml, illegalIdErrors);
await this.importXml(newXml, viewer);
return;
}
this.fitDiagramToViewport(viewer);
}
private fitDiagramToViewport(viewer: IBpmnModeler): void {
const canvas: ICanvas = viewer.get('canvas');
const viewbox: IViewbox = canvas.viewbox();
const diagramIsVisible: boolean = viewbox.height > 0 && viewbox.width > 0;
if (diagramIsVisible) {
canvas.zoom('fit-viewport', 'auto');
}
}
private async exportXml(modeler: IBpmnModeler): Promise<string> {
const xmlSaveOptions: IBpmnXmlSaveOptions = {
format: true,
};
const {xml} = await modeler.saveXML(xmlSaveOptions);
return xml;
}
private createNewViewer(): IBpmnModeler {
return new bundle.viewer({
additionalModules: [bundle.ZoomScrollModule, bundle.MoveCanvasModule],
});
}
private getChangedElementsToBeColored(changedElementList: IChangedElementList): Array<IShape> {
return Object.values(changedElementList)
.filter((element: IChangedElement) => {
return element.model.$type !== 'bpmn:Collaboration' && element.model.$type !== 'bpmn:Process';
})
.map((element: IChangedElement) => {
const currentElement: IShape = this.elementRegistry.get(element.model.id);
return currentElement;
});
}
private getElementsToBeColored(elements: IDiffElementList): Array<IShape> {
return Object.values(elements)
.filter((element: IModdleElement) => {
return element.$type !== 'bpmn:Collaboration' && element.$type !== 'bpmn:Process';
})
.map((element: IModdleElement) => {
const currentElement: IShape = this.elementRegistry.get(element.id);
return currentElement;
});
}
private clearColors(): void {
const elementsToBeColored: Array<IShape> = this.elementRegistry.filter((element: IShape): boolean => {
const elementHasFillColor: boolean = element.businessObject.di.fill !== undefined;
const elementHasBorderColor: boolean = element.businessObject.di.stroke !== undefined;
const elementHasColor: boolean = elementHasFillColor || elementHasBorderColor;
return elementHasColor;
});
this.colorizeElements(elementsToBeColored, defaultBpmnColors.none);
}
private colorizeElements(elementsToBeColored: Array<IShape>, color: IColorPickerColor): void {
const noElementsToBeColored: boolean = elementsToBeColored.length === 0;
if (noElementsToBeColored) {
return;
}
this.modeling.setColor(elementsToBeColored, {
stroke: color.border,
fill: color.fill,
});
}
} | the_stack |
import {
IConnection,
Diagnostic,
DiagnosticSeverity,
TextDocuments,
ErrorMessageTracker,
DidChangeConfigurationParams
} from "vscode-languageserver";
import { TextDocument } from 'vscode-languageserver-textdocument';
import { URI } from 'vscode-uri';
import * as path from 'path';
let stripJsonComments: any = require('strip-json-comments');
import fs = require('fs');
import * as htmlhint from '../htmlhint';
import { replaceIsPrintAttr } from "../utils/strings";
import { customRules } from "./customRules";
import { HTMLHint } from 'htmlhint';
let islintingEnabled = true;
let htmlhintrcOptions: any = {};
interface Settings {
htmlhint: {
enable: boolean;
options: any;
}
[key: string]: any;
}
let settings: Settings | null = null;
interface ITagType {
denyTag?: string;
selfclosing?: boolean;
attrsRequired?: string[];
redundantAttrs?: string[];
attrsOptional?: [string, string][]
}
export const tagsTypings: { [key: string]: ITagType } = {
br: {
denyTag: 'error',
},
a: {
selfclosing: false,
attrsRequired: ['href'],
redundantAttrs: ['alt']
},
div: {
selfclosing: false
},
main: {
selfclosing: false,
redundantAttrs: ['role']
},
nav: {
selfclosing: false,
redundantAttrs: ['role']
},
script: {
attrsOptional: [['async', 'async'], ['defer', 'defer']],
redundantAttrs: ['type=javascript,text/javascript']
},
img: {
selfclosing: true,
attrsRequired: [
'src', 'alt'
]
},
area: {
selfclosing: true
},
base: {
selfclosing: true
},
col: {
selfclosing: true
},
embed: {
selfclosing: true
},
hr: {
selfclosing: true
},
input: {
selfclosing: true
},
keygen: {
selfclosing: true
},
link: {
selfclosing: true
},
menuitem: {
selfclosing: true
},
meta: {
selfclosing: true
},
param: {
selfclosing: true
},
source: {
selfclosing: true
},
track: {
selfclosing: true
},
wbr: {
selfclosing: true
}
};
const defaultLinterConfig = {
"tagname-lowercase": true,
"attr-lowercase": true,
"attr-value-double-quotes": false,
"doctype-first": false,
"max-length": false,
"tag-pair": true,
"spec-char-escape": false,
"id-unique": false,
"src-not-empty": true,
"attr-no-duplication": true,
"title-require": false,
"doctype-html5": true,
"space-tab-mixed-disabled": "space",
"inline-style-disabled": true,
"tag-self-close": true,
"localize-strings": true,
"encoding-off-warn": true,
"unsafe-external-link": true,
"no-html-comment": true,
"no-div-without-class": true,
"aria-attr-exists": true,
"aria-attr-has-proper-value": true,
"sfcc-custom-tags": true,
"no-aria-hidden-with-hidden-attr" : true,
"for-attr-is-allowed-for-label-and-output": true,
"no-whitespace-in-id-attr": true,
"tags-check": {
"isslot": {
"selfclosing": true,
"attrsRequired": ["id", ["context", "global", "category", "folder"], "description"]
},
"iscache": {
"selfclosing": true,
"attrsRequired": ["hour|minute", ["type", "relative", "daily"]],
"attrsOptional": [["varyby", "price_promotion"]]
},
"isdecorate": {
"selfclosing": false,
"attrsRequired": ["template"]
},
"isreplace": {
"selfclosing": true
},
"isinclude": {
"selfclosing": true,
"attrsRequired": ["template|url"]
},
"iscontent": {
"selfclosing": true,
"attrsOptional": [["encoding", "on", "off", "html", "xml", "wml"], ["compact", "true", "false"]],
"attrsRequired": ["type", "charset"]
},
"ismodule": {
"selfclosing": true,
"attrsRequired": ["template", "name"]
},
"isobject": {
"selfclosing": false,
"attrsRequired": ["object", ["view", "none", "searchhit", "recommendation", "setproduct", "detail"]]
},
"isset": {
"selfclosing": true,
"attrsRequired": ["name", "value", ["scope", "session", "request", "page", "pdict"]]
},
"iscomponent": {
"selfclosing": true,
"attrsRequired": ["pipeline"]
},
"iscontinue": {
"selfclosing": true
},
"isbreak": {
"selfclosing": true
},
"isnext": {
"selfclosing": true
},
"isscript": {
"selfclosing": false,
denyTag: 'warn'
},
"iselse": {
"selfclosing": true
},
"isloop": {
"selfclosing": false,
"attrsRequired": ["items|iterator|begin", "alias|var|end"]
},
"isif": {
"selfclosing": false,
"attrsRequired": ["condition"]
},
"iselseif": {
"selfclosing": true,
"attrsRequired": ["condition"]
},
"isprint": {
"selfclosing": true,
"attrsRequired": ["value"],
"attrsOptional": [["encoding", "on", "off", "htmlcontent", "htmlsinglequote", "htmldoublequote", "htmlunquote", "jshtml", "jsattribute", "jsblock", "jssource", "jsonvalue", "uricomponent", "uristrict", "xmlcontent", "xmlsinglequote", "xmldoublequote", "xmlcomment"], ["timezone", "SITE", "INSTANCE", "utc"]]
},
"isstatus": {
"selfclosing": true,
"attrsRequired": ["value"]
},
"isredirect": {
"selfclosing": true,
"attrsOptional": [["permanent", "true", "false"]],
"attrsRequired": ["location"]
},
"isinputfield": {
"selfclosing": true,
"attrsRequired": ["type", "formfield"]
}
}
};
export const encodingValues = ["on", "htmlcontent", "htmlsinglequote", "htmldoublequote", "htmlunquote", "jshtml", "jsattribute", "jsblock", "jssource", "jsonvalue", "uricomponent", "uristrict", "xmlcontent", "xmlsinglequote", "xmldoublequote", "xmlcomment"];
function getErrorMessage(err: any, document: TextDocument): string {
let result: string;
if (typeof err.message === 'string' || err.message instanceof String) {
result = <string>err.message;
} else {
result = `An unknown error occurred while validating file: ${URI.parse(document.uri).fsPath}`;
}
return result;
}
/**
* Given a path to a .htmlhintrc file, load it into a javascript object and return it.
*/
function loadConfigurationFile(configFile: string): any {
var ruleSet: any = null;
if (fs.existsSync(configFile)) {
var config = fs.readFileSync(configFile, 'utf8');
try {
ruleSet = JSON.parse(stripJsonComments(config));
}
catch (e) {
console.warn('The .htmlhintrc configuration file is invalid. Source: ' + configFile);
console.warn(e);
}
}
return ruleSet;
}
export function validateTextDocument(connection: IConnection, document: TextDocument): void {
try {
doValidate(connection, document);
} catch (err) {
connection.window.showErrorMessage(getErrorMessage(err, document));
}
}
/**
* Get the html-hint configuration settings for the given html file. This method will take care of whether to use
* VS Code settings, or to use a .htmlhintrc file.
*/
function getConfiguration(filePath: string): any {
var options: any;
if (
settings &&
settings.htmlhint &&
settings.htmlhint.options &&
Object.keys(settings.htmlhint.options).length > 0
) {
options = settings.htmlhint.options;
}
else {
options = findConfigForHtmlFile(filePath);
}
options = options || {};
return options;
}
/**
* Given the path of an html file, this function will look in current directory & parent directories
* to find a .htmlhintrc file to use as the linter configuration. The settings are
*/
function findConfigForHtmlFile(base: string) {
var options: any;
if (fs.existsSync(base)) {
// find default config file in parent directory
if (fs.statSync(base).isDirectory() === false) {
base = path.dirname(base);
}
while (base && !options) {
var tmpConfigFile = path.resolve(base + path.sep, '.htmlhintrc');
// undefined means we haven't tried to load the config file at this path, so try to load it.
if (htmlhintrcOptions[tmpConfigFile] === undefined) {
htmlhintrcOptions[tmpConfigFile] = loadConfigurationFile(tmpConfigFile);
}
// defined, non-null value means we found a config file at the given path, so use it.
if (htmlhintrcOptions[tmpConfigFile]) {
options = htmlhintrcOptions[tmpConfigFile];
break;
}
base = base.substring(0, base.lastIndexOf(path.sep));
}
}
return options;
}
/**
* Given an htmlhint Error object, approximate the text range highlight
*/
function getRange(error: htmlhint.Error, lines: string[]): any {
const line = lines[error.line - 1];
var isWhitespace = false;
var curr = error.col;
while (curr < line.length && !isWhitespace) {
var char = line[curr];
isWhitespace = (char === ' ' || char === '\t' || char === '\n' || char === '\r' || char === '<');
++curr;
}
if (isWhitespace) {
--curr;
}
return {
start: {
line: error.line - 1, // Html-hint line numbers are 1-based.
character: error.col - 1
},
end: {
line: error.line - 1,
character: curr
}
};
}
const evidenceMap = {
'warning': DiagnosticSeverity.Warning,
'warn': DiagnosticSeverity.Warning,
'error': DiagnosticSeverity.Error,
'info': DiagnosticSeverity.Information,
'hint': DiagnosticSeverity.Hint
}
/**
* Given an htmlhint.Error type return a VS Code server Diagnostic object
*/
function makeDiagnostic(problem: htmlhint.Error, lines: string[]): Diagnostic {
return {
severity: evidenceMap[problem.type] || DiagnosticSeverity.Error,
message: problem.message,
range: getRange(problem, lines),
code: problem.rule.id
};
}
function replaceSystemPlaceholders(str: string) {
let currentPos = -1;
while ((currentPos = str.indexOf('${', currentPos + 1)) !== -1) {
const closingTag = str.indexOf('}', currentPos);
if (closingTag > -1) {
const content = str.substr(currentPos, closingTag - currentPos + 1);
str = str.substr(0, currentPos) + content.replace(/[^\n^\r]/ig, '_') + str.substr(closingTag + 1);
currentPos = -1; // reset pos since content may shift
}
};
return str;
}
function doValidate(connection: IConnection, document: TextDocument): void {
const uri = document.uri;
if (islintingEnabled) {
try {
const fsPath = URI.parse(document.uri).fsPath;
const contents = replaceSystemPlaceholders(replaceIsPrintAttr(document.getText()));
const lines = contents.split('\n');
const config = Object.assign({}, defaultLinterConfig, getConfiguration(fsPath)); //;
const errors: htmlhint.Error[] = HTMLHint && HTMLHint.verify(contents, config);
const diagnostics: Diagnostic[] = [];
if (errors.length > 0) {
errors.forEach(each => {
diagnostics.push(makeDiagnostic(each, lines));
});
}
connection.sendDiagnostics({ uri, diagnostics });
} catch (err) {
if (typeof err.message === 'string' || err.message instanceof String) {
throw new Error(<string>err.message);
}
throw err;
}
} else {
connection.sendDiagnostics({ uri, diagnostics: [] });
}
}
function validateAllTextDocuments(connection: IConnection, documents: TextDocument[]): void {
let tracker = new ErrorMessageTracker();
documents.forEach(document => {
try {
validateTextDocument(connection, document);
} catch (err) {
tracker.add(getErrorMessage(err, document));
}
});
tracker.sendErrors(connection);
}
export function disableLinting(connection: IConnection, documents: TextDocuments<TextDocument>) {
islintingEnabled = false;
let tracker = new ErrorMessageTracker();
documents.all().forEach(document => {
try {
validateTextDocument(connection, document);
} catch (err) {
tracker.add(getErrorMessage(err, document));
}
});
tracker.sendErrors(connection);
connection.onDidChangeWatchedFiles(() => { })
}
export function enableLinting(connection: IConnection, documents: TextDocuments<TextDocument>) {
islintingEnabled = true;
HTMLHint && customRules.forEach(rule => HTMLHint && HTMLHint.addRule(rule));
// The watched .htmlhintrc has changed. Clear out the last loaded config, and revalidate all documents.
connection.onDidChangeWatchedFiles((params) => {
for (var i = 0; i < params.changes.length; i++) {
htmlhintrcOptions[URI.parse(params.changes[i].uri).fsPath] = undefined;
}
validateAllTextDocuments(connection, documents.all());
})
}
export function onDidChangeConfiguration(connection: IConnection, documents: TextDocuments<TextDocument>, params: DidChangeConfigurationParams) {
settings = params.settings;
if (
settings &&
settings.extension &&
settings.extension.prophet &&
settings.extension.prophet.htmlhint &&
settings.extension.prophet.htmlhint.enabled &&
!islintingEnabled
) {
enableLinting(connection, documents);
connection.console.log('htmlhint enabled');
} else if (
settings &&
settings.extension &&
settings.extension.prophet &&
settings.extension.prophet.htmlhint &&
!settings.extension.prophet.htmlhint.enabled && islintingEnabled
) {
connection.console.log('htmlhint disabled');
disableLinting(connection, documents);
}
}; | the_stack |
import type * as appsync from '@aws-cdk/aws-appsync';
import { isOptional, Meta, Shape, ShapeGuards, timestamp, UnionShape } from '@punchcard/shape';
import { UserPool } from '../../cognito/user-pool';
import { Build } from '../../core/build';
import { CDK } from '../../core/cdk';
import { Construct, Scope } from '../../core/construct';
import { Resource } from '../../core/resource';
import { toAuthDirectives } from '../lang';
import { VExpression } from '../lang/expression';
import { StatementGuards } from '../lang/statement';
import { VBool, VInteger, VNothing, VObject, VUnion } from '../lang/vtl-object';
import { ApiFragment, ApiFragments } from './api-fragment';
import { AuthMetadata } from './auth';
import { CacheMetadata, CachingConfiguration } from './caching';
import { GqlApiClient, GqlResult } from './client';
import { InterpreterState, interpretProgram, parseIf } from './interpreter';
import { FieldResolver } from './resolver';
import { MutationRoot, QueryRoot } from './root';
import { SubscribeMetadata } from './subscription';
import { TypeSpec } from './type-system';
export interface OverrideApiProps extends Omit<appsync.GraphqlApiProps,
| 'name'
| 'schemaDefinition'
| 'schemaDefinitionFile'
> {}
export interface ApiProps<Fragments extends readonly ApiFragment<any, any>[]> {
readonly name: string;
readonly userPool?: UserPool<any, any>;
readonly fragments: Fragments;
readonly caching?: CachingConfiguration;
readonly overrideProps?: Build<OverrideApiProps>;
}
/**
* A finalized AppSync-managed GraphQL API.
*
* APIs are constructed by combining `ApiFragments`.
*
* @typeparam Types - map of names to types in this API
*/
export class Api<
Fragments extends readonly ApiFragment<any, any>[],
> extends Construct implements Resource<appsync.CfnGraphQLApi> {
public readonly resource: Build<appsync.CfnGraphQLApi>;
public readonly fragments: Fragments;
public readonly types: ApiFragments.Reduce<Fragments>;
public readonly query: this['types']['Query'];
public readonly mutation: this['types']['Mutation'];
public readonly subscription: this['types']['Subscription'];
constructor(scope: Scope, id: string, props: ApiProps<Fragments>) {
super(scope, id);
this.fragments = props.fragments;
this.types = ApiFragments.reduce(...props.fragments) as any;
this.query = (this.types as any).Query;
this.mutation = (this.types as any).Mutation;
this.subscription = (this.types as any).Subscription;
const self: {
types: Record<string, TypeSpec>;
query: TypeSpec;
mutation: TypeSpec;
subscription: TypeSpec;
} = this as any;
this.resource = Build.concat(
CDK,
Scope.resolve(scope),
props.userPool?.resource || Build.of(undefined),
props.overrideProps || Build.of({}),
).map(([{appsync, core, iam}, scope, userPool, buildProps]) => {
const blocks: string[] = [];
scope = new core.Construct(scope, id);
const cwRole = new iam.Role(scope, 'CloudWatchRole', {
assumedBy: new iam.ServicePrincipal('appsync')
});
cwRole.addToPolicy(new iam.PolicyStatement({
actions: [
'logs:CreateLogGroup',
'logs:CreateLogStream',
'logs:PutLogEvents',
'logs:DescribeLogStreams'
],
resources: [
'arn:aws:logs:*:*:*'
]
}));
const api = new appsync.CfnGraphQLApi(scope, 'Api', {
name: props.name,
logConfig: {
cloudWatchLogsRoleArn: cwRole.roleArn,
fieldLogLevel: 'ALL',
},
authenticationType: userPool ? 'AMAZON_COGNITO_USER_POOLS' : 'AWS_IAM',
userPoolConfig: userPool ? {
defaultAction: 'ALLOW',
userPoolId: userPool.userPoolId,
awsRegion: userPool.stack.region
} : undefined,
...buildProps,
});
const apiCache: appsync.CfnApiCache | undefined = props.caching ? new appsync.CfnApiCache(scope, 'ApiCache', {
apiId: api.attrApiId,
apiCachingBehavior: props.caching.behavior,
atRestEncryptionEnabled: props.caching.atRestEncryptionEnabled,
transitEncryptionEnabled: props.caching.transitEncryptionEnabled,
ttl: props.caching.ttl,
type: props.caching.instanceType,
}) : undefined;
const schema = new appsync.CfnGraphQLSchema(scope, 'Schema', {
apiId: api.attrApiId,
definition: core.Lazy.stringValue({
produce: () => {
return blocks.concat(generateSchemaHeader(this)).join('\n');
}
}),
});
const dataSources = new core.Construct(api, '_DataSources');
const seenDataTypes = new Set<string>();
if (isUseful(self.query as TypeSpec)) {
parseType(self.query.type);
}
if (isUseful(self.mutation)) {
parseType(self.mutation.type);
}
if (isUseful(self.subscription)) {
parseType(self.subscription.type);
}
return api;
function parseType(shape: Shape): void {
if (ShapeGuards.isArrayShape(shape)) {
// recurse into the Items to discover any custom types
parseType(shape.Items);
} else if (ShapeGuards.isRecordShape(shape)) {
if (shape.FQN === undefined) {
throw new Error(`un-named record types are not supported`);
}
if (!seenDataTypes.has(shape.FQN)) {
seenDataTypes.add(shape.FQN);
const typeSpec = (self.types as Record<string, TypeSpec>)[shape.FQN!];
if (typeSpec === undefined) {
throw new Error(`could not find type ${shape.FQN} in the TypeIndex`);
}
const directives = interpretResolverPipeline(typeSpec);
generateTypeSignature(typeSpec, directives);
Object.values(typeSpec.fields).forEach(parseType);
}
} else if (ShapeGuards.isUnionShape(shape)) {
shape.Items.forEach(parseType);
if(!isOptional(shape)) {
if (shape.FQN === undefined) {
throw new Error(`un-named union types are not supported`);
}
if (!seenDataTypes.has(shape.FQN!)) {
seenDataTypes.add(shape.FQN!);
blocks.push(`union ${shape.FQN} = ${shape.Items.map(i => i.FQN!).filter(i => i !== undefined).join(' | ')};`);
}
}
} else if (ShapeGuards.isFunctionShape(shape)) {
Object.values(shape.args).forEach(parseInputType);
parseType(shape.returns);
} else if (ShapeGuards.isEnumShape(shape)) {
if (shape.FQN === undefined) {
throw new Error(`un-named enum types are not supported`);
}
if (!seenDataTypes.has(shape.FQN)) {
seenDataTypes.add(shape.FQN);
blocks.push(`enum ${shape.FQN} {\n ${Object.values(shape.Values).join('\n ')}\n}`);
}
}
}
function parseInputType(shape: Shape): void {
if (ShapeGuards.isRecordShape(shape)) {
if (shape.FQN === undefined) {
console.error('un-named input type', shape);
throw new Error(`un-named input type`);
}
if (!seenDataTypes.has(shape.FQN!)) {
seenDataTypes.add(shape.FQN!);
Object.values(shape.Members).forEach(parseInputType);
const inputSpec = `input ${shape.FQN} {\n${Object.entries(shape.Members).map(([fieldName, fieldShape]) => {
return ` ${fieldName}: ${getTypeAnnotation(fieldShape)}`;
}).join('\n')}\n}`;
blocks.push(inputSpec);
}
} else if (ShapeGuards.isCollectionShape(shape)) {
parseInputType(shape.Items);
} else if (ShapeGuards.isUnionShape(shape)) {
if (!isOptional(shape)) {
console.error('un-named input type', shape);
throw new Error(`union types not supported as input types`);
}
shape.Items.forEach(parseInputType);
} else if (ShapeGuards.isEnumShape(shape)) {
parseType(shape);
}
}
function generateTypeSignature(typeSpec: TypeSpec, directives: Directives) {
const fieldShapes = Object.entries(typeSpec.fields);
const fields = fieldShapes.map(([fieldName, fieldShape]) => {
const fieldDirectives = (directives[fieldName] || []).join('\n ');
if (ShapeGuards.isFunctionShape(fieldShape)) {
const args = Object.entries(fieldShape.args);
return ` ${fieldName}(${`${args.map(([argName, argShape]) =>
`${argName}: ${getTypeAnnotation(argShape)}`
).join(',')}`}): ${getTypeAnnotation(fieldShape.returns)}${fieldDirectives ? `\n ${fieldDirectives}` : ''}`;
} else {
return ` ${fieldName}: ${getTypeAnnotation(fieldShape)}${fieldDirectives ? `\n ${fieldDirectives}` : ''}`;
}
}).join('\n');
blocks.push(`type ${typeSpec.type.FQN} {\n${fields}\n}`);
}
function interpretResolverPipeline(typeSpec: TypeSpec): Directives {
const directives: Directives = {};
const typeName = typeSpec.type.FQN;
const self = VObject.fromExpr(typeSpec.type, VExpression.text('$context.source'));
for (const [fieldName, resolver] of Object.entries(typeSpec.resolvers) as [string, FieldResolver<any, any, any>][]) {
directives[fieldName] = [];
const {auth, cache, subscribe} = resolver as Partial<AuthMetadata & CacheMetadata<Shape> & SubscribeMetadata<Shape>>;
if (auth !== undefined) {
directives[fieldName]!.push(...toAuthDirectives(auth!));
}
if (subscribe !== undefined) {
directives[fieldName]!.push(`@aws_subscribe(mutations:[${(Array.isArray(subscribe) ? subscribe : [subscribe]).map(s => `"${s.field}"`).join(',')}])`);
}
const fieldShape: Shape = typeSpec.fields[fieldName];
let program: Generator<any, any, any> = undefined as any;
if (ShapeGuards.isFunctionShape(fieldShape)) {
const args = Object.entries(fieldShape.args).map(([argName, argShape]) => ({
[argName]: VObject.fromExpr(argShape, VExpression.text(`$context.arguments.${argName}`))
})).reduce((a, b) => ({...a, ...b}));
if (resolver.resolve) {
program = resolver.resolve.bind(self)(args as any, self);
}
} else if (resolver.resolve) {
program = (resolver as any).resolve.bind(self)(self);
}
if (program === undefined) {
program = (function*() {})();
}
const functions: appsync.CfnFunctionConfigurationProps[] = [];
// let template: string[] = [];
let stageCount = 0;
// create a FQN for the <type>.<field>
const fieldFQN = `${typeName}_${fieldName}`.replace(/[^_0-9A-Za-z]/g, '_');
const initState = new InterpreterState();
const result = interpretProgram(program, initState, interpret);
function interpret(stmt: any, state: InterpreterState): any {
if(StatementGuards.isGetState(stmt)) {
return state;
} else if (StatementGuards.isStash(stmt)) {
const stashId = state.stash(stmt.value, stmt);
return VObject.fromExpr(VObject.getType(stmt.value), VExpression.text(stashId));
} else if (StatementGuards.isWrite(stmt)) {
state.write(...stmt.expressions);
return undefined;
} else if (StatementGuards.isForLoop(stmt)) {
const itemId = `$${state.newId('item')}`;
state.write(VExpression.concat(
'#foreach( ', itemId, ' in ', stmt.list, ')'
)).indent().writeLine();
const item = VObject.fromExpr(VObject.getType(stmt.list).Items, VExpression.text(itemId));
const index = new VInteger(VExpression.text('$foreach.index'));
const hasNext = new VBool(VExpression.text('$foreach.hasNext'));
interpretProgram(
stmt.then(item, index, hasNext),
state,
interpret
);
state.unindent().writeLine().write('#end').writeLine();
return undefined;
} else if (StatementGuards.isIf(stmt)) {
const [returnId, branchYieldValues] = parseIf(stmt, state, interpret);
const allUndefined = branchYieldValues.filter(v => v !== undefined).length === 0;
const returnedValues = branchYieldValues
// map undefined to VNothing
.map(r => r === undefined ? new VNothing(VExpression.text('null')) : r as VObject)
// filter duplicates
.filter((r, index, self) => self.findIndex(v => VObject.getType(r).equals(VObject.getType(v))) === index)
;
// derive a VObject to represent the returned value of the if-else-then branches
const returnValue = returnedValues.length === 1 ? returnedValues[0] : new VUnion(
new UnionShape(returnedValues.map(v => VObject.getType(v)), undefined),
VExpression.text(returnId)
);
if (!allUndefined) {
return VObject.fromExpr(VObject.getType(returnValue), VExpression.text(state.stash(returnValue)));
} else {
return new VNothing(VExpression.text('null'));
}
} else if (StatementGuards.isCall(stmt)) {
const name = state.newId();
state.write(VObject.getExpr(stmt.request));
const requestMappingTemplate = state.renderTemplate();
// return a reference to the previou s result
const responseMappingTemplate = `#set($context.stash.${name} = $context.result)\n`;
// clear template state
const stageName = `${fieldFQN}${stageCount += 1}`;
const dataSourceProps = Build.resolve(stmt.dataSourceProps)(dataSources, stageName);
// TODO: de-duplicate data sources
const dataSource = new appsync.CfnDataSource(scope, `DataSource(${stageName})`, {
...dataSourceProps,
apiId: api.attrApiId,
name: stageName,
});
functions.push({
apiId: api.attrApiId,
name: stageName,
requestMappingTemplate,
responseMappingTemplate,
dataSourceName: dataSource.attrName,
functionVersion: '2018-05-29',
});
return VObject.fromExpr(stmt.responseType, VExpression.text(`$context.stash.${name}`));
}
console.error('unsupported statement type', stmt);
throw new Error(`unsupported statement type: ${state}`);
}
let _noneDataSource: appsync.CfnDataSource | undefined;
const noneDataSource = () => {
if (!_noneDataSource) {
_noneDataSource = new appsync.CfnDataSource(scope, 'None', {
apiId: api.attrApiId,
name: 'NONE',
type: 'NONE',
description: 'Empty Data Source'
});
}
return _noneDataSource;
};
const config: {
kind: 'PIPELINE' | 'UNIT';
requestMappingTemplate?: string;
responseMappingTemplate?: string;
dataSourceName?: string;
pipelineConfig?: appsync.CfnResolver.PipelineConfigProperty;
} = {
kind: 'UNIT'
};
if (result !== undefined && !VObject.isObject(result)) {
const err = new Error('result must be undefined or a VObject');
console.error('result is not a VObject', result, err);
throw err;
}
if (functions.length === 0 && result === undefined && initState.template.length === 0) {
// we don't need a resolver pipeline
console.warn(`no Resolver required for field ${fieldFQN}`);
} else {
if (functions.length === 0) {
config.dataSourceName = noneDataSource().attrName;
config.requestMappingTemplate = initState.write(VExpression.json({
version: '2017-02-28',
payload: result === undefined ? {} : VExpression.concat('$util.toJson(', result, ')')
})).renderTemplate();
config.responseMappingTemplate = result === undefined ? 'null' : initState.write('$util.toJson(', result, ')').renderTemplate();
} else {
if (result !== undefined) {
initState.write('$util.toJson(', result, ')');
} else {
initState.write('null');
}
if (functions.length === 1) {
config.dataSourceName = functions[0].dataSourceName;
config.requestMappingTemplate = functions[0].requestMappingTemplate;
config.responseMappingTemplate = functions[0].responseMappingTemplate + '\n' + initState.renderTemplate();
} else {
config.kind = 'PIPELINE';
config.requestMappingTemplate = 'null';
config.pipelineConfig = {
functions: functions.map((f, i) =>
new appsync.CfnFunctionConfiguration(scope, `Function(${fieldFQN}, ${i})`, {
...f,
// intermediate pipelines should emit null to the next function or final response mapping template
responseMappingTemplate: f.responseMappingTemplate + '\nnull'
}).attrFunctionId)
};
config.responseMappingTemplate = initState.renderTemplate();
}
}
const cfnResolver = new appsync.CfnResolver(scope, `Resolve(${fieldFQN})`, {
...config,
apiId: api.attrApiId,
typeName,
fieldName,
cachingConfig: (() => {
let cachingConfig: appsync.CfnResolver.CachingConfigProperty | undefined;
if (apiCache) {
if (cache !== undefined) {
cachingConfig = {
cachingKeys: cache.keys,
ttl: cache.ttl
};
}
}
if (cachingConfig !== undefined) {
return {
...cachingConfig,
cachingKeys: cachingConfig.cachingKeys?.map((k: string) =>
k.startsWith('$context.identity') ? k : `$context.arguments.${k}`
)
};
}
return undefined;
})()
});
cfnResolver.addDependsOn(schema);
}
}
return directives;
}
});
}
public Query<T extends Record<string, GqlResult>>(f: (client: GqlApiClient<this, typeof QueryRoot>) => T): Promise<{
[i in keyof T]: T[i][GqlApiClient.result]
}> {
return null as any;
}
public Mutate<T extends Record<string, GqlResult>>(f: (client: GqlApiClient<this, typeof MutationRoot>) => T): Promise<{
[i in keyof T]: T[i][GqlApiClient.result]
}> {
return null as any;
}
}
type Directives = {
[field in string]?: string[]; // directives
};
const generateSchemaHeader = (api: Api<any>) => `schema {
${[
isUseful(api.query) ? `query: ${api.query.type.FQN}` : undefined,
isUseful(api.mutation) ? `mutation: ${api.mutation.type.FQN}` : undefined,
isUseful(api.subscription) ? `subscription: ${api.subscription.type.FQN}` : undefined,
].filter(_ => _ !== undefined).join(',\n ')}
}`;
const isUseful = (spec?: TypeSpec): spec is TypeSpec => {
return spec !== undefined && Object.keys(spec.fields).length > 0;
};
// gets the GraphQL type annotaiton syntax for a Shape
function getTypeAnnotation(shape: Shape): string {
const {graphqlType} = Meta.get(shape, ['graphqlType']);
const isNullable = isOptional(shape);
if (isNullable && ShapeGuards.isUnionShape(shape)) {
shape = (shape as UnionShape<Shape[]>).Items.find(i => !ShapeGuards.isNothingShape(i))!;
}
return `${getTypeName()}${isNullable === true ? '' : '!'}`;
function getTypeName(): string {
if (typeof graphqlType === 'string') {
return graphqlType;
} else if (ShapeGuards.isArrayShape(shape) || ShapeGuards.isSetShape(shape)) {
return `[${getTypeAnnotation(shape.Items)}]`;
} else if (ShapeGuards.isMapShape(shape)) {
throw new Error(`maps are not supported in GraphQL - use a RecordType instead`);
} else if (ShapeGuards.isStringShape(shape)) {
return 'String';
} else if (ShapeGuards.isTimestampShape(shape)) {
return 'AWSDateTime';
} else if (ShapeGuards.isAnyShape(shape)) {
return 'AWSJSON';
} else if (ShapeGuards.isBoolShape(shape)) {
return 'Boolean';
} else if (ShapeGuards.isNumberShape(shape)) {
return ShapeGuards.isIntegerShape(shape) ? 'Int' : 'Float';
} else if (ShapeGuards.isRecordShape(shape)) {
if (shape.FQN === undefined) {
throw new Error(`Only records with a FQN are supported as types in Graphql. class A extends Record('FQN', { .. }) {}`);
}
return shape.FQN!;
} else if (ShapeGuards.isUnionShape(shape) && shape.FQN !== undefined) {
return shape.FQN!;
} else if (ShapeGuards.isEnumShape(shape) && shape.FQN !== undefined) {
return shape.FQN!;
} else {
throw new Error(`shape type ${shape.Kind} is not supported by GraphQL`);
}
}
} | the_stack |
import test from 'ava';
import {JsonView} from '../src/decorators/JsonView';
import {ObjectMapper} from '../src/databind/ObjectMapper';
import {JsonProperty} from '../src/decorators/JsonProperty';
import {JsonGetter} from '../src/decorators/JsonGetter';
import {JsonSetter} from '../src/decorators/JsonSetter';
import {JsonClassType} from '../src/decorators/JsonClassType';
class Views {
static public = class Public {};
static internal = class Internal {};
}
test('@JsonView at class level', t => {
@JsonView({value: () => [Views.internal]})
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
@JsonView({value: () => [Views.public]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
password: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.public]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
activationCode: string;
// eslint-disable-next-line no-shadow
constructor(id: number, email: string, password: string, firstname: string, lastname: string, activationCode: string) {
this.id = id;
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.activationCode = activationCode;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'rtJ9FrqP!rCE', 'John', 'Alfa', '75afe654-695e-11ea-bc55-0242ac130003');
const objectMapper = new ObjectMapper();
const jsonDataWithoutView = objectMapper.stringify<User>(user);
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithoutView), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithoutView = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User]
});
t.assert(userParsedWithoutView instanceof User);
t.is(userParsedWithoutView.id, 1);
t.is(userParsedWithoutView.email, 'john.alfa@gmail.com');
t.is(userParsedWithoutView.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithoutView.firstname, 'John');
t.is(userParsedWithoutView.lastname, 'Alfa');
t.is(userParsedWithoutView.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
const jsonDataWithViewPublic = objectMapper.stringify<User>(user, {withViews: () => [Views.public]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewPublic), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}'));
// eslint-disable-next-line max-len
const userParsedWithViewPublic = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.public]
});
t.assert(userParsedWithViewPublic instanceof User);
t.is(userParsedWithViewPublic.id, 1);
t.is(userParsedWithViewPublic.email, 'john.alfa@gmail.com');
t.is(userParsedWithViewPublic.password, null);
t.is(userParsedWithViewPublic.firstname, 'John');
t.is(userParsedWithViewPublic.lastname, 'Alfa');
t.is(userParsedWithViewPublic.activationCode, null);
const jsonDataWithViewInternal = objectMapper.stringify<User>(user, {withViews: () => [Views.internal]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewInternal), JSON.parse('{"password":"rtJ9FrqP!rCE","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithViewInternal = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.internal]
});
t.assert(userParsedWithViewInternal instanceof User);
t.is(userParsedWithViewInternal.id, null);
t.is(userParsedWithViewInternal.email, null);
t.is(userParsedWithViewInternal.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithViewInternal.firstname, null);
t.is(userParsedWithViewInternal.lastname, null);
t.is(userParsedWithViewInternal.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
});
test('@JsonView at property level', t => {
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.internal]})
password: string;
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.internal]})
activationCode: string;
// eslint-disable-next-line no-shadow
constructor(id: number, email: string, password: string, firstname: string, lastname: string, activationCode: string) {
this.id = id;
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.activationCode = activationCode;
}
}
const user = new User(1, 'john.alfa@gmail.com', 'rtJ9FrqP!rCE', 'John', 'Alfa', '75afe654-695e-11ea-bc55-0242ac130003');
const objectMapper = new ObjectMapper();
const jsonDataWithoutView = objectMapper.stringify<User>(user);
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithoutView), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithoutView = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User]
});
t.assert(userParsedWithoutView instanceof User);
t.is(userParsedWithoutView.id, 1);
t.is(userParsedWithoutView.email, 'john.alfa@gmail.com');
t.is(userParsedWithoutView.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithoutView.firstname, 'John');
t.is(userParsedWithoutView.lastname, 'Alfa');
t.is(userParsedWithoutView.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
const jsonDataWithViewPublic = objectMapper.stringify<User>(user, {withViews: () => [Views.public]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewPublic), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}'));
// eslint-disable-next-line max-len
const userParsedWithViewPublic = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.public]
});
t.assert(userParsedWithViewPublic instanceof User);
t.is(userParsedWithViewPublic.id, 1);
t.is(userParsedWithViewPublic.email, 'john.alfa@gmail.com');
t.is(userParsedWithViewPublic.password, null);
t.is(userParsedWithViewPublic.firstname, 'John');
t.is(userParsedWithViewPublic.lastname, 'Alfa');
t.is(userParsedWithViewPublic.activationCode, null);
const jsonDataWithViewInternal = objectMapper.stringify<User>(user, {withViews: () => [Views.internal]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewInternal), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithViewInternal = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.internal]
});
t.assert(userParsedWithViewInternal instanceof User);
t.is(userParsedWithViewInternal.id, 1);
t.is(userParsedWithViewInternal.email, 'john.alfa@gmail.com');
t.is(userParsedWithViewInternal.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithViewInternal.firstname, 'John');
t.is(userParsedWithViewInternal.lastname, 'Alfa');
t.is(userParsedWithViewInternal.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
});
test('@JsonView at method level', t => {
class User {
@JsonProperty() @JsonClassType({type: () => [Number]})
id: number;
@JsonProperty() @JsonClassType({type: () => [String]})
email: string;
@JsonProperty() @JsonClassType({type: () => [String]})
password: string;
@JsonProperty() @JsonClassType({type: () => [String]})
firstname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
lastname: string;
@JsonProperty() @JsonClassType({type: () => [String]})
activationCode: string;
// eslint-disable-next-line no-shadow
constructor(id: number, email: string, password: string, firstname: string, lastname: string, activationCode: string) {
this.id = id;
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.activationCode = activationCode;
}
@JsonGetter() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.internal]})
getPassword(): string {
return this.password;
}
@JsonSetter()
@JsonView({value: () => [Views.internal]})
// eslint-disable-next-line no-shadow
setPassword(password: string) {
this.password = password;
}
@JsonGetter() @JsonClassType({type: () => [String]})
@JsonView({value: () => [Views.internal]})
getActivationCode(): string {
return this.activationCode;
}
@JsonSetter()
@JsonView({value: () => [Views.internal]})
// eslint-disable-next-line no-shadow
setActivationCode(activationCode: string) {
this.activationCode = activationCode;
}
}
const password = 'rtJ9FrqP!rCE';
const activationCode = '75afe654-695e-11ea-bc55-0242ac130003';
const user = new User(1, 'john.alfa@gmail.com', password, 'John', 'Alfa', activationCode);
const objectMapper = new ObjectMapper();
const jsonDataWithoutView = objectMapper.stringify<User>(user);
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithoutView), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithoutView = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User]
});
t.assert(userParsedWithoutView instanceof User);
t.is(userParsedWithoutView.id, 1);
t.is(userParsedWithoutView.email, 'john.alfa@gmail.com');
t.is(userParsedWithoutView.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithoutView.firstname, 'John');
t.is(userParsedWithoutView.lastname, 'Alfa');
t.is(userParsedWithoutView.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
const jsonDataWithViewPublic = objectMapper.stringify<User>(user, {withViews: () => [Views.public]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewPublic), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}'));
// eslint-disable-next-line max-len
const userParsedWithViewPublic = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.public]
});
t.assert(userParsedWithViewPublic instanceof User);
t.is(userParsedWithViewPublic.id, 1);
t.is(userParsedWithViewPublic.email, 'john.alfa@gmail.com');
t.is(userParsedWithViewPublic.password, null);
t.is(userParsedWithViewPublic.firstname, 'John');
t.is(userParsedWithViewPublic.lastname, 'Alfa');
t.is(userParsedWithViewPublic.activationCode, null);
const jsonDataWithViewInternal = objectMapper.stringify<User>(user, {withViews: () => [Views.internal]});
// eslint-disable-next-line max-len
t.deepEqual(JSON.parse(jsonDataWithViewInternal), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}'));
// eslint-disable-next-line max-len
const userParsedWithViewInternal = objectMapper.parse<User>('{"id":1,"email":"john.alfa@gmail.com","password":"rtJ9FrqP!rCE","firstname":"John","lastname":"Alfa","activationCode":"75afe654-695e-11ea-bc55-0242ac130003"}', {
mainCreator: () => [User],
withViews: () => [Views.internal]
});
t.assert(userParsedWithViewInternal instanceof User);
t.is(userParsedWithViewInternal.id, 1);
t.is(userParsedWithViewInternal.email, 'john.alfa@gmail.com');
t.is(userParsedWithViewInternal.password, 'rtJ9FrqP!rCE');
t.is(userParsedWithViewInternal.firstname, 'John');
t.is(userParsedWithViewInternal.lastname, 'Alfa');
t.is(userParsedWithViewInternal.activationCode, '75afe654-695e-11ea-bc55-0242ac130003');
});
test('@JsonView at parameter level', t => {
class Company {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty()
@JsonClassType({type: () => [Array, [Employee]]})
employees: Employee[] = [];
constructor(name: string,
@JsonView({value: () => [Views.internal]})
@JsonClassType({type: () => [Array, [Employee]]}) employees: Employee[] ) {
this.name = name;
this.employees = employees;
}
}
class Employee {
@JsonProperty() @JsonClassType({type: () => [String]})
name: string;
@JsonProperty() @JsonClassType({type: () => [Number]})
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const employee = new Employee('John Alfa', 25);
const company = new Company('Google', [employee]);
const objectMapper = new ObjectMapper();
const jsonData = objectMapper.stringify<Company>(company);
t.deepEqual(JSON.parse(jsonData), JSON.parse('{"employees":[{"name":"John Alfa","age":25}],"name":"Google"}'));
const companyParsed = objectMapper.parse<Company>(jsonData, {
mainCreator: () => [Company],
withViews: () => [Views.public]
});
t.assert(companyParsed instanceof Company);
t.is(companyParsed.name, 'Google');
t.is(companyParsed.employees, null);
}); | the_stack |
import { ChildProcess, exec } from 'child_process';
import * as FS from 'fs';
import getPort from 'get-port';
import * as Path from 'path';
import vscode from 'vscode';
import { getWebviewContent } from './getWebviewContent';
interface ViteProcess {
port: number;
output: vscode.OutputChannel;
instance: ChildProcess;
serverBaseURI: string;
onReady: Promise<any>;
}
const processes = new Map<string, ViteProcess>();
function findProjectDir(fileName: string): string {
let dir = Path.dirname(fileName);
while (dir !== Path.dirname(dir)) {
if (FS.existsSync(Path.join(dir, 'package.json'))) {
return dir;
}
dir = Path.dirname(dir);
}
return Path.dirname(fileName);
}
export async function activate(context: vscode.ExtensionContext): Promise<void> {
const bin = Path.resolve(context.extensionPath, 'node_modules/@vuedx/preview/bin/preview.js');
// TODO: Use global installation in .vuedx/preview directory to avoid extension source changed warning.
await vscode.commands.executeCommand('setContext', 'preview:isViteStarted', true);
let activeWebviewPanel: vscode.WebviewPanel | undefined;
const previewSources = new Map<vscode.WebviewPanel, { fileName: string; uri: string }>();
function getActiveVueFile(): string | undefined {
const fileName =
activeWebviewPanel != null ? previewSources.get(activeWebviewPanel)?.fileName : undefined;
return fileName ?? vscode.window.activeTextEditor?.document?.fileName;
}
async function getVitePort(rootDir: string): Promise<number> {
const p = processes.get(rootDir);
if (p != null) {
return p.port;
}
return await getPort({ port: 65000 });
}
async function getViteInstance(bin: string, rootDir: string, port: number): Promise<ViteProcess> {
await installPreview(bin, context);
if (processes.has(rootDir)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = processes.get(rootDir)!;
await result.onReady;
return result;
}
const output = vscode.window.createOutputChannel(`Preview (${processes.size})`);
const instance = exec(`${bin} --force --port ${port}`, {
cwd: rootDir,
env: { ...process.env, CI: 'true' },
});
const onReady = new Promise<string>((resolve, reject) => {
let isResolved = false;
output.appendLine(`> Launching preview in ${rootDir}`);
instance.stderr?.on('data', (message) => {
output.append(message.toString());
});
const re = /> Local:\s+([^ \s\n]+)/;
instance.stdout?.on('data', (message: string | Buffer) => {
const line = message.toString();
output.append(line);
const match = re.exec(line);
if (!isResolved && match?.[1] != null) {
isResolved = true;
const url = match[1].trim().replace(/\/+$/, '');
setTimeout(() => {
output.appendLine(`Preview is ready, running on ${url}`);
resolve(url);
}, 1000);
}
});
instance.on('exit', (code) => {
output.dispose();
if (!isResolved) {
reject(new Error(`Preview exited with code: ${code ?? 'null'}`));
}
});
});
const result = { port, output, instance, serverBaseURI: '', onReady: onReady };
processes.set(rootDir, result);
result.serverBaseURI = await onReady;
return result;
}
context.subscriptions.push(
vscode.commands.registerCommand('preview.show', async () => {
try {
const editor = vscode.window.activeTextEditor;
if (editor == null) {
await vscode.window.showErrorMessage('No active editor');
return;
}
const fileName = editor.document.fileName;
if (!fileName.endsWith('.vue')) {
await vscode.window.showErrorMessage('Only .vue files are supported');
return;
}
const existing = Array.from(previewSources.keys()).find((panel) => {
const info = previewSources.get(panel);
return info?.fileName === fileName;
});
if (existing != null) {
existing.reveal(vscode.ViewColumn.Beside);
return;
}
const rootDir = findProjectDir(fileName);
const port = await getVitePort(rootDir);
const panel = vscode.window.createWebviewPanel(
'preview',
`Preview ${Path.basename(fileName)}`,
{
viewColumn: vscode.ViewColumn.Beside,
preserveFocus: true,
},
{
enableFindWidget: true,
retainContextWhenHidden: true,
enableScripts: true,
portMapping: [{ webviewPort: port, extensionHostPort: port }],
}
);
panel.iconPath = vscode.Uri.file(Path.resolve(context.extensionPath, 'logo.png'));
panel.onDidDispose(() => {
previewSources.delete(panel);
});
panel.onDidChangeViewState(async (event) => {
if (event.webviewPanel.active) {
activeWebviewPanel = event.webviewPanel;
} else if (activeWebviewPanel === event.webviewPanel) {
activeWebviewPanel = undefined;
}
await vscode.commands.executeCommand(
'setContext',
'preview:isFocused',
event.webviewPanel.active
);
});
panel.webview.onDidReceiveMessage(async (event: { command: string; payload: any }) => {
switch (event.command) {
case 'alert': {
await vscode.window.showInformationMessage(event.payload.message);
break;
}
}
});
panel.webview.html = getWebviewContent(
'<div style="display: flex; height: 100%; align-items: center; justify-content: center;">Starting preview...</div>'
);
const vite = await getViteInstance(bin, rootDir, port);
vite.instance.stdin?.write(
JSON.stringify({ command: 'open', arguments: { fileName } }) + '\n'
);
const id = Path.relative(rootDir, fileName);
const uri = `${vite.serverBaseURI}/sandbox?fileName=${encodeURIComponent(id)}`;
previewSources.set(panel, { fileName, uri });
vite.output.appendLine(`Preview File: "${fileName}"`);
vite.output.appendLine(`URL: "${uri}"`);
panel.webview.html = getWebviewContent(getPreviewIFrame(uri));
} catch (error) {
console.error(error);
await vscode.window.showErrorMessage(error.message);
}
}),
vscode.commands.registerCommand('preview.open', async () => {
const fileName = getActiveVueFile();
if (fileName?.endsWith('.vue') !== true) {
await vscode.window.showErrorMessage('Only .vue files are supported');
return;
}
const rootDir = findProjectDir(fileName);
const port = await getVitePort(rootDir);
const vite = await getViteInstance(bin, rootDir, port);
vite.instance.stdin?.write(
JSON.stringify({ command: 'open', arguments: { fileName } }) + '\n'
);
const id = Path.relative(rootDir, fileName);
const uri = `${vite.serverBaseURI}/sandbox?fileName=${encodeURIComponent(id)}`;
vite.output.appendLine(`Preview File: "${fileName}"`);
vite.output.appendLine(`URL: "${uri}"`);
await vscode.env.openExternal(vscode.Uri.parse(uri));
}),
vscode.commands.registerCommand('preview.refresh', async () => {
if (activeWebviewPanel != null) {
const info = previewSources.get(activeWebviewPanel);
if (info != null) {
activeWebviewPanel.webview.html = getWebviewContent(getPreviewIFrame(info.uri));
}
}
}),
vscode.commands.registerCommand('preview.update', async () => {
await installPreview(bin, context, true);
}),
vscode.commands.registerCommand('preview.showSource', async () => {
const fileName = getActiveVueFile();
if (fileName != null) {
const editor = vscode.window.visibleTextEditors.find(
(editor) => editor.document.fileName === fileName
);
const options: vscode.TextDocumentShowOptions = {
viewColumn: vscode.ViewColumn.One,
};
if (editor != null) {
await vscode.window.showTextDocument(editor.document, options);
} else {
await vscode.commands.executeCommand('vscode.open', vscode.Uri.file(fileName), options);
}
}
}),
vscode.commands.registerCommand('preview.stop', async () => {
await vscode.window.withProgress(
{
title: 'Shutting down preview',
location: vscode.ProgressLocation.Notification,
cancellable: false,
},
async () => {
await stopVite();
}
);
}),
vscode.Disposable.from({
dispose: async () => {
await stopVite();
},
})
);
async function stopVite(): Promise<void> {
const instances = Array.from(processes.values());
instances.forEach((item) => {
if (!item.instance.killed) {
item.output.appendLine('Exiting preview.');
item.instance.kill('SIGABRT');
}
});
processes.clear();
await vscode.commands.executeCommand('setContext', 'preview:isViteStarted', false); // TODO: This needs to be set per file basis.
}
}
function getPreviewIFrame(uri: string): string {
return `
<iframe style="border: none;" width="100%" height="100%" src="${uri}&t=${Date.now()}&vscode"></iframe>
`;
}
async function installPreview(
bin: string,
context: vscode.ExtensionContext,
force = false
): Promise<void> {
if (context.extensionMode === vscode.ExtensionMode.Development) return;
if (!FS.existsSync(bin) || force) {
await vscode.window.withProgress(
{
cancellable: true,
location: vscode.ProgressLocation.Notification,
title: 'Installing @vuedx/preview',
},
async (progress, token): Promise<void> => {
return await new Promise<void>((resolve, reject) => {
const output = vscode.window.createOutputChannel('Preview (installation)');
const version = getExtensionName(context).includes('insiders') ? 'insiders' : 'latest';
const command = __DEV__
? `pnpm add ${__PREVIEW_INSTALLATION_SOURCE__}`
: `npm add @vuedx/preview@${version} --loglevel info`;
if (__DEV__) output.show();
output.appendLine(command);
const installation = exec(command, {
cwd: context.extensionPath,
env: { ...process.env, CI: 'true' },
});
token.onCancellationRequested(() => {
if (!installation.killed) installation.kill('SIGABRT');
});
installation.on('message', (chunk) => {
output.append(typeof chunk === 'string' ? chunk : JSON.stringify(chunk));
});
installation.on('error', (error) => {
output.appendLine(`Error: ${error.message}`);
output.appendLine(error.stack ?? '');
});
installation.stdout?.on('data', (chunk: Buffer) => {
output.append(chunk.toString());
progress.report({ message: chunk.toString() });
});
let error: string = '';
installation.stderr?.on('data', (chunk: Buffer) => {
output.append(chunk.toString());
error += chunk.toString();
});
installation.on('exit', (code) => {
if (code !== 0) {
reject(
new Error(
`Error: npm exited with non-zero status code: ${code ?? 'null'}.\n\n${error}`
)
);
} else {
resolve();
}
if (__PROD__) output.dispose();
});
});
}
);
}
}
function getExtensionName(context: vscode.ExtensionContext): string {
try {
const pkgFile = context.asAbsolutePath('package.json');
console.log('PackageFile: ' + pkgFile);
return JSON.parse(FS.readFileSync(pkgFile, 'utf-8')).name;
} catch {
return 'znck.preview';
}
} | the_stack |
import * as lodash from 'lodash';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { ICRManagementDataProvider } from './ICRManagementDataProvider';
import { IMyChangeRequestItem, IChangeDiscussionItem, Constants, IPerson } from '../../../libraries/index';
import { IChangeRequestManagementItem, CRMTab } from '../models/CRManagementModel';
import { sp } from '../../../pnp-preset';
import { ISiteUserInfo } from '@pnp/sp/site-users/types';
export class CRManagementDataProvider implements ICRManagementDataProvider {
private _currentUser: IPerson;
public constructor(context: IWebPartContext) {
sp.setup(context);
this._currentUser = null;
}
public getChangeRequestStatusField(): Promise<Array<string>> {
return sp.web
.lists.getByTitle(`${Constants.ChangeRequestListTitle}`)
.fields.getByInternalNameOrTitle('Status')()
.then(
(field: any) => Promise.resolve(field.Choices),
err => Promise.reject(err)
);
}
public getChangeDiscussionStatusField(): Promise<Array<string>> {
return sp.web
.lists.getByTitle(`${Constants.ChangeDiscussionListTitle}`)
.fields.getByInternalNameOrTitle('Sub_x0020_Status')()
.then(
(field: any) => Promise.resolve(field.Choices),
err => Promise.reject(err)
);
}
public getCRMItems(tab: CRMTab): Promise<IChangeRequestManagementItem[]> {
return this
._getCurrentUser()
.then((person: IPerson) => {
if (tab == CRMTab.ActiveIssues) {
return this._getCRMItems(person, `Status ne 'Closed'`);
}
else if (tab == CRMTab.MyIssues) {
if (person.isInTriage) {
return this._getMyCRMItems(person);
}
else {
return Promise.resolve([]);
}
}
else {
return this._getCRMItems(person, `Status eq 'Closed'`);
}
});
}
public getUserById(uid: number): Promise<IPerson> {
return sp.web
.getUserById(uid)()
.then(
user => this._analyseAndGetPersonGroup(user),
err => Promise.reject(err)
);
}
public isTriageTeamUser(): Promise<Boolean> {
return this._getCurrentUser().then((person: IPerson) => {
return person.isInTriage;
});
}
public saveCRMItem(item: IChangeRequestManagementItem): Promise<boolean> {
return this._updateCRItem(item.critem)
.then((success) => {
if (success) {
return item.cditem.id > 0 ? this._updateCDItem(item.cditem) : this._createCDItem(item.cditem);
}
else {
return false;
}
});
}
private _getCurrentUser(): Promise<IPerson> {
if (this._currentUser != null) {
return Promise.resolve(this._currentUser);
}
else {
return sp.web
.currentUser()
.then(
user => this._analyseAndGetPersonGroup(user),
err => Promise.reject(err)
);
}
}
//get site users
public getTriageSiteUsers(): Promise<IPerson[]> {
return sp.web
.siteUsers()
.then((siteUsers: ISiteUserInfo[]) => {
if (siteUsers && siteUsers.length > 0) {
const peoplePromiseArray: Promise<IPerson>[] = siteUsers.map(user => this._analyseAndGetPersonGroup(user));
return Promise
.all(peoplePromiseArray)
.then((users: IPerson[]) => {
return lodash.filter(users, (user: IPerson) => {
return user.isInTriage;
});
});
}
else {
return [];
}
});
}
//Active Issues will display only active issues.
//Closed issues will display only closed issues.
private _getCRMItems(person: IPerson, filter: string): Promise<IChangeRequestManagementItem[]> {
return this._getCRItems(filter)
.then((critems: IMyChangeRequestItem[]) => {
if (critems != null && critems.length > 0) {
if (person.isInTriage) {
let cdPromiseArray: Array<Promise<IChangeDiscussionItem>> = [];
critems.forEach((item: IMyChangeRequestItem) => {
let filterString: string = `ChangeId eq ${item.id}`;
cdPromiseArray.push(this._getCDItem(filterString));
});
return Promise.all(cdPromiseArray)
.then((cditems: IChangeDiscussionItem[]) => {
return critems.map((critem: IMyChangeRequestItem, index: number) => {
let cditem: IChangeDiscussionItem;
let cdindex = lodash.findIndex(cditems, (filtercditem: IChangeDiscussionItem) => filtercditem != null && filtercditem.changeid === critem.id);
if (cdindex != -1) {
cditem = cditems[cdindex];
}
return { critem: critem, cditem: cditem } as IChangeRequestManagementItem;
});
});
}
else {
return critems.map((critem: IMyChangeRequestItem, index: number) => {
return { critem: critem, cditem: null } as IChangeRequestManagementItem;
});
}
}
else {
return [];
}
});
}
//My Issues will display all issues that are assigned to the current user viewing the issues
private _getMyCRMItems(person: IPerson): Promise<IChangeRequestManagementItem[]> {
return this._getCDItems(`Assigned_x0020_ToId eq ${person.id}`)
.then((cditems: IChangeDiscussionItem[]) => {
if (cditems != null && cditems.length > 0) {
const crPromiseArray: Array<Promise<IMyChangeRequestItem>> = [];
cditems.forEach((item: IChangeDiscussionItem) => {
const filterString: string = `Id eq ${item.changeid}`;
crPromiseArray.push(this._getCRItem(filterString));
});
return Promise.all(crPromiseArray)
.then((critems: IMyChangeRequestItem[]) => {
return critems.map((critem: IMyChangeRequestItem) => {
if (critem != null) {
let cditem: IChangeDiscussionItem;
let cdindex = lodash.findIndex(cditems, (filtercditem: IChangeDiscussionItem) => filtercditem != null && filtercditem.changeid === critem.id);
if (cdindex != -1) {
cditem = cditems[cdindex];
}
return { critem: critem, cditem: cditem } as IChangeRequestManagementItem;
}
});
});
}
else {
return [];
}
});
}
private _getCRItems(crfilter: string): Promise<IMyChangeRequestItem[]> {
return sp.web
.lists.getByTitle(Constants.ChangeRequestListTitle)
.items
.filter(crfilter)
.select('ID', 'Title', 'Description', 'Status', 'Status_x0020_Updates', 'Created', 'AuthorId')
.orderBy('ID', false)()
.then(
crItems => crItems.map(item => {
return {
id: item.ID,
title: item.Title,
description: item.Description,
status: item.Status,
statusupdates: item.Status_x0020_Updates,
createdby: item.AuthorId,
createddate: item.Created
};
}),
err => Promise.reject(err)
);
}
private _getCRItem(crfilter: string): Promise<IMyChangeRequestItem> {
return this._getCRItems(crfilter)
.then((critems: IMyChangeRequestItem[]) => {
if (critems.length > 0) {
return critems[0];
}
else {
return null;
}
});
}
private _updateCRItem(item: IMyChangeRequestItem): Promise<boolean> {
return sp.web
.lists.getByTitle(Constants.ChangeRequestListTitle)
.items.getById(item.id)
.update({
'Title': item.title,
'Status': item.status,
'Description': item.description,
'Status_x0020_Updates': item.statusupdates
})
.then(_ => Promise.resolve(true), _ => Promise.resolve(false));
}
private _getCDItems(cdfilter: string): Promise<IChangeDiscussionItem[]> {
return sp.web
.lists.getByTitle(Constants.ChangeDiscussionListTitle)
.items
.filter(cdfilter)
.select('ID', 'ChangeId', 'Triage_x0020_Comments', 'Sub_x0020_Status', 'Priority', 'Assigned_x0020_ToId')()
.then(
crItems => crItems.map(item => {
return {
id: item.ID,
changeid: item.ChangeId,
triagecomments: item.Triage_x0020_Comments,
substatus: item.Sub_x0020_Status,
priority: item.Priority,
assignedto: item.Assigned_x0020_ToId
};
}),
err => Promise.reject(err)
);
}
private _getCDItem(cdfilter: string): Promise<IChangeDiscussionItem> {
return this._getCDItems(cdfilter)
.then((cditems: IChangeDiscussionItem[]) => {
if (cditems.length > 0) {
return cditems[0];
}
else {
return null;
}
});
}
private _updateCDItem(item: IChangeDiscussionItem): Promise<boolean> {
return sp.web
.lists.getByTitle(Constants.ChangeDiscussionListTitle)
.items.getById(item.id)
.update({
'Assigned_x0020_ToId': item.assignedto,
'Priority': item.priority,
'Sub_x0020_Status': item.substatus,
'Triage_x0020_Comments': item.triagecomments
})
.then(_ => Promise.resolve(true), _ => Promise.resolve(false));
}
private _createCDItem(item: IChangeDiscussionItem): Promise<boolean> {
return sp.web
.lists.getByTitle(Constants.ChangeDiscussionListTitle)
.items.add({
'ChangeId': item.changeid,
'Triage_x0020_Comments': item.triagecomments,
'Sub_x0020_Status': item.substatus,
'Priority': item.priority,
'Assigned_x0020_ToId': item.assignedto
})
.then(_ => Promise.resolve(true), _ => Promise.resolve(false));
}
private _analyseAndGetPersonGroup(item: ISiteUserInfo): Promise<IPerson> {
const userId: number = item.Id, userTitle: string = item.Title, isSiteAdmin: boolean = item.IsSiteAdmin;
let firstName: string = '', lastName: string = '';
let person: IPerson = null;
if (userTitle != null) {
let strArray: string[] = userTitle.split(' ');
firstName = strArray[0];
lastName = strArray.length > 1 ? strArray[1] : '';
}
person = { id: userId, firstName: firstName, lastName: lastName, isInTriage: false, displayName: userTitle };
if (isSiteAdmin) {
person.isInTriage = true;
return Promise.resolve(person);
}
else {
return sp.web
.getUserById(person.id)
.groups()
.then(
groups => {
const filterGroups = lodash.filter(groups, group => {
return group.Title == Constants.ChangeRequestTriageTeamGroupName;
});
if (groups.length > 0 && filterGroups.length > 0) {
person.isInTriage = true;
}
return person;
},
err => Promise.reject(err));
}
}
} | the_stack |
import {FloppyDisk, SectorData, Side} from "trs80-base";
import {SimpleEventDispatcher} from "strongly-typed-events";
import {Machine} from "./Machine.js";
import {toHexByte} from "z80-base";
import {EventType} from "./EventScheduler.js";
// Enable debug logging.
const DEBUG_LOG = false;
// Whether this controller supports writing.
const SUPPORT_WRITING = false;
// Number of physical drives.
export const FLOPPY_DRIVE_COUNT = 4;
// Width of the index hole as a fraction of the circumference.
const HOLE_WIDTH = 0.01;
// Speed of disk.
const RPM = 300;
// How long the disk motor stays on after drive selected, in seconds.
const MOTOR_TIME_AFTER_SELECT = 2;
/**
* Converts boolean for "back" to a Side.
*/
function booleanToSide(back: boolean): Side {
return back ? Side.BACK : Side.FRONT;
}
// Type I status bits.
const STATUS_BUSY = 0x01; // Whether a command is in progress.
const STATUS_INDEX = 0x02; // The head is currently over the index hole.
const STATUS_TRACK_ZERO = 0x04; // Head is on track 0.
const STATUS_CRC_ERROR = 0x08; // CRC error.
const STATUS_SEEK_ERROR = 0x10; // Seek error.
const STATUS_HEAD_ENGAGED = 0x20; // Head engaged.
const STATUS_WRITE_PROTECTED = 0x40; // Write-protected.
const STATUS_NOT_READY = 0x80; // Disk not ready (motor not running).
// Type II and III status bits.
// STATUS_BUSY = 0x01;
const STATUS_DRQ = 0x02; // Data is ready to be read or written.
const STATUS_LOST_DATA = 0x04; // CPU was too slow to read.
// STATUS_CRC_ERROR = 0x08;
const STATUS_NOT_FOUND = 0x10; // Track, sector, or side were not found.
const STATUS_DELETED = 0x20; // On read: Sector was deleted (data is invalid, 0xF8 DAM).
const STATUS_FAULT = 0x20; // On write: Indicates a write fault.
const STATUS_REC_TYPE = 0x60;
// STATUS_WRITE_PROTECTED = 0x40;
// STATUS_NOT_READY = 0x80;
// Select register bits for writeSelect().
const SELECT_DRIVE_0 = 0x01;
const SELECT_DRIVE_1 = 0x02;
const SELECT_DRIVE_2 = 0x04;
const SELECT_DRIVE_3 = 0x08;
const SELECT_SIDE = 0x10; // 0 = front, 1 = back.
const SELECT_PRECOMP = 0x20;
const SELECT_WAIT = 0x40; // Controller should block OUT until operation is done.
const SELECT_MFM = 0x80; // Double density.
const SELECT_DRIVE_MASK = SELECT_DRIVE_0 | SELECT_DRIVE_1 | SELECT_DRIVE_2 | SELECT_DRIVE_3;
// Type of command (see below for specific commands in each type).
enum CommandType {
TYPE_I,
TYPE_II,
TYPE_III,
TYPE_IV,
}
// Commands and various sub-flags.
const COMMAND_MASK = 0xF0;
// Type I commands: cccchvrr, where
// cccc = command number
// h = head load
// v = verify (i.e., read next address to check we're on the right track)
// rr = step rate: 00=6ms, 01=12ms, 10=20ms, 11=40ms
const COMMAND_RESTORE = 0x00;
const COMMAND_SEEK = 0x10;
const COMMAND_STEP = 0x20; // Doesn't update track register.
const COMMAND_STEPU = 0x30; // Updates track register.
const COMMAND_STEP_IN = 0x40;
const COMMAND_STEP_INU = 0x50;
const COMMAND_STEP_OUT = 0x60;
const COMMAND_STEP_OUTU = 0x70;
const MASK_H = 0x08;
const MASK_V = 0x04;
// Type II commands: ccccbecd, where
// cccc = command number
// e = delay for head engage (10ms)
// b = side expected
// c = side compare (0=disable, 1=enable)
// d = select data address mark (writes only, 0 for reads):
// 0=FB (normal), 1=F8 (deleted)
const COMMAND_READ = 0x80; // Single sector.
const COMMAND_READM = 0x90; // Multiple sectors.
const COMMAND_WRITE = 0xA0;
const COMMAND_WRITEM = 0xB0;
const MASK_B = 0x08; // Side (0 = front, 1 = back).
const MASK_E = 0x04;
const MASK_C = 0x02; // Whether side (MASK_B) is defined.
const MASK_D = 0x01; // Deleted: 0 = Data is valid, DAM is 0xFB; 1 = Data is invalid, DAM is 0xF8.
// Type III commands: ccccxxxs (?), where
// cccc = command number
// xxx = ?? (usually 010)
// s = 1=READ_TRACK no synchronize; otherwise 0
const COMMAND_READ_ADDRESS = 0xC0;
const COMMAND_READ_TRACK = 0xE0;
const COMMAND_WRITE_TRACK = 0xF0;
// Type IV command: cccciiii, where
// cccc = command number
// iiii = bitmask of events to terminate and interrupt on (unused on TRS-80).
// 0000 for immediate terminate with no interrupt.
const COMMAND_FORCE_INTERRUPT = 0xD0;
/**
* Given a command, returns its type.
*/
function getCommandType(command: number): CommandType {
switch (command & COMMAND_MASK) {
case COMMAND_RESTORE:
case COMMAND_SEEK:
case COMMAND_STEP:
case COMMAND_STEPU:
case COMMAND_STEP_IN:
case COMMAND_STEP_INU:
case COMMAND_STEP_OUT:
case COMMAND_STEP_OUTU:
return CommandType.TYPE_I;
case COMMAND_READ:
case COMMAND_READM:
case COMMAND_WRITE:
case COMMAND_WRITEM:
return CommandType.TYPE_II;
case COMMAND_READ_ADDRESS:
case COMMAND_READ_TRACK:
case COMMAND_WRITE_TRACK:
return CommandType.TYPE_III;
case COMMAND_FORCE_INTERRUPT:
return CommandType.TYPE_IV;
default:
throw new Error("Unknown command 0x" + toHexByte(command));
}
}
/**
* Whether a command is for reading or writing.
*/
function isReadWriteCommand(command: number): boolean {
switch (getCommandType(command)) {
case CommandType.TYPE_II:
case CommandType.TYPE_III:
return true;
default:
return false;
}
}
/**
* State of a physical drive.
*/
class FloppyDrive {
public physicalTrack = 0;
public writeProtected = true;
public floppyDisk: FloppyDisk | undefined = undefined;
}
/**
* The disk controller. We only emulate the WD1791/93, not the Model I's WD1771.
*/
export class FloppyDiskController {
private readonly machine: Machine;
// Registers.
private status = STATUS_TRACK_ZERO | STATUS_NOT_READY;
private track = 0;
private sector = 0;
private data = 0;
// Internal state.
private currentCommand = COMMAND_RESTORE;
private side = Side.FRONT;
private doubleDensity = false;
private currentDrive = 0;
private motorOn = false;
// ID index found in by last COMMAND_READ_ADDRESS.
private lastReadAddress: number | undefined = undefined;
// State for current command.
public dataIndex = 0;
private sectorData: SectorData | undefined = undefined;
// Floppy drives.
private readonly drives: FloppyDrive[] = [];
// Timeout handle for turning off the motor.
private motorOffTimeoutHandle: number | undefined = undefined;
// Which drive is currently active, for lighting up an LED.
public readonly onActiveDrive = new SimpleEventDispatcher<number | undefined>();
// Event when a drive moves the head this many tracks.
public readonly onTrackMove = new SimpleEventDispatcher<number>();
// The number of debug readStatus() calls we've had to print. We use this to collapse
// consecutive calls, otherwise Chrome's devtools melt down.
private readStatusCounter = 1;
private readStatusLast = 0;
constructor(foo: Machine) {
this.machine = foo;
for (let i = 0; i < FLOPPY_DRIVE_COUNT; i++) {
this.drives.push(new FloppyDrive());
}
}
/**
* Put a floppy in the specified drive (0 to 3).
*/
public loadFloppyDisk(floppyDisk: FloppyDisk | undefined, driveNumber: number): void {
if (driveNumber < 0 || driveNumber >= this.drives.length) {
throw new Error("Invalid drive number " + driveNumber);
}
this.drives[driveNumber].floppyDisk = floppyDisk;
}
public readStatus(): number {
let status;
// If no disk was loaded into drive 0, just pretend that we don't
// have a disk system. Otherwise we have to hold down Break while
// booting (to get to cassette BASIC) and that's annoying.
if (this.drives[0].floppyDisk === undefined) {
status = 0xFF;
} else {
this.updateStatus();
// Clear interrupt.
this.machine.diskIntrqInterrupt(false);
status = this.status;
}
if (DEBUG_LOG) {
if (status !== this.readStatusLast) {
this.readStatusLast = status;
this.readStatusCounter = 1;
}
// See if it's a power of 2.
if ((this.readStatusCounter & (this.readStatusCounter - 1)) === 0) {
console.log("readStatus() = " + toHexByte(status) + " (x" + this.readStatusCounter + ")");
}
this.readStatusCounter += 1;
}
return status;
}
public readTrack(): number {
if (DEBUG_LOG) {
console.log("readTrack() = " + toHexByte(this.track));
this.readStatusCounter = 1;
}
return this.track;
}
public readSector(): number {
if (DEBUG_LOG) {
console.log("readSector() = " + toHexByte(this.sector));
this.readStatusCounter = 1;
}
return this.sector;
}
/**
* Read a byte of data from the sector.
*/
public readData(): number {
const drive = this.drives[this.currentDrive];
// The read command can do various things depending on the specific
// current command, but we only support reading from the diskette.
switch (this.currentCommand & COMMAND_MASK) {
case COMMAND_READ:
// Keep reading from the buffer.
if (this.sectorData !== undefined && (this.status & STATUS_DRQ) !== 0 && drive.floppyDisk !== undefined) {
this.data = this.sectorData.data[this.dataIndex];
this.dataIndex++;
if (this.dataIndex >= this.sectorData.data.length) {
this.sectorData = undefined;
this.status &= ~STATUS_DRQ;
this.machine.diskDrqInterrupt(false);
this.machine.eventScheduler.cancelByEventTypeMask(EventType.DISK_LOST_DATA);
this.machine.eventScheduler.add(EventType.DISK_DONE, this.machine.tStateCount + 64,
() => this.done(0));
}
}
break;
default:
// Might be okay, not sure.
throw new Error("Unhandled case in readData()");
}
if (DEBUG_LOG) {
// console.log("readData() = " + toHexByte(this.data));
this.readStatusCounter = 1;
}
return this.data;
}
/**
* Set current command.
*/
public writeCommand(cmd: number): void {
if (DEBUG_LOG) {
console.log("writeCommand(" + toHexByte(cmd) + ")");
}
const drive = this.drives[this.currentDrive];
// Cancel "lost data" event.
this.machine.eventScheduler.cancelByEventTypeMask(EventType.DISK_LOST_DATA);
this.machine.diskIntrqInterrupt(false);
this.sectorData = undefined;
this.currentCommand = cmd;
// Kick off anything that's based on the command.
switch (cmd & COMMAND_MASK) {
case COMMAND_RESTORE:
this.lastReadAddress = undefined;
drive.physicalTrack = 0;
this.track = 0;
this.status = STATUS_TRACK_ZERO | STATUS_BUSY;
if ((cmd & MASK_V) != 0) {
this.verify();
}
this.machine.eventScheduler.add(EventType.DISK_DONE, this.machine.tStateCount + 2000,
() => this.done(0));
break;
case COMMAND_SEEK:
this.lastReadAddress = undefined;
const moveCount = this.data - this.track;
if (moveCount !== 0) {
this.onTrackMove.dispatch(moveCount);
}
drive.physicalTrack += moveCount;
this.track = this.data;
if (drive.physicalTrack <= 0) {
// this.track too?
drive.physicalTrack = 0;
this.status = STATUS_TRACK_ZERO | STATUS_BUSY;
} else {
this.status = STATUS_BUSY;
}
// Should this set lastDirection?
if ((cmd & MASK_V) != 0) {
this.verify();
}
this.machine.eventScheduler.add(EventType.DISK_DONE, this.machine.tStateCount + 2000,
() => this.done(0));
break;
case COMMAND_READ:
// Read the sector. The bytes will be read later.
this.lastReadAddress = undefined;
this.status = STATUS_BUSY;
// Not sure how to use this. Ignored for now:
const goalSide = (cmd & MASK_C) === 0 ? undefined : booleanToSide((cmd & MASK_B) !== 0);
const sectorData = drive.floppyDisk === undefined
? undefined
: drive.floppyDisk.readSector(drive.physicalTrack, this.side, this.sector);
if (sectorData === undefined) {
this.machine.eventScheduler.add(EventType.DISK_DONE, this.machine.tStateCount + 512,
() => this.done(0));
console.error(`Didn't find sector ${this.sector} on track ${drive.physicalTrack}`);
} else {
let newStatus = 0;
if (sectorData.deleted) {
newStatus |= STATUS_DELETED;
}
if (sectorData.crcError) {
newStatus |= STATUS_CRC_ERROR;
}
this.sectorData = sectorData;
this.dataIndex = 0;
this.machine.eventScheduler.add(EventType.DISK_FIRST_DRQ, this.machine.tStateCount + 64,
() => this.firstDrq(newStatus));
}
break;
case COMMAND_WRITE:
console.log(`Sector write: ${drive.physicalTrack}, ${this.sector}, ${this.side}`);
this.status = STATUS_WRITE_PROTECTED;
break;
case COMMAND_FORCE_INTERRUPT:
// Stop whatever is going on and forget it.
this.machine.eventScheduler.cancelByEventTypeMask(EventType.DISK_ALL);
this.status = 0;
this.updateStatus();
if ((cmd & 0x07) !== 0) {
throw new Error("Conditional interrupt features not implemented");
} else if ((cmd & 0x08) !== 0) {
// Immediate interrupt.
this.machine.diskIntrqInterrupt(true);
} else {
this.machine.diskIntrqInterrupt(false);
}
break;
default:
throw new Error("Don't handle command 0x" + toHexByte(cmd));
}
}
public writeTrack(track: number): void {
if (DEBUG_LOG) {
console.log("writeTrack(" + toHexByte(track) + ")");
}
this.track = track;
}
public writeSector(sector: number): void {
if (DEBUG_LOG) {
console.log("writeSector(" + toHexByte(sector) + ")");
}
this.sector = sector;
}
public writeData(data: number): void {
if (DEBUG_LOG) {
// console.log("writeData(" + toHexByte(data) + ")");
}
const command = this.currentCommand & COMMAND_MASK;
if (command === COMMAND_WRITE || command === COMMAND_WRITE_TRACK) {
throw new Error("Can't yet write data");
}
this.data = data;
}
/**
* Select a drive.
*/
public writeSelect(value: number): void {
if (DEBUG_LOG) {
console.log("writeSelect(" + toHexByte(value) + ")");
}
this.status &= ~STATUS_NOT_READY;
this.side = booleanToSide((value & SELECT_SIDE) !== 0);
this.doubleDensity = (value & SELECT_MFM) != 0;
if ((value & SELECT_WAIT) != 0) {
// If there was an event pending, simulate waiting until it was due.
const event = this.machine.eventScheduler.getFirstEvent(EventType.DISK_ALL & ~EventType.DISK_LOST_DATA);
if (event !== undefined) {
// This puts the clock ahead immediately, but the main loop of the emulator
// will then sleep to make the real-time correct.
// TODO is this legit? Can we use another method?
this.machine.tStateCount = event.tStateCount;
this.machine.eventScheduler.dispatch(this.machine.tStateCount);
}
}
// Which drive is being enabled?
const previousDrive = this.currentDrive;
switch (value & SELECT_DRIVE_MASK) {
case 0:
this.status |= STATUS_NOT_READY;
break;
case SELECT_DRIVE_0:
this.currentDrive = 0;
break;
case SELECT_DRIVE_1:
this.currentDrive = 1;
break;
case SELECT_DRIVE_2:
this.currentDrive = 2;
break;
case SELECT_DRIVE_3:
this.currentDrive = 3;
break;
default:
throw new Error("Not drive specified in select: 0x" + toHexByte(value));
}
if (this.currentDrive !== previousDrive) {
this.updateMotorOn();
}
// If a drive was selected, turn on its motor.
if ((this.status & STATUS_NOT_READY) == 0) {
this.setMotorOn(true);
// Set timer to later turn off motor.
if (this.motorOffTimeoutHandle !== undefined) {
this.machine.eventScheduler.cancel(this.motorOffTimeoutHandle);
}
this.motorOffTimeoutHandle = this.machine.eventScheduler.add(undefined,
this.machine.tStateCount + MOTOR_TIME_AFTER_SELECT*this.machine.clockHz, () => {
this.motorOffTimeoutHandle = undefined;
this.status |= STATUS_NOT_READY;
this.setMotorOn(false);
});
}
}
/**
* Verify that head is on the expected track. Set either STATUS_NOT_FOUND or
* STATUS_SEEK_ERROR if a problem is found.
*/
private verify(): void {
const drive = this.drives[this.currentDrive];
if (drive.floppyDisk === undefined) {
this.status |= STATUS_NOT_FOUND;
} else if (drive.physicalTrack !== this.track) {
this.status |= STATUS_SEEK_ERROR;
} else {
// Make sure a sector exists on this track.
const sectorData = drive.floppyDisk.readSector(this.track, Side.FRONT, undefined);
if (sectorData === undefined) {
this.status |= STATUS_NOT_FOUND;
}
if (this.doubleDensity && !drive.floppyDisk.supportsDoubleDensity) {
this.status |= STATUS_NOT_FOUND;
}
}
}
/**
* If we're doing a non-read/write command, update the status with the state
* of the disk, track, and head position.
*/
private updateStatus(): void {
if (isReadWriteCommand(this.currentCommand)) {
// Don't modify status.
return;
}
const drive = this.drives[this.currentDrive];
if (drive.floppyDisk === undefined) {
this.status |= STATUS_INDEX;
} else {
// See if we're over the index hole.
if (this.angle() < HOLE_WIDTH) {
this.status |= STATUS_INDEX;
} else {
this.status &= ~STATUS_INDEX;
}
// See if the diskette is write protected.
if (drive.writeProtected || !SUPPORT_WRITING) {
this.status |= STATUS_WRITE_PROTECTED;
} else {
this.status &= ~STATUS_WRITE_PROTECTED;
}
}
// See if we're on track 0, which for some reason has a special bit.
if (drive.physicalTrack === 0) {
this.status |= STATUS_TRACK_ZERO;
} else {
this.status &= ~STATUS_TRACK_ZERO;
}
// RDY and HLT inputs are wired together on TRS-80 I/III/4/4P.
if ((this.status & STATUS_NOT_READY) !== 0) {
this.status &= ~STATUS_HEAD_ENGAGED;
} else {
this.status |= STATUS_HEAD_ENGAGED;
}
}
/**
* Turn motor on or off.
*/
private setMotorOn(motorOn: boolean): void {
if (motorOn !== this.motorOn) {
this.motorOn = motorOn;
this.machine.diskMotorOffInterrupt(!motorOn);
this.updateMotorOn();
}
}
/**
* Dispatch a change to the motor light.
*/
private updateMotorOn(): void {
this.onActiveDrive.dispatch(this.motorOn ? this.currentDrive : undefined);
}
// Return a value in [0,1) indicating how far we've rotated
// from the leading edge of the index hole. For the first HOLE_WIDTH we're
// on the hole itself.
private angle(): number {
// Use simulated time.
const clocksPerRevolution = Math.round(this.machine.clockHz / (RPM/60));
return (this.machine.tStateCount % clocksPerRevolution) / clocksPerRevolution;
}
/**
* Event used for delayed command completion. Clears BUSY,
* sets any additional bits specified, and generates a command
* completion interrupt.
*/
private done(bits: number): void {
this.status &= ~STATUS_BUSY;
this.status |= bits;
this.machine.diskIntrqInterrupt(true);
}
/**
* Event to abort the last command with LOST_DATA if it is
* still in progress.
*/
private lostData(cmd: number): void {
if (this.currentCommand === cmd) {
this.status &= ~STATUS_BUSY;
this.status |= STATUS_LOST_DATA;
this.sectorData = undefined;
this.machine.diskIntrqInterrupt(true);
}
}
/**
* Event used as a delayed command start. Sets DRQ, generates a DRQ interrupt,
* sets any additional bits specified, and schedules a lostData() event.
*/
private firstDrq(bits: number): void {
this.status |= STATUS_DRQ | bits;
this.machine.diskDrqInterrupt(true);
// Evaluate this now, not when the callback is run.
const currentCommand = this.currentCommand;
// If we've not finished our work within half a second, trigger a lost data interrupt.
this.machine.eventScheduler.add(EventType.DISK_LOST_DATA, this.machine.tStateCount + this.machine.clockHz/2,
() => this.lostData(currentCommand));
}
} | the_stack |
import * as chaiAsPromised from "chai-as-promised";
import * as chai from "chai";
chai.use(chaiAsPromised);
import { expect } from "chai";
import {
AlreadyHaveReaderError,
Stream,
Transform,
WriteAfterEndError,
} from "../lib/index";
import "./mocha-init";
import {
defer,
delay,
settle,
swallowErrors,
track,
readInto,
noop,
identity,
} from "./util";
describe("Stream", () => {
let s: Stream<number>;
let boomError: Error;
let abortError: Error;
let results: number[];
let promises: Promise<any>[];
beforeEach(() => {
s = new Stream<number>();
boomError = new Error("boom");
abortError = new Error("abort error");
results = [];
promises = [];
});
function pushResult(n: number): void {
results.push(n);
}
it("supports get after put", async () => {
promises.push(s.write(42));
promises.push(s.end());
promises.push(readInto(s, results));
await settle(promises);
expect(results).to.deep.equal([42]);
});
it("supports put after get", async () => {
promises.push(readInto(s, results));
promises.push(s.write(42));
promises.push(s.end());
await settle(promises);
expect(results).to.deep.equal([42]);
});
it("allows end before get", async () => {
promises.push(s.end());
promises.push(readInto(s, results));
await settle(promises);
expect(results).to.deep.equal([]);
});
it("allows get before end", async () => {
promises.push(readInto(s, results));
promises.push(s.end());
await settle(promises);
expect(results).to.deep.equal([]);
});
it("disallows write after end", async () => {
promises.push(s.end());
promises.push(
s.write(42).catch((r) => {
expect(r).to.be.instanceof(WriteAfterEndError);
})
);
promises.push(readInto(s, results));
await settle(promises);
expect(results).to.deep.equal([]);
});
it("disallows multiple ends", async () => {
const p1 = track(s.end());
const p2 = track(s.end());
const p3 = track(readInto(s, results));
await settle([p1.promise, p2.promise, p3.promise]);
expect(p1.isFulfilled).to.equal(true);
expect(p2.reason).to.be.instanceof(WriteAfterEndError);
expect(p3.isFulfilled).to.equal(true);
expect(results).to.deep.equal([]);
});
it("write fails when writing synchronously rejected promise", async () => {
const wp1 = track(s.write(Promise.reject<number>(boomError)));
const wp2 = track(s.write(42));
const ep = track(s.end());
const rp = track(readInto(s, results));
await settle([wp1.promise, wp2.promise, ep.promise, rp.promise]);
expect(wp1.reason).to.equal(boomError);
expect(wp2.isFulfilled).to.equal(true);
expect(results).to.deep.equal([42]);
expect(ep.isFulfilled).to.equal(true);
expect(rp.isFulfilled).to.equal(true);
});
it("write fails when writing asynchronously rejected promise", async () => {
const d = defer<number>();
const wp1 = track(s.write(d.promise));
const wp2 = track(s.write(42));
const ep = track(s.end());
const rp = track(readInto(s, results));
d.reject(boomError);
await settle([wp1.promise, wp2.promise, ep.promise, rp.promise]);
expect(wp1.reason).to.equal(boomError);
expect(wp2.isFulfilled).to.equal(true);
expect(results).to.deep.equal([42]);
expect(ep.isFulfilled).to.equal(true);
expect(rp.isFulfilled).to.equal(true);
});
it("resolves reads in-order for out-of-order writes", async () => {
const d = defer<number>();
promises.push(s.write(d.promise));
promises.push(s.write(2));
promises.push(s.end());
promises.push(readInto(s, results));
await delay(1);
expect(results).to.deep.equal([]);
d.resolve(1);
await settle(promises);
expect(results).to.deep.equal([1, 2]);
});
describe("abort()", () => {
it("aborts pending writes when not being processed", async () => {
const w1 = track(s.write(1));
const w2 = track(s.write(2));
s.abort(abortError);
await settle([w1.promise, w2.promise]);
expect(w1.reason).to.equal(abortError);
expect(w2.reason).to.equal(abortError);
});
it("aborts future writes when not being processed", async () => {
s.abort(abortError);
const w1 = track(s.write(1));
const w2 = track(s.write(2));
await settle([w1.promise, w2.promise]);
expect(w1.reason).to.equal(abortError);
expect(w2.reason).to.equal(abortError);
});
it("waits for reader to finish, then aborts writes until end", async () => {
swallowErrors(s.aborted());
swallowErrors(s.result());
const endDef = defer();
const endSeen = defer();
swallowErrors(endDef.promise);
const r1 = defer();
const reads = [r1.promise];
let endResult: Error | null | undefined = null;
const w1 = track(s.write(1));
const w2 = track(s.write(2));
swallowErrors(
s.forEach(
(v) => {
results.push(v);
return reads.shift();
},
(err) => {
endResult = err;
endSeen.resolve();
return endDef.promise;
}
)
);
await delay(1);
expect(w1.isPending).to.equal(true);
expect(w2.isPending).to.equal(true);
expect(results).to.deep.equal([1]);
s.abort(abortError);
const w3 = track(s.write(3));
await delay(1);
expect(w1.isPending).to.equal(true);
expect(w2.isPending).to.equal(true);
expect(w3.isPending).to.equal(true);
expect(results).to.deep.equal([1]);
r1.reject(boomError); // could do resolve() too, error is more interesting :)
await settle([w1.promise, w2.promise, w3.promise]);
expect(w1.reason).to.equal(boomError);
expect(w2.reason).to.equal(abortError);
expect(w3.reason).to.equal(abortError);
expect(results).to.deep.equal([1]);
expect(endResult).to.equal(null);
const we = track(s.end(new Error("end error")));
await endSeen.promise;
expect(endResult).to.equal(abortError);
expect(we.isPending).to.equal(true);
const enderError = new Error("ender error");
endDef.reject(enderError);
try {
await we.promise;
expect(false).to.equal(true, "expected an error");
} catch (e) {
expect(e).to.equal(enderError);
}
try {
await s.end();
expect(false).to.equal(true, "expected an error");
} catch (e) {
expect(e).to.be.instanceof(WriteAfterEndError);
}
});
it("can be called in reader", async () => {
swallowErrors(s.aborted());
swallowErrors(s.result());
let endResult: Error | null | undefined = null;
const w1 = track(s.write(1));
const w2 = track(s.write(2));
const r1 = defer();
swallowErrors(
s.forEach(
(v) => {
s.abort(abortError);
return r1.promise;
},
(e) => {
endResult = e;
}
)
);
await delay(1);
expect(w1.isPending).to.equal(true);
expect(w2.isPending).to.equal(true);
expect(endResult).to.equal(null);
r1.resolve();
await settle([w1.promise, w2.promise]);
expect(w1.value).to.equal(undefined);
expect(w2.reason).to.equal(abortError);
expect(endResult).to.equal(null);
const we = track(s.end());
await settle([we.promise]);
expect(endResult).to.equal(abortError);
expect(we.value).to.equal(undefined);
});
it("ignores multiple aborts", async () => {
swallowErrors(s.aborted());
swallowErrors(s.result());
let endResult: Error | null | undefined = null;
const w1 = track(s.write(1));
const r1 = defer();
const firstAbortError = new Error("first abort error");
s.abort(firstAbortError);
s.forEach(
(v) => {
chai.assert(false);
},
(e) => {
endResult = e;
}
);
await settle([w1.promise]);
expect(w1.reason).to.equal(firstAbortError);
expect(endResult).to.equal(null);
s.abort(abortError);
r1.resolve();
const we = track(s.end());
await settle([we.promise]);
expect(endResult).to.equal(firstAbortError);
expect(we.value).to.equal(undefined);
});
it("asynchronously calls aborter when already reading", async () => {
let abortResult: Error | null | undefined = null;
const w1 = track(s.write(1));
const r1 = defer();
s.forEach(
(v) => r1.promise,
undefined,
(e) => {
abortResult = e;
}
);
await delay(1);
s.abort(abortError);
expect(abortResult).to.equal(null);
await delay(1);
expect(abortResult).to.equal(abortError);
expect(w1.isPending).to.equal(true);
r1.resolve();
await settle([w1.promise]);
expect(w1.isFulfilled).to.equal(true);
});
it("asynchronously calls aborter when not currently reading", async () => {
swallowErrors(s.aborted());
swallowErrors(s.result());
let abortResult: Error | null | undefined = null;
const abortSeen = defer();
const w1 = track(s.write(1));
s.forEach(
(v) => undefined,
undefined,
(e) => {
abortResult = e;
abortSeen.resolve();
}
);
await delay(1);
s.abort(abortError);
expect(abortResult).to.equal(null);
await abortSeen.promise;
expect(abortResult).to.equal(abortError);
expect(w1.isFulfilled).to.equal(true);
});
it("asynchronously calls aborter when attaching late", async () => {
swallowErrors(s.aborted());
swallowErrors(s.result());
const w1 = track(s.write(1));
await delay(1);
s.abort(abortError);
await settle([w1.promise]);
expect(w1.reason).to.equal(abortError);
let abortResult: Error | null | undefined = null;
const abortSeen = defer();
swallowErrors(
s.forEach(
(v) => undefined,
undefined,
(e) => {
abortResult = e;
abortSeen.resolve();
}
)
);
expect(abortResult).to.equal(null);
await abortSeen.promise;
expect(abortResult).to.equal(abortError);
});
it("no longer calls aborter when ender finished", async () => {
const w1 = track(s.write(1));
const we = track(s.end());
let abortResult: Error | null | undefined = null;
s.forEach(
(v) => undefined,
undefined,
(e) => {
abortResult = e;
}
);
await settle([w1.promise, we.promise]);
expect(abortResult).to.equal(null);
expect(s.isEnded()).to.equal(true);
expect(w1.isFulfilled).to.equal(true);
expect(we.isFulfilled).to.equal(true);
s.abort(abortError);
const ab = track(s.aborted());
await settle([ab.promise]);
await delay(1);
expect(abortResult).to.equal(null);
expect(ab.reason).to.equal(abortError);
});
it("supports being called without a reason", async () => {
s.abort();
const p = track(s.aborted());
await p.promise.then(noop, noop);
expect(p.reason).to.be.instanceof(Error);
});
}); // abort()
describe("aborted()", () => {
it("is rejected when abort is called", async () => {
const ab = track(s.aborted());
await delay(1);
expect(ab.isPending).to.equal(true);
s.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
it("is rejected when abort is called, even after stream end", async () => {
const ab = track(s.aborted());
s.end();
await s.forEach(noop);
expect(ab.isPending).to.equal(true);
expect(s.isEnded()).to.equal(true);
s.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
});
describe("forEach()", () => {
it("handles empty stream", async () => {
let endResult: Error | null | undefined = null; // null, to distinguish from 'undefined' that gets assigned by ender
const res = track(
s.forEach(pushResult, (e?: Error) => {
endResult = e;
})
);
s.end();
await res.promise;
expect(results).to.deep.equal([]);
expect(endResult).to.equal(undefined);
expect(res.isFulfilled).to.equal(true);
});
it("handles a single value", async () => {
let endResult: Error | null | undefined = null; // null, to distinguish from 'undefined' that gets assigned by ender
const res = track(
s.forEach(pushResult, (e?: Error) => {
endResult = e;
})
);
s.write(1);
s.end();
await res.promise;
expect(results).to.deep.equal([1]);
expect(endResult).to.equal(undefined);
expect(res.isFulfilled).to.equal(true);
});
it("handles multiple values", async () => {
let endResult: Error | null | undefined = null; // null, to distinguish from 'undefined' that gets assigned by ender
const res = track(
s.forEach(pushResult, (e?: Error) => {
endResult = e;
})
);
s.write(1);
s.write(2);
s.write(3);
s.end();
await res.promise;
expect(results).to.deep.equal([1, 2, 3]);
expect(endResult).to.equal(undefined);
expect(res.isFulfilled).to.equal(true);
});
it("handles error in reader", async () => {
// Error thrown in reader should ONLY reflect back to writer, not to reader
// Allows writer to decide to send another value, abort, end normally, etc.
const endError = new Error("end boom");
let endResult: Error | null | undefined = null; // null, to distinguish from 'undefined' that gets assigned by ender
const res = track(
s.forEach(
(n) => {
throw boomError;
},
(e?: Error) => {
endResult = e;
}
)
);
// Write a value, will be rejected by reader and returned from write
const wp = track(s.write(1));
await settle([wp.promise]);
expect(endResult).to.equal(null);
expect(wp.reason).to.equal(boomError);
// Then end the stream with an error, the end() itself should return
// void promise
const ep = track(s.end(endError));
await settle([ep.promise, res.promise]);
expect(endResult).to.equal(endError);
expect(ep.value).to.equal(undefined);
expect(res.reason).to.equal(endError);
});
it("can use a default ender", async () => {
const res = track(
s.forEach((v) => {
results.push(v);
})
);
s.write(1);
s.write(2);
s.end();
await res.promise;
expect(results).to.deep.equal([1, 2]);
expect(res.isFulfilled).to.equal(true);
});
it("returns errors by default, but does not bounce them (#35)", async () => {
const res = track(
s.forEach((v) => {
results.push(v);
})
);
s.write(1);
s.write(2);
const we = track(s.end(boomError));
await settle([res.promise, we.promise]);
expect(results).to.deep.equal([1, 2]);
expect(we.isFulfilled).to.equal(true);
expect(res.reason).to.equal(boomError);
});
describe("ender errors", () => {
it("returns ender error to `end()` and reflects it in `result()` by default", async () => {
// Rationale: if error from `end()` is not explicitly handled,
// we 'bounce' it back downstream.
// The only way to 'handle' it (i.e. to communicate its result
// to observers of the stream) is to influence the stream's result,
// which can only be done by passing that result to end()'s second
// argument. No such argument is given here, so by default we bounce that error.
const result = s.forEach(noop, () => {
throw boomError;
});
const we = s.end();
await expect(result).rejectedWith(boomError);
await expect(we).rejectedWith(boomError);
});
it("allows overriding result even if ender fails", async () => {
const result = track(
s.forEach(noop, () => {
throw boomError;
})
);
const d = defer();
const we = s.end(undefined, d.promise);
await expect(we).rejectedWith(boomError);
expect(result.isPending).to.equal(true);
d.resolve();
await result.promise;
});
});
it("disallows multiple attach", async () => {
s.forEach(noop);
const result = track(s.forEach(noop));
await settle([result.promise]);
expect(result.reason).to.be.instanceof(AlreadyHaveReaderError);
});
}); // forEach()
describe("write()", () => {
it("disallows writing undefined", async () => {
const result = track(s.write(undefined as any));
await settle([result.promise]);
expect(result.reason).to.be.instanceof(TypeError);
});
}); // write()
describe("end()", () => {
it("allows null as error parameter", () => {
readInto(s, results);
return s.end(null as any);
});
it("allows undefined as error parameter", () => {
readInto(s, results);
return s.end(undefined);
});
it("allows an Error as error parameter", () => {
swallowErrors(s.result());
swallowErrors(readInto(s, results));
return settle([s.end(boomError)]);
});
it("disallows non-error as error parameter", async () => {
swallowErrors(s.result());
swallowErrors(readInto(s, results));
const result = track(s.end(<any>"boom"));
await settle([result.promise]);
expect(result.reason).to.be.instanceof(TypeError);
});
}); // end()
describe("isEnded()", () => {
it("indicates stream end after ender has run", async () => {
expect(s.isEnded()).to.equal(false);
const we = track(s.end());
await delay(1);
expect(s.isEnded()).to.equal(false);
const d = defer();
s.forEach(noop, (e) => d.promise);
await delay(1);
expect(s.isEnded()).to.equal(false);
d.resolve();
await settle([we.promise]);
expect(s.isEnded()).to.equal(true);
});
}); // isEnded()
describe("isEnding()", () => {
it("indicates stream is ending", async () => {
expect(s.isEnding()).to.equal(false);
const we = track(s.end());
await delay(1);
expect(s.isEnding()).to.equal(true);
const d = defer();
s.forEach(noop, (e) => d.promise);
await delay(1);
expect(s.isEnding()).to.equal(true);
d.resolve();
await settle([we.promise]);
expect(s.isEnding()).to.equal(false);
});
it("ignores ending after end", async () => {
expect(s.isEnding()).to.equal(false);
s.forEach(noop);
const we = track(s.end());
await settle([we.promise]);
expect(s.isEnding()).to.equal(false);
s.end().catch(noop);
await delay(1);
expect(s.isEnding()).to.equal(false);
});
}); // isEnding()
describe("isEndingOrEnded()", () => {
it("indicates stream is ending or ended", async () => {
expect(s.isEndingOrEnded()).to.equal(false);
const we = track(s.end());
await delay(1);
expect(s.isEndingOrEnded()).to.equal(true);
const d = defer();
s.forEach(noop, (e) => d.promise);
await delay(1);
expect(s.isEndingOrEnded()).to.equal(true);
d.resolve();
await settle([we.promise]);
expect(s.isEndingOrEnded()).to.equal(true);
});
}); // isEndingOrEnded()
describe("hasReader()", () => {
it("indicates whether reader/ender are attached", async () => {
expect(s.hasReader()).to.equal(false);
s.forEach(noop);
expect(s.hasReader()).to.equal(true);
await s.end();
expect(s.isEnded()).to.equal(true);
expect(s.hasReader()).to.equal(true);
});
});
describe("result()", () => {
it("indicates stream end", async () => {
const res = track(s.result());
s.end();
await delay(1);
expect(res.isPending).to.equal(true);
const d = defer();
s.forEach(noop, (e) => d.promise);
await delay(1);
expect(res.isPending).to.equal(true);
d.resolve();
await settle([res.promise]);
expect(res.isPending).to.equal(false);
expect(res.value).to.equal(undefined);
});
it("can be overridden by `end()`", async () => {
const res = track(s.result());
const endResult = defer();
s.end(undefined, endResult.promise);
await delay(1);
expect(res.isPending).to.equal(true);
const d = defer();
s.forEach(noop, (e) => d.promise);
await delay(1);
expect(res.isPending).to.equal(true);
d.resolve();
await delay(1);
expect(res.isPending).to.equal(true);
endResult.resolve();
await settle([res.promise]);
expect(res.isPending).to.equal(false);
expect(res.value).to.equal(undefined);
});
}); // result()
describe("map()", () => {
it("maps values", async () => {
const mapped = s.map((n) => n * 2);
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
readInto(mapped, results);
await s.result();
expect(results).to.deep.equal([2, 4]);
expect(writes[0].isFulfilled).to.equal(true);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("bounces thrown error", async () => {
const mapped = s.map((n) => {
if (n === 1) {
throw boomError;
} else {
return n * 2;
}
});
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
writes.forEach((t): void => {
swallowErrors(t.promise);
});
readInto(mapped, results);
await settle([s.result()]);
expect(results).to.deep.equal([4]);
expect(writes[0].reason).to.equal(boomError);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("bounces returned rejection", async () => {
const mapped = s.map((n) => {
if (n === 1) {
return Promise.reject<number>(boomError);
} else {
return n * 2;
}
});
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
writes.forEach((t): void => {
swallowErrors(t.promise);
});
readInto(mapped, results);
await settle([s.result()]);
expect(results).to.deep.equal([4]);
expect(writes[0].reason).to.equal(boomError);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("waits for source stream to end", async () => {
const d = defer();
const slowEndingSource = s.transform<number>(
(readable, writable) => {
readable.forEach(
(v) => writable.write(v),
(error?: Error) => {
writable.end(error, readable.result());
return d.promise;
}
);
}
);
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
const mapped = slowEndingSource.map((n) => n * 2);
const mres = track(mapped.result());
readInto(mapped, results);
await settle([writes[0].promise, writes[1].promise]);
await delay(1);
expect(results).to.deep.equal([2, 4]);
expect(writes[0].isFulfilled).to.equal(true);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(false);
expect(mres.isFulfilled).to.equal(false);
d.resolve();
await settle([mres.promise]);
expect(writes[2].isFulfilled).to.equal(true);
});
it("waits for destination stream to end", async () => {
const d = defer();
const slowEnder: Transform<number, number> = (
readable,
writable
) => {
readable.forEach(
(v) => writable.write(v),
(error?: Error) => {
writable.end(error, readable.result());
return d.promise;
}
);
};
const w1 = track(s.write(1));
const w2 = track(s.write(2));
const we = track(s.end());
const mapped = s.map((n) => n * 2);
const mres = track(mapped.result());
const slowed = mapped.transform(slowEnder);
const sres = track(slowed.result());
readInto(slowed, results);
await delay(1);
expect(results).to.deep.equal([2, 4]);
expect(w1.isFulfilled).to.equal(true);
expect(w2.isFulfilled).to.equal(true);
expect(we.isFulfilled).to.equal(false);
expect(mres.isFulfilled).to.equal(false);
expect(sres.isFulfilled).to.equal(false);
d.resolve();
await settle([mres.promise, sres.promise]);
});
it("calls ender and awaits its result", async () => {
const d = defer();
let endResult: Error | null | undefined = null;
const mapped = s.map(
(n) => n * 2,
(e) => {
endResult = e;
return d.promise;
}
);
readInto(mapped, results);
const w1 = track(s.write(1));
const we = track(s.end());
await delay(1);
expect(results).to.deep.equal([2]);
expect(mapped.isEnded()).to.equal(false);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
d.resolve();
await we.promise;
expect(we.isFulfilled).to.equal(true);
expect(mapped.isEnded()).to.equal(true);
});
it("returns asynchronous error in ender to writer but does end stream", async () => {
const d = defer();
let endResult: Error | null | undefined = null;
const mapped = s.map(
(n) => n * 2,
(e) => {
endResult = e;
return d.promise;
}
);
const r = track(readInto(mapped, results));
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[r, w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(mapped.result());
await delay(1);
expect(results).to.deep.equal([2]);
expect(mapped.isEnded()).to.equal(false);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
d.reject(boomError);
await settle([r.promise, res.promise]);
expect(we.reason).to.equal(boomError);
expect(mapped.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(r.reason).to.equal(boomError);
});
it("returns synchronous error in ender to writer but does end stream", async () => {
let endResult: Error | null | undefined = null;
const mapped = s.map(
(n) => n * 2,
(e) => {
endResult = e;
throw boomError;
}
);
const r = track(readInto(mapped, results));
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[r, w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(mapped.result());
await settle([r.promise, res.promise]);
expect(results).to.deep.equal([2]);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.reason).to.equal(boomError);
expect(mapped.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(r.reason).to.equal(boomError);
});
it("returns synchronous error in ender to writer even if downstream ender fails", async () => {
let endResult: Error | null | undefined = null;
const mapped = s.map(
(n) => n * 2,
(e) => {
endResult = e;
throw boomError;
}
);
let forEachEndResult: Error | null | undefined = null;
mapped.forEach(
(n) => {
results.push(n);
},
(e) => {
forEachEndResult = e;
throw new Error("some other error");
}
);
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(mapped.result());
await settle([res.promise]);
expect(results).to.deep.equal([2]);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.reason).to.equal(boomError);
expect(mapped.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(forEachEndResult).to.equal(boomError);
});
it("leaves original end error intact and waits for stream to end", async () => {
const endError = new Error("endError");
let mapEndResult: Error | null | undefined = null;
const mapped = s.map(
(n) => n * 2,
(e) => {
mapEndResult = e;
throw boomError;
}
);
const w1 = track(s.write(1));
const we = track(s.end(endError));
const res = track(s.result());
swallowErrors(mapped.result());
let forEachEndResult: Error | null | undefined = null;
const d = defer();
mapped.forEach(
(n) => {
results.push(n);
},
(e) => {
forEachEndResult = e;
return d.promise;
}
);
while (!mapped.isEnding()) {
await delay(1);
}
expect(mapEndResult).to.equal(endError);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
expect(mapped.isEnding()).to.equal(true);
expect(mapped.isEnded()).to.equal(false);
expect(res.isPending).to.equal(true);
d.resolve();
await settle([res.promise, we.promise]);
expect(results).to.deep.equal([2]);
expect(we.reason).to.equal(boomError);
expect(mapped.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(forEachEndResult).to.equal(endError);
});
it("supports aborter", async () => {
let abortResult: Error | null | undefined = null;
const abortSeen = defer();
const mapped = s.map(
(n) => n * 2,
undefined,
(e) => {
abortResult = e;
abortSeen.resolve();
}
);
mapped.abort(abortError);
await abortSeen.promise;
expect(abortResult).to.equal(abortError);
});
it("aborts from source to sink", async () => {
const sink = s.map(identity).map(identity);
const ab = track(sink.aborted());
s.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
it("aborts from sink to source", async () => {
const ab = track(s.aborted());
const sink = s.map(identity).map(identity);
sink.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
}); // map()
describe("filter()", () => {
it("filters values", async () => {
const filtered = s.filter((n) => n % 2 === 0);
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
readInto(filtered, results);
await s.result();
expect(results).to.deep.equal([2]);
expect(writes[0].isFulfilled).to.equal(true);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("filters values async", async () => {
const filtered = s.filter(async (n) => n % 2 === 0);
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
readInto(filtered, results);
await s.result();
expect(results).to.deep.equal([2]);
expect(writes[0].isFulfilled).to.equal(true);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("bounces thrown error", async () => {
const filtered = s.filter((n) => {
if (n === 1) {
throw boomError;
} else {
return n % 2 === 0;
}
});
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
writes.forEach((t): void => {
swallowErrors(t.promise);
});
readInto(filtered, results);
await settle([s.result()]);
expect(results).to.deep.equal([2]);
expect(writes[0].reason).to.equal(boomError);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("bounces returned rejection", async () => {
const filtered = s.filter((n) => {
if (n === 1) {
return Promise.reject(boomError);
} else {
return n % 2 === 0;
}
});
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
writes.forEach((t): void => {
swallowErrors(t.promise);
});
readInto(filtered, results);
await settle([s.result()]);
expect(results).to.deep.equal([2]);
expect(writes[0].reason).to.equal(boomError);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(true);
});
it("waits for source stream to end", async () => {
const d = defer();
const slowEndingSource = s.transform<number>(
(readable, writable) => {
readable.forEach(
(v) => writable.write(v),
(error?: Error) => {
writable.end(error, readable.result());
return d.promise;
}
);
}
);
const writes = [
track(s.write(1)),
track(s.write(2)),
track(s.end()),
];
const filtered = slowEndingSource.filter((n) => n % 2 === 0);
const mres = track(filtered.result());
readInto(filtered, results);
await settle([writes[0].promise, writes[1].promise]);
await delay(1);
expect(results).to.deep.equal([2]);
expect(writes[0].isFulfilled).to.equal(true);
expect(writes[1].isFulfilled).to.equal(true);
expect(writes[2].isFulfilled).to.equal(false);
expect(mres.isFulfilled).to.equal(false);
d.resolve();
await settle([mres.promise]);
});
it("waits for destination stream to end", async () => {
const d = defer();
const slowEnder: Transform<number, number> = (
readable,
writable
) => {
readable.forEach(
(v) => writable.write(v),
(error?: Error) => {
writable.end(error, readable.result());
return d.promise;
}
);
};
const w1 = track(s.write(1));
const w2 = track(s.write(2));
const we = track(s.end());
const filtered = s.filter((n) => n % 2 === 0);
const mres = track(filtered.result());
const slowed = filtered.transform(slowEnder);
const sres = track(slowed.result());
readInto(slowed, results);
await delay(1);
expect(results).to.deep.equal([2]);
expect(w1.isFulfilled).to.equal(true);
expect(w2.isFulfilled).to.equal(true);
expect(we.isFulfilled).to.equal(false);
expect(mres.isFulfilled).to.equal(false);
expect(sres.isFulfilled).to.equal(false);
d.resolve();
await settle([mres.promise, sres.promise]);
});
it("calls ender and awaits its result", async () => {
const d = defer();
let endResult: Error | null | undefined = null;
const filtered = s.filter(
(n) => true,
(e) => {
endResult = e;
return d.promise;
}
);
readInto(filtered, results);
const w1 = track(s.write(1));
const we = track(s.end());
await delay(1);
expect(results).to.deep.equal([1]);
expect(filtered.isEnded()).to.equal(false);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
d.resolve();
await we.promise;
expect(we.isFulfilled).to.equal(true);
expect(filtered.isEnded()).to.equal(true);
});
it("returns asynchronous error in ender to writer but does end stream", async () => {
const d = defer();
let endResult: Error | null | undefined = null;
const filtered = s.filter(
(n) => true,
(e) => {
endResult = e;
return d.promise;
}
);
const r = track(readInto(filtered, results));
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[r, w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(filtered.result());
await delay(1);
expect(results).to.deep.equal([1]);
expect(filtered.isEnded()).to.equal(false);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
d.reject(boomError);
await settle([r.promise, res.promise]);
expect(we.reason).to.equal(boomError);
expect(filtered.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(r.reason).to.equal(boomError);
});
it("returns synchronous error in ender to writer but does end stream", async () => {
let endResult: Error | null | undefined = null;
const filtered = s.filter(
(n) => true,
(e) => {
endResult = e;
throw boomError;
}
);
const r = track(readInto(filtered, results));
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[r, w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(filtered.result());
await settle([r.promise, res.promise]);
expect(results).to.deep.equal([1]);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.reason).to.equal(boomError);
expect(filtered.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(r.reason).to.equal(boomError);
});
it("returns synchronous error in ender to writer even if downstream ender fails", async () => {
let endResult: Error | null | undefined = null;
const filtered = s.filter(
(n) => true,
(e) => {
endResult = e;
throw boomError;
}
);
let forEachEndResult: Error | null | undefined = null;
filtered.forEach(
(n) => {
results.push(n);
},
(e) => {
forEachEndResult = e;
throw new Error("some other error");
}
);
const w1 = track(s.write(1));
const we = track(s.end());
const res = track(s.result());
[w1, we, res].forEach((t): void => {
swallowErrors(t.promise);
});
swallowErrors(filtered.result());
await settle([res.promise]);
expect(results).to.deep.equal([1]);
expect(endResult).to.equal(undefined);
expect(w1.isFulfilled).to.equal(true);
expect(we.reason).to.equal(boomError);
expect(filtered.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(forEachEndResult).to.equal(boomError);
});
it("leaves original end error intact and waits for stream to end", async () => {
const endError = new Error("endError");
let mapEndResult: Error | null | undefined = null;
const filtered = s.filter(
(n) => true,
(e) => {
mapEndResult = e;
throw boomError;
}
);
const w1 = track(s.write(1));
const we = track(s.end(endError));
const res = track(s.result());
swallowErrors(filtered.result());
let forEachEndResult: Error | null | undefined = null;
const d = defer();
filtered.forEach(
(n) => {
results.push(n);
},
(e) => {
forEachEndResult = e;
return d.promise;
}
);
while (!filtered.isEnding()) {
await delay(1);
}
expect(mapEndResult).to.equal(endError);
expect(w1.isFulfilled).to.equal(true);
expect(we.isPending).to.equal(true);
expect(filtered.isEnding()).to.equal(true);
expect(filtered.isEnded()).to.equal(false);
expect(res.isPending).to.equal(true);
d.resolve();
await settle([res.promise, we.promise]);
expect(results).to.deep.equal([1]);
expect(we.reason).to.equal(boomError);
expect(filtered.isEnded()).to.equal(true);
expect(s.isEnded()).to.equal(true);
expect(res.reason).to.equal(boomError);
expect(forEachEndResult).to.equal(endError);
});
it("supports aborter", async () => {
let abortResult: Error | null | undefined = null;
const abortSeen = defer();
const filtered = s.filter(
(n) => true,
undefined,
(e) => {
abortResult = e;
abortSeen.resolve();
}
);
filtered.abort(abortError);
await abortSeen.promise;
expect(abortResult).to.equal(abortError);
});
it("aborts from source to sink", async () => {
const sink = s.filter(() => true).map(identity);
const ab = track(sink.aborted());
s.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
it("aborts from sink to source", async () => {
const ab = track(s.aborted());
const sink = s.filter(() => true).map(identity);
sink.abort(abortError);
await settle([ab.promise]);
expect(ab.reason).to.equal(abortError);
});
}); // filter()
describe("reduce()", () => {
it("can be used to sum values", async () => {
const x = Stream.from([1, 2, 3, 4]);
const value = await x.reduce((a, b) => a + b);
expect(value).to.equal(10);
});
it("can be used to sum values with seed", async () => {
const x = Stream.from([1, 2, 3, 4]);
const value = await x.reduce((a, b) => a + b, 10);
expect(value).to.equal(20);
});
it("can be used to implement toArray()", async () => {
const x = Stream.from([1, 2, 3, 4]);
const value = await x.reduce((arr: number[], v: number) => {
arr.push(v);
return arr;
}, []);
expect(value).to.deep.equal([1, 2, 3, 4]);
});
it("calls reducer with same args as Array#reduce, without initial value", async () => {
const arr = [1, 2, 3, 4];
let calls: any[][];
let previouses: number[];
function reducer(...args: any[]): number {
// Skip the last arg though (either the array or stream)
calls.push(args.slice(0, 3));
return previouses.shift()!;
}
calls = [];
previouses = [-10, -20, -30];
const arrResult = arr.reduce(reducer);
const arrCalls = calls;
expect(previouses).to.deep.equal([]);
calls = [];
previouses = [-10, -20, -30];
const x = Stream.from(arr);
const value = await x.reduce(reducer);
expect(value).to.equal(arrResult);
expect(previouses).to.deep.equal([]);
expect(calls).to.deep.equal(arrCalls);
});
it("calls reducer with same args as Array#reduce, with initial value", async () => {
const arr = [1, 2, 3, 4];
let calls: any[][];
let previouses: number[];
function reducer(...args: any[]): number {
// Skip the last arg though (either the array or stream)
calls.push(args.slice(0, 3));
return previouses.shift()!;
}
calls = [];
previouses = [-20, -30, -40, -50];
const arrResult = arr.reduce(reducer, -10);
const arrCalls = calls;
expect(previouses).to.deep.equal([]);
calls = [];
previouses = [-20, -30, -40, -50];
const x = Stream.from(arr);
const value = await x.reduce(reducer, -10);
expect(value).to.equal(arrResult);
expect(previouses).to.deep.equal([]);
expect(calls).to.deep.equal(arrCalls);
});
it("calls reducer with stream as 4th arg, without initial value", async () => {
const x = Stream.from([1, 2, 3, 4]);
const calls: any[][] = [];
const previouses = [-1, -2, -3];
function reducer(...args: any[]): number {
calls.push(args);
return previouses.shift()!;
}
const value = await x.reduce(reducer);
expect(value).to.equal(-3);
expect(previouses).to.deep.equal([]);
expect(calls).to.deep.equal([
[1, 2, 1, x],
[-1, 3, 2, x],
[-2, 4, 3, x],
]);
});
it("accepts promise from reducer", async () => {
const d = defer<number>();
const reduceResult = track(s.reduce(() => d.promise, 0));
const writeResult = track(s.write(1));
await delay(1);
expect(reduceResult.isPending).to.equal(true);
expect(writeResult.isPending).to.equal(true);
d.resolve(100);
await settle([writeResult.promise]);
expect(reduceResult.isPending).to.equal(true);
expect(writeResult.isFulfilled).to.equal(true);
s.end();
await settle([reduceResult.promise]);
expect(reduceResult.value).to.equal(100);
});
it("returns error when stream is empty without initial value", async () => {
const reduceResult = track(s.reduce(() => 0));
s.end();
await settle([reduceResult.promise]);
expect(reduceResult.reason).to.be.instanceof(TypeError);
});
it("returns thrown error to writer", async () => {
const reduceResult = track(
s.reduce((prev, curr): number => {
throw boomError;
}, 0)
);
const writeResult = track(s.write(1));
await settle([writeResult.promise]);
expect(reduceResult.isPending).to.equal(true);
expect(writeResult.reason).to.equal(boomError);
s.end();
await settle([reduceResult.promise]);
expect(reduceResult.isFulfilled).to.equal(true);
});
it("returns rejected error to writer", async () => {
const reduceResult = track(
s.reduce((prev, curr) => Promise.reject<number>(boomError), 0)
);
const writeResult = track(s.write(1));
await settle([writeResult.promise]);
expect(reduceResult.isPending).to.equal(true);
expect(writeResult.reason).to.equal(boomError);
s.end();
await settle([reduceResult.promise]);
expect(reduceResult.isFulfilled).to.equal(true);
});
}); // reduce()
describe("toArray()", () => {
it("returns all values in the stream", async () => {
const value = await Stream.from([1, 2, 3, 4]).toArray();
expect(value).to.deep.equal([1, 2, 3, 4]);
});
it("returns empty array for empty stream", async () => {
const value = await Stream.from([]).toArray();
expect(value).to.deep.equal([]);
});
it("returns end error if stream ended with error", async () => {
swallowErrors(s.result());
const result = track(s.toArray());
swallowErrors(s.end(boomError));
await settle([result.promise]);
expect(result.reason).to.deep.equal(boomError);
});
it("doesn't bounce end error (#35)", async () => {
const result = track(s.toArray());
await s.end(boomError);
await result.promise.then(undefined, noop);
expect(result.reason).to.equal(boomError);
});
}); // toArray()
describe("pipe()", () => {
it("moves values from source to destination", async () => {
const source = Stream.from([1, 2, 3, 4]);
const destination = new Stream<number>();
source.pipe(destination);
const result = await destination.toArray();
expect(result).to.deep.equal([1, 2, 3, 4]);
});
it("aborts source when aborting destination", (done) => {
const source = Stream.from([1, 2, 3, 4]);
const destination = new Stream<number>();
source.pipe(destination);
destination.abort();
source.aborted().catch((reason) => {
expect(reason.message).to.contain("aborted");
done();
});
});
it("aborts destination when aborting source", (done) => {
const source = Stream.from([1, 2, 3, 4]);
const destination = new Stream<number>();
source.pipe(destination);
source.abort();
destination.aborted().catch((reason) => {
expect(reason.message).to.contain("aborted");
done();
});
});
});
describe("writeEach()", () => {
it("calls callback until undefined is returned", async () => {
const values = [1, 2, undefined, 3];
const writeResult = track(s.writeEach(() => values.shift()));
await s.forEach((v) => {
results.push(v);
});
expect(s.isEnded()).to.equal(true);
expect(results).to.deep.equal([1, 2]);
expect(values).to.deep.equal([3]);
expect(writeResult.isFulfilled).to.equal(true);
});
it("waits for next call until previous value is processed", async () => {
const values = [1, 2];
const writeResult = track(s.writeEach(() => values.shift()));
await delay(1);
expect(values).to.deep.equal([2]);
const fe = s.forEach((v) => {
results.push(v);
});
await settle([fe, writeResult.promise]);
expect(results).to.deep.equal([1, 2]);
expect(writeResult.isFulfilled).to.equal(true);
});
it("handles synchronous exception in writer", async () => {
swallowErrors(s.result());
const writeResult = track(
s.writeEach(() => {
throw boomError;
})
);
const fe = s.forEach(noop);
await settle([fe, writeResult.promise]);
expect(s.isEnded()).to.equal(true);
expect(writeResult.reason).to.equal(boomError);
});
it("handles all values and stream end as promises", async () => {
const values = [1, 2];
const writeResult = track(
s.writeEach(() => Promise.resolve(values.shift()))
);
const fe = s.forEach((v) => {
results.push(v);
});
await settle([fe, writeResult.promise]);
expect(results).to.deep.equal([1, 2]);
expect(writeResult.isFulfilled).to.equal(true);
});
it("aborts and ends with error on write error", async () => {
swallowErrors(s.result());
const ab = track(s.aborted());
const values = [1, 2, 3];
const writeResult = track(s.writeEach(() => values.shift()));
let endResult: Error | null | undefined = null;
const forEachResult = track(
s.forEach(
(v) => {
if (v === 2) {
return Promise.reject(boomError);
}
},
(error?: Error) => {
endResult = error;
}
)
);
await settle([
ab.promise,
forEachResult.promise,
writeResult.promise,
]);
expect(values).to.deep.equal([3]);
expect(s.isEnded()).to.equal(true);
expect(ab.reason).to.equal(boomError);
expect(endResult).to.equal(boomError);
expect(forEachResult.reason).to.equal(boomError);
expect(writeResult.reason).to.equal(boomError);
});
it("aborts and ends with error on normal end error", async () => {
swallowErrors(s.result());
const ab = track(s.aborted());
const values = [1, 2];
const writeResult = track(s.writeEach(() => values.shift()));
const forEachResult = track(
s.forEach(noop, (error?: Error) => Promise.reject(boomError))
);
await settle([
ab.promise,
forEachResult.promise,
writeResult.promise,
]);
expect(values).to.deep.equal([]);
expect(s.isEnded()).to.equal(true);
expect(ab.reason).to.equal(boomError);
expect(forEachResult.reason).to.equal(boomError);
expect(writeResult.reason).to.equal(boomError);
});
it("ends with error on end error after abort", async () => {
swallowErrors(s.result());
const ab = track(s.aborted());
const values = [1, 2];
const writeResult = track(s.writeEach(() => values.shift()));
s.abort(abortError);
const forEachResult = track(
s.forEach(noop, (error?: Error) => Promise.reject(boomError))
);
await settle([
ab.promise,
forEachResult.promise,
writeResult.promise,
]);
expect(values).to.deep.equal([1, 2]);
expect(s.isEnded()).to.equal(true);
expect(ab.reason).to.equal(abortError);
expect(forEachResult.reason).to.equal(boomError);
expect(writeResult.reason).to.equal(boomError);
});
it("handles abort bounce", async () => {
swallowErrors(s.result());
swallowErrors(s.aborted());
const values = [1, 2, 3];
const writeResult = track(s.writeEach(() => values.shift()));
const forEachResult = track(
s.forEach(
(v) => {
if (v === 2) {
return Promise.reject(boomError);
}
}
// Note: no end handler, so default, which 'bounces' the given
// error
)
);
await settle([forEachResult.promise, writeResult.promise]);
expect(values).to.deep.equal([3]);
expect(s.isEnded()).to.equal(true);
expect(forEachResult.reason).to.equal(boomError);
expect(writeResult.reason).to.equal(boomError);
});
it("ends on abort", async () => {
swallowErrors(s.result());
swallowErrors(s.aborted());
const values = [1, 2, 3];
const writeResult = track(s.writeEach(() => values.shift()));
let endResult: Error | null | undefined = null;
const d = defer();
const forEachResult = track(
s.forEach(
(v) => d.promise,
(err?) => {
endResult = err;
}
)
);
await delay(1);
expect(values).to.deep.equal([2, 3]);
s.abort(abortError);
d.resolve();
await settle([forEachResult.promise, writeResult.promise]);
expect(values).to.deep.equal([2, 3]);
expect(s.isEnded()).to.equal(true);
expect(endResult).to.equal(abortError);
expect(forEachResult.reason).to.equal(abortError);
expect(writeResult.reason).to.equal(abortError);
});
it("asynchronously calls writer", async () => {
let called = false;
s.writeEach(() => {
called = true;
});
expect(called).to.equal(false);
});
it("waits for writer to finish after abort before calling ender", async () => {
swallowErrors(s.aborted());
const d = defer();
let called = false;
swallowErrors(
s.writeEach(
() => d.promise,
() => {
called = true;
}
)
);
await delay(1); // ensure writer is called
s.abort();
await delay(1);
expect(called).to.equal(false);
d.resolve();
await delay(1);
expect(called).to.equal(true);
});
it("calls ender without arguments after stream ends", async () => {
let called = false;
s.forEach(noop); // flush stream
await s.writeEach(
() => undefined,
(...args) => {
expect(args.length).to.equal(0);
called = true;
}
);
expect(called).to.equal(true);
});
it("calls ender with abort error when writer throws", async () => {
let called = false;
s.forEach(noop); // flush stream
const writeEachResult = s.writeEach(
() => {
throw new Error("boom");
},
(err) => {
expect(err && err.message).to.equal("boom");
called = true;
}
);
await writeEachResult.catch(noop);
expect(called).to.equal(true);
});
it("calls aborter with writer error", async () => {
let called = false;
s.forEach(noop); // flush stream
const writeEachResult = s.writeEach(
() => {
throw new Error("boom");
},
noop,
(err) => {
expect(err.message).to.equal("boom");
called = true;
}
);
await writeEachResult.catch(noop);
expect(called).to.equal(true);
});
it("calls aborter with writer error", async () => {
let called = false;
swallowErrors(s.aborted());
s.forEach(noop); // flush stream
const writeEachResult = s.writeEach(
() => {
throw new Error("boom");
},
noop,
(err) => {
expect(err.message).to.equal("boom");
called = true;
}
);
await writeEachResult.catch(noop);
expect(called).to.equal(true);
});
it("calls aborter once even when writer is still pending", async () => {
swallowErrors(s.aborted());
const d = defer();
let enderCalled = 0;
let aborterCalled = 0;
swallowErrors(
s.writeEach(
() => d.promise,
() => {
enderCalled++;
},
() => {
aborterCalled++;
}
)
);
await delay(1); // ensure writer is called
s.abort();
await delay(1);
expect(enderCalled).to.equal(0);
expect(aborterCalled).to.equal(1);
d.reject(new Error("boom"));
await delay(1);
expect(enderCalled).to.equal(1);
expect(aborterCalled).to.equal(1);
});
it("calls aborter once even when ender has ended", async () => {
swallowErrors(s.aborted());
let enderCalled = 0;
let aborterCalled = 0;
swallowErrors(
s.writeEach(
() => undefined,
() => {
enderCalled++;
},
() => {
aborterCalled++;
}
)
);
await delay(1); // ensure writer is called
expect(enderCalled).to.equal(1);
expect(aborterCalled).to.equal(0);
s.abort();
await delay(1);
expect(enderCalled).to.equal(1);
expect(aborterCalled).to.equal(1);
});
}); // writeEach()
describe("from()", () => {
it("produces all values, then ends", async () => {
const x = Stream.from([1, 2]);
await x.forEach((v) => {
results.push(v);
});
expect(x.isEnded()).to.equal(true);
expect(results).to.deep.equal([1, 2]);
});
it("supports promise for array", async () => {
const x = Stream.from(Promise.resolve([1, 2]));
await x.forEach((v) => {
results.push(v);
});
expect(results).to.deep.equal([1, 2]);
});
it("supports array of promises", async () => {
const x = Stream.from([Promise.resolve(1), Promise.resolve(2)]);
await x.forEach((v) => {
results.push(v);
});
expect(results).to.deep.equal([1, 2]);
});
it("supports promise for array of promises", async () => {
const x = Stream.from<number>(
Promise.resolve([Promise.resolve(1), Promise.resolve(2)])
);
await x.forEach((v: number) => {
results.push(v);
});
expect(results).to.deep.equal([1, 2]);
});
it("ends on first undefined", async () => {
const x = Stream.from<any>([1, 2, undefined, 3]);
await x.forEach((v) => {
results.push(v);
});
expect(x.isEnded()).to.equal(true);
expect(results).to.deep.equal([1, 2]);
});
it("aborts on write error", async () => {
const x = Stream.from([1, 2]);
swallowErrors(x.result());
swallowErrors(x.aborted());
let endResult: Error | null | undefined = null;
const result = track(
x.forEach(
(v) => {
if (v === 2) {
return Promise.reject(boomError);
}
},
(error?: Error) => {
endResult = error;
}
)
);
await settle([result.promise]);
expect(x.isEnded()).to.equal(true);
expect(endResult).to.equal(boomError);
expect(result.reason).to.equal(boomError);
});
it("handles abort bounce", async () => {
const x = Stream.from([1, 2]);
swallowErrors(x.result());
swallowErrors(x.aborted());
const result = track(
x.forEach(
(v) => {
if (v === 2) {
return Promise.reject(boomError);
}
}
// Note: no end handler, so default, which 'bounces' the given
// error
)
);
await settle([result.promise]);
expect(x.isEnded()).to.equal(true);
expect(result.reason).to.equal(boomError);
});
it("ends on abort", async () => {
const x = Stream.from([1, 2]);
swallowErrors(x.result());
swallowErrors(x.aborted());
let endResult: Error | null | undefined = null;
const d = defer();
const result = track(
x.forEach(
(v) => d.promise,
(err?) => {
endResult = err;
}
)
);
await delay(1);
x.abort(abortError);
d.resolve();
await settle([result.promise]);
expect(x.isEnded()).to.equal(true);
expect(endResult).to.equal(abortError);
expect(result.reason).to.equal(abortError);
});
}); // from()
describe("issue #31", (): void => {
it("should not result in unhandled rejections", (done: Mocha.Done) => {
const result = new Stream();
const stream = new Stream();
stream.end(new Error("foo")).catch((error) => undefined);
stream.pipe(result);
result.forEach(() => undefined).catch(() => undefined);
setTimeout(done, 10);
});
it("should wait for source stream before passing on result", async () => {
const enderError = new Error("enderError");
const endError = new Error("endError");
const result = new Stream();
const stream = new Stream();
const d = defer();
// Create stream that already ended with an error.
// `stream.forEach()`'s ender itself doesn't throw,
// so this `end()` also doesn't.
// Because we don't pass an explicit result, the final
// result will be our end error.
stream.end(endError);
// Pipe to follow-up stream, but make the end of result stream wait on `d`
const streamResult = stream.forEach(
(v) => result.write(v),
(e) => {
swallowErrors(result.end(e, stream.result()));
return d.promise;
}
);
let ended = false;
let finished: Error | undefined;
result
.forEach(
() => undefined,
(err) => {
ended = true;
throw enderError;
}
)
.catch((e) => {
finished = e;
});
// Prevent unhandled rejection errors due to delays below
streamResult.catch(noop);
await delay(0); // have to tick macro queue
expect(ended).to.equal(true);
expect(finished).to.equal(undefined);
d.resolve();
await delay(0); // have to tick macro queue
expect(finished).to.equal(endError);
expect(streamResult).eventually.rejectedWith(endError);
});
});
}); | the_stack |
import 'vs/css!./notebookOutline';
import { Codicon } from 'vs/base/common/codicons';
import { Emitter, Event } from 'vs/base/common/event';
import { combinedDisposable, IDisposable, Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { IActiveNotebookEditor, ICellViewModel } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { NotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookEditor';
import { CellKind } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { IOutline, IOutlineComparator, IOutlineCreator, IOutlineListConfig, IOutlineService, IQuickPickDataSource, IQuickPickOutlineElement, OutlineChangeEvent, OutlineConfigKeys, OutlineTarget } from 'vs/workbench/services/outline/browser/outline';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions';
import { Registry } from 'vs/platform/registry/common/platform';
import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IEditorPane } from 'vs/workbench/common/editor';
import { IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import { IDataSource, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree';
import { createMatches, FuzzyScore } from 'vs/base/common/filters';
import { IconLabel, IIconLabelValueOptions } from 'vs/base/browser/ui/iconLabel/iconLabel';
import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget';
import { IEditorOptions } from 'vs/platform/editor/common/editor';
import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { getIconClassesForLanguageId } from 'vs/editor/common/services/getIconClasses';
import { IWorkbenchDataTreeOptions } from 'vs/platform/list/browser/listService';
import { localize } from 'vs/nls';
import { IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { listErrorForeground, listWarningForeground } from 'vs/platform/theme/common/colorRegistry';
import { isEqual } from 'vs/base/common/resources';
import { IdleValue } from 'vs/base/common/async';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
import { marked } from 'vs/base/common/marked/marked';
import { renderMarkdownAsPlaintext } from 'vs/base/browser/markdownRenderer';
import { INotebookExecutionStateService } from 'vs/workbench/contrib/notebook/common/notebookExecutionStateService';
import { executingStateIcon } from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { URI } from 'vs/base/common/uri';
export interface IOutlineMarkerInfo {
readonly count: number;
readonly topSev: MarkerSeverity;
}
export class OutlineEntry {
private _children: OutlineEntry[] = [];
private _parent: OutlineEntry | undefined;
private _markerInfo: IOutlineMarkerInfo | undefined;
get icon(): ThemeIcon {
return this.isExecuting && this.isPaused ? executingStateIcon :
this.isExecuting ? ThemeIcon.modify(executingStateIcon, 'spin') :
this.cell.cellKind === CellKind.Markup ? Codicon.markdown : Codicon.code;
}
constructor(
readonly index: number,
readonly level: number,
readonly cell: ICellViewModel,
readonly label: string,
readonly isExecuting: boolean,
readonly isPaused: boolean
) { }
addChild(entry: OutlineEntry) {
this._children.push(entry);
entry._parent = this;
}
get parent(): OutlineEntry | undefined {
return this._parent;
}
get children(): Iterable<OutlineEntry> {
return this._children;
}
get markerInfo(): IOutlineMarkerInfo | undefined {
return this._markerInfo;
}
updateMarkers(markerService: IMarkerService): void {
if (this.cell.cellKind === CellKind.Code) {
// a code cell can have marker
const marker = markerService.read({ resource: this.cell.uri, severities: MarkerSeverity.Error | MarkerSeverity.Warning });
if (marker.length === 0) {
this._markerInfo = undefined;
} else {
const topSev = marker.find(a => a.severity === MarkerSeverity.Error)?.severity ?? MarkerSeverity.Warning;
this._markerInfo = { topSev, count: marker.length };
}
} else {
// a markdown cell can inherit markers from its children
let topChild: MarkerSeverity | undefined;
for (const child of this.children) {
child.updateMarkers(markerService);
if (child.markerInfo) {
topChild = !topChild ? child.markerInfo.topSev : Math.max(child.markerInfo.topSev, topChild);
}
}
this._markerInfo = topChild && { topSev: topChild, count: 0 };
}
}
clearMarkers(): void {
this._markerInfo = undefined;
for (const child of this.children) {
child.clearMarkers();
}
}
find(cell: ICellViewModel, parents: OutlineEntry[]): OutlineEntry | undefined {
if (cell.id === this.cell.id) {
return this;
}
parents.push(this);
for (const child of this.children) {
const result = child.find(cell, parents);
if (result) {
return result;
}
}
parents.pop();
return undefined;
}
asFlatList(bucket: OutlineEntry[]): void {
bucket.push(this);
for (const child of this.children) {
child.asFlatList(bucket);
}
}
}
class NotebookOutlineTemplate {
static readonly templateId = 'NotebookOutlineRenderer';
constructor(
readonly container: HTMLElement,
readonly iconClass: HTMLElement,
readonly iconLabel: IconLabel,
readonly decoration: HTMLElement
) { }
}
class NotebookOutlineRenderer implements ITreeRenderer<OutlineEntry, FuzzyScore, NotebookOutlineTemplate> {
templateId: string = NotebookOutlineTemplate.templateId;
constructor(
@IThemeService private readonly _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
) { }
renderTemplate(container: HTMLElement): NotebookOutlineTemplate {
container.classList.add('notebook-outline-element', 'show-file-icons');
const iconClass = document.createElement('div');
container.append(iconClass);
const iconLabel = new IconLabel(container, { supportHighlights: true });
const decoration = document.createElement('div');
decoration.className = 'element-decoration';
container.append(decoration);
return new NotebookOutlineTemplate(container, iconClass, iconLabel, decoration);
}
renderElement(node: ITreeNode<OutlineEntry, FuzzyScore>, _index: number, template: NotebookOutlineTemplate, _height: number | undefined): void {
const options: IIconLabelValueOptions = {
matches: createMatches(node.filterData),
labelEscapeNewLines: true,
extraClasses: []
};
if (node.element.cell.cellKind === CellKind.Code && this._themeService.getFileIconTheme().hasFileIcons && !node.element.isExecuting) {
template.iconClass.className = '';
options.extraClasses?.push(...getIconClassesForLanguageId(node.element.cell.language ?? ''));
} else {
template.iconClass.className = 'element-icon ' + ThemeIcon.asClassNameArray(node.element.icon).join(' ');
}
template.iconLabel.setLabel(node.element.label, undefined, options);
const { markerInfo } = node.element;
template.container.style.removeProperty('--outline-element-color');
template.decoration.innerText = '';
if (markerInfo) {
const useBadges = this._configurationService.getValue(OutlineConfigKeys.problemsBadges);
if (!useBadges) {
template.decoration.classList.remove('bubble');
template.decoration.innerText = '';
} else if (markerInfo.count === 0) {
template.decoration.classList.add('bubble');
template.decoration.innerText = '\uea71';
} else {
template.decoration.classList.remove('bubble');
template.decoration.innerText = markerInfo.count > 9 ? '9+' : String(markerInfo.count);
}
const color = this._themeService.getColorTheme().getColor(markerInfo.topSev === MarkerSeverity.Error ? listErrorForeground : listWarningForeground);
const useColors = this._configurationService.getValue(OutlineConfigKeys.problemsColors);
if (!useColors) {
template.container.style.removeProperty('--outline-element-color');
template.decoration.style.setProperty('--outline-element-color', color?.toString() ?? 'inherit');
} else {
template.container.style.setProperty('--outline-element-color', color?.toString() ?? 'inherit');
}
}
}
disposeTemplate(templateData: NotebookOutlineTemplate): void {
templateData.iconLabel.dispose();
}
}
class NotebookOutlineAccessibility implements IListAccessibilityProvider<OutlineEntry> {
getAriaLabel(element: OutlineEntry): string | null {
return element.label;
}
getWidgetAriaLabel(): string {
return '';
}
}
class NotebookNavigationLabelProvider implements IKeyboardNavigationLabelProvider<OutlineEntry> {
getKeyboardNavigationLabel(element: OutlineEntry): { toString(): string | undefined } | { toString(): string | undefined }[] | undefined {
return element.label;
}
}
class NotebookOutlineVirtualDelegate implements IListVirtualDelegate<OutlineEntry> {
getHeight(_element: OutlineEntry): number {
return 22;
}
getTemplateId(_element: OutlineEntry): string {
return NotebookOutlineTemplate.templateId;
}
}
class NotebookQuickPickProvider implements IQuickPickDataSource<OutlineEntry> {
constructor(
private _getEntries: () => OutlineEntry[],
@IThemeService private readonly _themeService: IThemeService
) { }
getQuickPickElements(): IQuickPickOutlineElement<OutlineEntry>[] {
const bucket: OutlineEntry[] = [];
for (const entry of this._getEntries()) {
entry.asFlatList(bucket);
}
const result: IQuickPickOutlineElement<OutlineEntry>[] = [];
const { hasFileIcons } = this._themeService.getFileIconTheme();
for (const element of bucket) {
// todo@jrieken it is fishy that codicons cannot be used with iconClasses
// but file icons can...
result.push({
element,
label: hasFileIcons ? element.label : `$(${element.icon.id}) ${element.label}`,
ariaLabel: element.label,
iconClasses: hasFileIcons ? getIconClassesForLanguageId(element.cell.language ?? '') : undefined,
});
}
return result;
}
}
class NotebookComparator implements IOutlineComparator<OutlineEntry> {
private readonly _collator = new IdleValue<Intl.Collator>(() => new Intl.Collator(undefined, { numeric: true }));
compareByPosition(a: OutlineEntry, b: OutlineEntry): number {
return a.index - b.index;
}
compareByType(a: OutlineEntry, b: OutlineEntry): number {
return a.cell.cellKind - b.cell.cellKind || this._collator.value.compare(a.label, b.label);
}
compareByName(a: OutlineEntry, b: OutlineEntry): number {
return this._collator.value.compare(a.label, b.label);
}
}
export class NotebookCellOutline extends Disposable implements IOutline<OutlineEntry> {
private readonly _onDidChange = this._register(new Emitter<OutlineChangeEvent>());
readonly onDidChange: Event<OutlineChangeEvent> = this._onDidChange.event;
private _uri: URI | undefined;
private _entries: OutlineEntry[] = [];
private _activeEntry?: OutlineEntry;
private readonly _entriesDisposables = this._register(new DisposableStore());
readonly config: IOutlineListConfig<OutlineEntry>;
readonly outlineKind = 'notebookCells';
get activeElement(): OutlineEntry | undefined {
return this._activeEntry;
}
constructor(
private readonly _editor: NotebookEditor,
private readonly _target: OutlineTarget,
@IInstantiationService instantiationService: IInstantiationService,
@IThemeService themeService: IThemeService,
@IEditorService private readonly _editorService: IEditorService,
@IMarkerService private readonly _markerService: IMarkerService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@INotebookExecutionStateService private readonly _notebookExecutionStateService: INotebookExecutionStateService,
) {
super();
const selectionListener = this._register(new MutableDisposable());
const installSelectionListener = () => {
const notebookEditor = _editor.getControl();
if (!notebookEditor?.hasModel()) {
selectionListener.clear();
} else {
selectionListener.value = combinedDisposable(
notebookEditor.onDidChangeSelection(() => this._recomputeActive()),
notebookEditor.onDidChangeViewCells(() => this._recomputeState())
);
}
};
this._register(_editor.onDidChangeModel(() => {
this._recomputeState();
installSelectionListener();
}));
this._register(_configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('notebook.outline.showCodeCells')) {
this._recomputeState();
}
}));
this._register(themeService.onDidFileIconThemeChange(() => {
this._onDidChange.fire({});
}));
this._register(_notebookExecutionStateService.onDidChangeCellExecution(e => {
if (!!this._editor.textModel && e.affectsNotebook(this._editor.textModel?.uri)) {
this._recomputeState();
}
}));
this._recomputeState();
installSelectionListener();
const options: IWorkbenchDataTreeOptions<OutlineEntry, FuzzyScore> = {
collapseByDefault: _target === OutlineTarget.Breadcrumbs,
expandOnlyOnTwistieClick: true,
multipleSelectionSupport: false,
accessibilityProvider: new NotebookOutlineAccessibility(),
identityProvider: { getId: element => element.cell.id },
keyboardNavigationLabelProvider: new NotebookNavigationLabelProvider()
};
const treeDataSource: IDataSource<this, OutlineEntry> = { getChildren: parent => parent instanceof NotebookCellOutline ? this._entries : parent.children };
const delegate = new NotebookOutlineVirtualDelegate();
const renderers = [instantiationService.createInstance(NotebookOutlineRenderer)];
const comparator = new NotebookComparator();
this.config = {
breadcrumbsDataSource: {
getBreadcrumbElements: () => {
const result: OutlineEntry[] = [];
let candidate = this._activeEntry;
while (candidate) {
result.unshift(candidate);
candidate = candidate.parent;
}
return result;
}
},
quickPickDataSource: instantiationService.createInstance(NotebookQuickPickProvider, () => this._entries),
treeDataSource,
delegate,
renderers,
comparator,
options
};
}
private _recomputeState(): void {
this._entriesDisposables.clear();
this._activeEntry = undefined;
this._entries.length = 0;
this._uri = undefined;
const notebookEditorControl = this._editor.getControl();
if (!notebookEditorControl) {
return;
}
if (!notebookEditorControl.hasModel()) {
return;
}
this._uri = notebookEditorControl.textModel.uri;
const notebookEditorWidget: IActiveNotebookEditor = notebookEditorControl;
if (notebookEditorWidget.getLength() === 0) {
return;
}
let includeCodeCells = true;
if (this._target === OutlineTarget.OutlinePane) {
includeCodeCells = this._configurationService.getValue<boolean>('notebook.outline.showCodeCells');
} else if (this._target === OutlineTarget.Breadcrumbs) {
includeCodeCells = this._configurationService.getValue<boolean>('notebook.breadcrumbs.showCodeCells');
}
const focusedCellIndex = notebookEditorWidget.getFocus().start;
const focused = notebookEditorWidget.cellAt(focusedCellIndex)?.handle;
const entries: OutlineEntry[] = [];
for (let i = 0; i < notebookEditorWidget.getLength(); i++) {
const cell = notebookEditorWidget.cellAt(i);
const isMarkdown = cell.cellKind === CellKind.Markup;
if (!isMarkdown && !includeCodeCells) {
continue;
}
// cap the amount of characters that we look at and use the following logic
// - for MD prefer headings (each header is an entry)
// - otherwise use the first none-empty line of the cell (MD or code)
let content = this._getCellFirstNonEmptyLine(cell);
let hasHeader = false;
if (isMarkdown) {
const fullContent = cell.getText().substring(0, 10_000);
for (const token of marked.lexer(fullContent, { gfm: true })) {
if (token.type === 'heading') {
hasHeader = true;
entries.push(new OutlineEntry(entries.length, token.depth, cell, renderMarkdownAsPlaintext({ value: token.text }).trim(), false, false));
}
}
if (!hasHeader) {
content = renderMarkdownAsPlaintext({ value: content });
}
}
if (!hasHeader) {
let preview = content.trim();
if (preview.length === 0) {
// empty or just whitespace
preview = localize('empty', "empty cell");
}
const exeState = !isMarkdown && this._notebookExecutionStateService.getCellExecution(cell.uri);
entries.push(new OutlineEntry(entries.length, 7, cell, preview, !!exeState, exeState ? exeState.isPaused : false));
}
if (cell.handle === focused) {
this._activeEntry = entries[entries.length - 1];
}
// send an event whenever any of the cells change
this._entriesDisposables.add(cell.model.onDidChangeContent(() => {
this._recomputeState();
this._onDidChange.fire({});
}));
}
// build a tree from the list of entries
if (entries.length > 0) {
const result: OutlineEntry[] = [entries[0]];
const parentStack: OutlineEntry[] = [entries[0]];
for (let i = 1; i < entries.length; i++) {
const entry = entries[i];
while (true) {
const len = parentStack.length;
if (len === 0) {
// root node
result.push(entry);
parentStack.push(entry);
break;
} else {
const parentCandidate = parentStack[len - 1];
if (parentCandidate.level < entry.level) {
parentCandidate.addChild(entry);
parentStack.push(entry);
break;
} else {
parentStack.pop();
}
}
}
}
this._entries = result;
}
// feature: show markers with each cell
const markerServiceListener = new MutableDisposable();
this._entriesDisposables.add(markerServiceListener);
const updateMarkerUpdater = () => {
const doUpdateMarker = (clear: boolean) => {
for (const entry of this._entries) {
if (clear) {
entry.clearMarkers();
} else {
entry.updateMarkers(this._markerService);
}
}
};
if (this._configurationService.getValue(OutlineConfigKeys.problemsEnabled)) {
markerServiceListener.value = this._markerService.onMarkerChanged(e => {
if (e.some(uri => notebookEditorWidget.getCellsInRange().some(cell => isEqual(cell.uri, uri)))) {
doUpdateMarker(false);
this._onDidChange.fire({});
}
});
doUpdateMarker(false);
} else {
markerServiceListener.clear();
doUpdateMarker(true);
}
};
updateMarkerUpdater();
this._entriesDisposables.add(this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(OutlineConfigKeys.problemsEnabled)) {
updateMarkerUpdater();
this._onDidChange.fire({});
}
}));
this._onDidChange.fire({});
}
private _recomputeActive(): void {
let newActive: OutlineEntry | undefined;
const notebookEditorWidget = this._editor.getControl();
if (notebookEditorWidget) {
if (notebookEditorWidget.hasModel() && notebookEditorWidget.getLength() > 0) {
const cell = notebookEditorWidget.cellAt(notebookEditorWidget.getFocus().start);
if (cell) {
for (const entry of this._entries) {
newActive = entry.find(cell, []);
if (newActive) {
break;
}
}
}
}
}
if (newActive !== this._activeEntry) {
this._activeEntry = newActive;
this._onDidChange.fire({ affectOnlyActiveElement: true });
}
}
private _getCellFirstNonEmptyLine(cell: ICellViewModel) {
const textBuffer = cell.textBuffer;
for (let i = 0; i < textBuffer.getLineCount(); i++) {
const firstNonWhitespace = textBuffer.getLineFirstNonWhitespaceColumn(i + 1);
const lineLength = textBuffer.getLineLength(i + 1);
if (firstNonWhitespace < lineLength) {
return textBuffer.getLineContent(i + 1);
}
}
return cell.getText().substring(0, 10_000);
}
get isEmpty(): boolean {
return this._entries.length === 0;
}
get uri() {
return this._uri;
}
async reveal(entry: OutlineEntry, options: IEditorOptions, sideBySide: boolean): Promise<void> {
await this._editorService.openEditor({
resource: entry.cell.uri,
options: { ...options, override: this._editor.input?.editorId },
}, sideBySide ? SIDE_GROUP : undefined);
}
preview(entry: OutlineEntry): IDisposable {
const widget = this._editor.getControl();
if (!widget) {
return Disposable.None;
}
widget.revealInCenterIfOutsideViewport(entry.cell);
const ids = widget.deltaCellDecorations([], [{
handle: entry.cell.handle,
options: { className: 'nb-symbolHighlight', outputClassName: 'nb-symbolHighlight' }
}]);
return toDisposable(() => { widget.deltaCellDecorations(ids, []); });
}
captureViewState(): IDisposable {
const widget = this._editor.getControl();
const viewState = widget?.getEditorViewState();
return toDisposable(() => {
if (viewState) {
widget?.restoreListViewState(viewState);
}
});
}
}
class NotebookOutlineCreator implements IOutlineCreator<NotebookEditor, OutlineEntry> {
readonly dispose: () => void;
constructor(
@IOutlineService outlineService: IOutlineService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
const reg = outlineService.registerOutlineCreator(this);
this.dispose = () => reg.dispose();
}
matches(candidate: IEditorPane): candidate is NotebookEditor {
return candidate.getId() === NotebookEditor.ID;
}
async createOutline(editor: NotebookEditor, target: OutlineTarget): Promise<IOutline<OutlineEntry> | undefined> {
return this._instantiationService.createInstance(NotebookCellOutline, editor, target);
}
}
Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(NotebookOutlineCreator, LifecyclePhase.Eventually);
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({
id: 'notebook',
order: 100,
type: 'object',
'properties': {
'notebook.outline.showCodeCells': {
type: 'boolean',
default: false,
markdownDescription: localize('outline.showCodeCells', "When enabled notebook outline shows code cells.")
},
'notebook.breadcrumbs.showCodeCells': {
type: 'boolean',
default: true,
markdownDescription: localize('breadcrumbs.showCodeCells', "When enabled notebook breadcrumbs contain code cells.")
},
}
}); | the_stack |
import {log} from '../console/log';
const UNWALKABLE = -10;
const RANGE_MODIFIER = 1; // this parameter sets the scaling of weights to prefer walls closer protection bounds
const RANGE_PADDING = 3; // max range to reduce weighting; RANGE_MODIFIER * RANGE_PADDING must be < PROTECTED
const NORMAL = 0;
const PROTECTED = 10;
const CANNOT_BUILD = 20;
const EXIT = 30;
/**
* @property {number} capacity - The flow capacity of this edge
* @property {number} flow - The current flow of this edge
* @property {number} resEdge -
* @property {number} to - where this edge leads to
*/
export interface Edge {
capacity: number;
flow: number;
resEdge: number;
to: number;
}
/**
* @property {number} x1 - Top left corner
* @property {number} x1 - Top left corner
* @property {number} x2 - Bottom right corner
* @property {number} y2 - Bottom right corner
*/
export interface Rectangle {
x1: number;
y1: number;
x2: number;
y2: number;
}
export class Graph {
totalVertices: number;
level: number[];
edges: { [from: number]: Edge[] };
constructor(totalVertices: number) {
this.totalVertices = totalVertices;
this.level = Array(totalVertices);
// An array of edges for each vertex
this.edges = Array(totalVertices).fill(0).map((x) => []);
}
/**
* Create a new edge in the graph as well as a corresponding reverse edge on the residual graph
* @param from - vertex edge starts at
* @param to - vertex edge leads to
* @param capacity - max flow capacity for this edge
*/
newEdge(from: number, to: number, capacity: number) {
// Normal forward Edge
this.edges[from].push({to, resEdge: this.edges[to].length, capacity, flow: 0});
// reverse Edge for Residual Graph
this.edges[to].push({to: from, resEdge: this.edges[from].length - 1, capacity: 0, flow: 0});
}
/**
* Uses Breadth First Search to see if a path exists to the vertex 'to' and generate the level graph
* @param from - vertex to start from
* @param to - vertex to try and reach
*/
createLevelGraph(from: number, to: number) {
if (to >= this.totalVertices) {
return false;
}
this.level.fill(-1); // reset old levels
this.level[from] = 0;
const q = []; // queue with s as starting point
q.push(from);
let u = 0;
let edge = null;
while (q.length) {
u = q.shift()!;
for (edge of this.edges[u]) {
if (this.level[edge.to] < 0 && edge.flow < edge.capacity) {
this.level[edge.to] = this.level[u] + 1;
q.push(edge.to);
}
}
}
return this.level[to] >= 0; // return if theres a path, no level, no path!
}
/**
* Depth First Search-like: send flow at along path from from->to recursively while increasing the level of the
* visited vertices by one
* @param start - the vertex to start at
* @param end - the vertex to try and reach
* @param targetFlow - the amount of flow to try and achieve
* @param count - keep track of which vertices have been visited so we don't include them twice
*/
calcFlow(start: number, end: number, targetFlow: number, count: number[]) {
if (start === end) { // Sink reached , abort recursion
return targetFlow;
}
let edge: Edge;
let flowTillHere = 0;
let flowToT = 0;
while (count[start] < this.edges[start].length) { // Visit all edges of the vertex one after the other
edge = this.edges[start][count[start]];
if (this.level[edge.to] === this.level[start] + 1 && edge.flow < edge.capacity) {
// Edge leads to Vertex with a level one higher, and has flow left
flowTillHere = Math.min(targetFlow, edge.capacity - edge.flow);
flowToT = this.calcFlow(edge.to, end, flowTillHere, count);
if (flowToT > 0) {
edge.flow += flowToT; // Add Flow to current edge
// subtract from reverse Edge -> Residual Graph neg. Flow to use backward direction of BFS/DFS
this.edges[edge.to][edge.resEdge].flow -= flowToT;
return flowToT;
}
}
count[start]++;
}
return 0;
}
/**
* Uses Breadth First Search to find the vertices in the minCut for the graph
* - Must call calcMinCut first to prepare the graph
* @param from - the vertex to start from
*/
getMinCut(from: number) {
const eInCut = [];
this.level.fill(-1);
this.level[from] = 1;
const q = [];
q.push(from);
let u = 0;
let edge: Edge;
while (q.length) {
u = q.shift()!;
for (edge of this.edges[u]) {
if (edge.flow < edge.capacity) {
if (this.level[edge.to] < 1) {
this.level[edge.to] = 1;
q.push(edge.to);
}
}
if (edge.flow === edge.capacity && edge.capacity > 0) { // blocking edge -> could be in min cut
eInCut.push({to: edge.to, unreachable: u});
}
}
}
const minCut = [];
let cutEdge: { to: number, unreachable: number };
for (cutEdge of eInCut) {
if (this.level[cutEdge.to] === -1) {
// Only edges which are blocking and lead to the sink from unreachable vertices are in the min cut
minCut.push(cutEdge.unreachable);
}
}
return minCut;
}
/**
* Calculates min-cut graph using Dinic's Algorithm.
* use getMinCut to get the actual verticies in the minCut
* @param source - Source vertex
* @param sink - Sink vertex
*/
calcMinCut(source: number, sink: number) {
if (source === sink) {
return -1;
}
let ret = 0;
let count = [];
let flow = 0;
while (this.createLevelGraph(source, sink)) {
count = Array(this.totalVertices + 1).fill(0);
do {
flow = this.calcFlow(source, sink, Number.MAX_VALUE, count);
if (flow > 0) {
ret += flow;
}
} while (flow);
}
return ret;
}
}
/**
* An Array with Terrain information: -1 not usable, 2 Sink (Leads to Exit)
* @param room - the room to generate the terrain map from
*/
export function get2DArray(roomName: string, bounds: Rectangle = {x1: 0, y1: 0, x2: 49, y2: 49}) {
const room2D = Array(50).fill(NORMAL).map((d) => Array(50).fill(NORMAL)); // Array for room tiles
let x: number;
let y: number;
const terrain = Game.map.getRoomTerrain(roomName);
for (x = bounds.x1; x <= bounds.x2; x++) {
for (y = bounds.y1; y <= bounds.y2; y++) {
if (terrain.get(x, y) === TERRAIN_MASK_WALL) {
room2D[x][y] = UNWALKABLE; // Mark unwalkable
} else if (x === bounds.x1 || y === bounds.y1 || x === bounds.x2 || y === bounds.y2) {
room2D[x][y] = EXIT; // Mark exit tiles
}
}
}
// Marks tiles as unbuildable if they are proximate to exits
for (y = bounds.y1 + 1; y <= bounds.y2 - 1; y++) {
if (room2D[bounds.x1][y] === EXIT) {
for (const dy of [-1, 0, 1]) {
if (room2D[bounds.x1 + 1][y + dy] !== UNWALKABLE) {
room2D[bounds.x1 + 1][y + dy] = CANNOT_BUILD;
}
}
}
if (room2D[bounds.x2][y] === EXIT) {
for (const dy of [-1, 0, 1]) {
if (room2D[bounds.x2 - 1][y + dy] !== UNWALKABLE) {
room2D[bounds.x2 - 1][y + dy] = CANNOT_BUILD;
}
}
}
}
for (x = bounds.x1 + 1; x <= bounds.x2 - 1; x++) {
if (room2D[x][bounds.y1] === EXIT) {
for (const dx of [-1, 0, 1]) {
if (room2D[x + dx][bounds.y1 + 1] !== UNWALKABLE) {
room2D[x + dx][bounds.y1 + 1] = CANNOT_BUILD;
}
}
}
if (room2D[x][bounds.y2] === EXIT) {
for (const dx of [-1, 0, 1]) {
if (room2D[x + dx][bounds.y2 - 1] !== UNWALKABLE) {
room2D[x + dx][bounds.y2 - 1] = CANNOT_BUILD;
}
}
}
}
return room2D;
}
/**
* Function to create Source, Sink, Tiles arrays: takes a rectangle-Array as input for Tiles that are to Protect
* @param room - the room to consider
* @param toProtect - the coordinates to protect inside the walls
* @param bounds - the area to consider for the minCut
*/
export function createGraph(roomName: string, toProtect: Rectangle[],
preferCloserBarriers = true,
preferCloserBarrierLimit = Infinity, // ignore the toProtect[n] for n > this value
visualize = true,
bounds: Rectangle = {x1: 0, y1: 0, x2: 49, y2: 49}) {
const visual = new RoomVisual(roomName);
const roomArray = get2DArray(roomName, bounds);
// For all Rectangles, set edges as source (to protect area) and area as unused
let r: Rectangle;
let x: number;
let y: number;
for (r of toProtect) {
if (bounds.x1 >= bounds.x2 || bounds.y1 >= bounds.y2 ||
bounds.x1 < 0 || bounds.y1 < 0 || bounds.x2 > 49 || bounds.y2 > 49) {
return console.log('ERROR: Invalid bounds', JSON.stringify(bounds));
} else if (r.x1 >= r.x2 || r.y1 >= r.y2) {
return console.log('ERROR: Rectangle', JSON.stringify(r), 'invalid.');
} else if (r.x1 < bounds.x1 || r.x2 > bounds.x2 || r.y1 < bounds.y1 || r.y2 > bounds.y2) {
return console.log('ERROR: Rectangle', JSON.stringify(r), 'out of bounds:', JSON.stringify(bounds));
}
for (x = r.x1; x <= r.x2; x++) {
for (y = r.y1; y <= r.y2; y++) {
if (x === r.x1 || x === r.x2 || y === r.y1 || y === r.y2) {
if (roomArray[x][y] === NORMAL) {
roomArray[x][y] = PROTECTED;
}
} else {
roomArray[x][y] = UNWALKABLE;
}
}
}
}
// Preferentially weight closer tiles
if (preferCloserBarriers) {
for (r of _.take(toProtect, preferCloserBarrierLimit)) {
const [xmin, xmax] = [Math.max(r.x1 - RANGE_PADDING, 0), Math.min(r.x2 + RANGE_PADDING, 49)];
const [ymin, ymax] = [Math.max(r.y1 - RANGE_PADDING, 0), Math.min(r.y2 + RANGE_PADDING, 49)];
for (x = xmin; x <= xmax; x++) {
for (y = ymin; y <= ymax; y++) {
if (roomArray[x][y] >= NORMAL && roomArray[x][y] < PROTECTED) {
const x1range = Math.max(r.x1 - x, 0);
const x2range = Math.max(x - r.x2, 0);
const y1range = Math.max(r.y1 - y, 0);
const y2range = Math.max(y - r.y2, 0);
const rangeToBorder = Math.max(x1range, x2range, y1range, y2range);
const modifiedWeight = NORMAL + RANGE_MODIFIER * (RANGE_PADDING - rangeToBorder);
roomArray[x][y] = Math.max(roomArray[x][y], modifiedWeight);
if (visualize) {
visual.text(`${roomArray[x][y]}`, x, y);
}
}
}
}
}
}
// ********************** Visualization
if (visualize) {
for (x = bounds.x1; x <= bounds.x2; x++) {
for (y = bounds.y1; y <= bounds.y2; y++) {
if (roomArray[x][y] === UNWALKABLE) {
visual.circle(x, y, {radius: 0.5, fill: '#1b1b9f', opacity: 0.3});
} else if (roomArray[x][y] > UNWALKABLE && roomArray[x][y] < NORMAL) {
visual.circle(x, y, {radius: 0.5, fill: '#42cce8', opacity: 0.3});
} else if (roomArray[x][y] === NORMAL) {
visual.circle(x, y, {radius: 0.5, fill: '#bdb8b8', opacity: 0.3});
} else if (roomArray[x][y] > NORMAL && roomArray[x][y] < PROTECTED) {
visual.circle(x, y, {radius: 0.5, fill: '#9929e8', opacity: 0.3});
} else if (roomArray[x][y] === PROTECTED) {
visual.circle(x, y, {radius: 0.5, fill: '#e800c6', opacity: 0.3});
} else if (roomArray[x][y] === CANNOT_BUILD) {
visual.circle(x, y, {radius: 0.5, fill: '#e8000f', opacity: 0.3});
} else if (roomArray[x][y] === EXIT) {
visual.circle(x, y, {radius: 0.5, fill: '#000000', opacity: 0.3});
}
}
}
}
// initialise graph
// possible 2*50*50 +2 (st) Vertices (Walls etc set to unused later)
const g = new Graph(2 * 50 * 50 + 2);
const infini = Number.MAX_VALUE;
const surr = [[0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1]];
// per Tile (0 in Array) top + bot with edge of c=1 from top to bott (use every tile once!)
// infini edge from bot to top vertices of adjacent tiles if they not protected (array =1)
// (no reverse edges in normal graph)
// per prot. Tile (1 in array) Edge from source to this tile with infini cap.
// per exit Tile (2in array) Edge to sink with infini cap.
// source is at pos 2*50*50, sink at 2*50*50+1 as first tile is 0,0 => pos 0
// top vertices <-> x,y : v=y*50+x and x= v % 50 y=v/50 (math.floor?)
// bot vertices <-> top + 2500
const source = 2 * 50 * 50;
const sink = 2 * 50 * 50 + 1;
let top = 0;
let bot = 0;
let dx = 0;
let dy = 0;
// max = 49;
const baseCapacity = 10;
const modifyWeight = preferCloserBarriers ? 1 : 0;
for (x = bounds.x1 + 1; x < bounds.x2; x++) {
for (y = bounds.y1 + 1; y < bounds.y2; y++) {
top = y * 50 + x;
bot = top + 2500;
if (roomArray[x][y] >= NORMAL && roomArray[x][y] <= PROTECTED) {
if (roomArray[x][y] >= NORMAL && roomArray[x][y] < PROTECTED) {
g.newEdge(top, bot, baseCapacity - modifyWeight * roomArray[x][y]); // add surplus weighting
} else if (roomArray[x][y] === PROTECTED) { // connect this to the source
g.newEdge(source, top, infini);
g.newEdge(top, bot, baseCapacity - modifyWeight * RANGE_PADDING * RANGE_MODIFIER);
}
for (let i = 0; i < 8; i++) { // attach adjacent edges
dx = x + surr[i][0];
dy = y + surr[i][1];
if ((roomArray[dx][dy] >= NORMAL && roomArray[dx][dy] < PROTECTED)
|| roomArray[dx][dy] === CANNOT_BUILD) {
g.newEdge(bot, dy * 50 + dx, infini);
}
}
} else if (roomArray[x][y] === CANNOT_BUILD) { // near Exit
g.newEdge(top, sink, infini);
}
}
} // graph finished
return g;
}
/**
* Main function to be called by user: calculate min cut tiles from room using rectangles as protected areas
* @param room - the room to use
* @param rectangles - the areas to protect, defined as rectangles
* @param bounds - the area to be considered for the minCut
*/
export function getCutTiles(roomName: string, toProtect: Rectangle[],
preferCloserBarriers = true,
preferCloserBarrierLimit = Infinity,
visualize = true,
bounds: Rectangle = {x1: 0, y1: 0, x2: 49, y2: 49}): Coord[] {
const graph = createGraph(roomName, toProtect, preferCloserBarriers, preferCloserBarrierLimit, visualize, bounds);
if (!graph) {
return [];
}
let x: number;
let y: number;
const source = 2 * 50 * 50; // Position Source / Sink in Room-Graph
const sink = 2 * 50 * 50 + 1;
const count = graph.calcMinCut(source, sink);
// console.log('Number of Tiles in Cut:', count);
const positions = [];
if (count > 0) {
const cutVertices = graph.getMinCut(source);
let v: number;
for (v of cutVertices) {
// x= vertex % 50 y=v/50 (math.floor?)
x = v % 50;
y = Math.floor(v / 50);
positions.push({x, y});
}
}
// Visualise Result
if (positions.length > 0) {
const visual = new RoomVisual(roomName);
for (let i = positions.length - 1; i >= 0; i--) {
visual.circle(positions[i].x, positions[i].y, {radius: 0.5, fill: '#ff7722', opacity: 0.9});
}
} else {
return [];
}
const wholeRoom = bounds.x1 === 0 && bounds.y1 === 0 && bounds.x2 === 49 && bounds.y2 === 49;
return wholeRoom ? positions : pruneDeadEnds(roomName, positions);
}
/**
* Removes unnecessary tiles if they are blocking the path to a dead end
* Useful if minCut has been run on a subset of the room
* @param roomName - Room to work in
* @param cutTiles - Array of tiles which are in the minCut
*/
export function pruneDeadEnds(roomName: string, cutTiles: Coord[]) {
// Get Terrain and set all cut-tiles as unwalkable
const roomArray = get2DArray(roomName);
let tile: Coord;
for (tile of cutTiles) {
roomArray[tile.x][tile.y] = UNWALKABLE;
}
// Floodfill from exits: save exit tiles in array and do a BFS-like search
const unvisited: number[] = [];
let y: number;
let x: number;
for (y = 0; y < 49; y++) {
if (roomArray[0][y] === EXIT) {
console.log('prune: toExit', 0, y);
unvisited.push(50 * y);
}
if (roomArray[49][y] === EXIT) {
console.log('prune: toExit', 49, y);
unvisited.push(50 * y + 49);
}
}
for (x = 0; x < 49; x++) {
if (roomArray[x][0] === EXIT) {
console.log('prune: toExit', x, 0);
unvisited.push(x);
}
if (roomArray[x][49] === EXIT) {
console.log('prune: toExit', x, 49);
unvisited.push(2450 + x); // 50*49=2450
}
}
// Iterate over all unvisited EXIT tiles and mark neigbours as EXIT tiles if walkable, add to unvisited
const surr = [[0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1]];
let currPos: number;
let dx: number;
let dy: number;
while (unvisited.length > 0) {
currPos = unvisited.pop()!;
x = currPos % 50;
y = Math.floor(currPos / 50);
for (let i = 0; i < 8; i++) {
dx = x + surr[i][0];
dy = y + surr[i][1];
if (dx < 0 || dx > 49 || dy < 0 || dy > 49) {
continue;
}
if ((roomArray[dx][dy] >= NORMAL && roomArray[dx][dy] < PROTECTED)
|| roomArray[dx][dy] === CANNOT_BUILD) {
unvisited.push(50 * dy + dx);
roomArray[dx][dy] = EXIT;
}
}
}
// Remove min-Cut-Tile if there is no EXIT reachable by it
let leadsToExit: boolean;
const validCut: Coord[] = [];
for (tile of cutTiles) {
leadsToExit = false;
for (let j = 0; j < 8; j++) {
dx = tile.x + surr[j][0];
dy = tile.y + surr[j][1];
if (roomArray[dx][dy] === EXIT) {
leadsToExit = true;
}
}
if (leadsToExit) {
validCut.push(tile);
}
}
return validCut;
}
/**
* Example function: demonstrates how to get a min cut with 2 rectangles, which define a "to protect" area
* @param roomName - the name of the room to use for the test, must be visible
*/
export function testMinCut(colonyName: string, preferCloserBarriers = true) {
const colony = Overmind.colonies[colonyName];
if (!colony) {
return `No colony: ${colonyName}`;
}
let cpu = Game.cpu.getUsed();
// Rectangle Array, the Rectangles will be protected by the returned tiles
const rectArray = [];
const padding = 3;
if (colony.hatchery) {
const {x, y} = colony.hatchery.pos;
const [x1, y1] = [Math.max(x - 5 - padding, 0), Math.max(y - 4 - padding, 0)];
const [x2, y2] = [Math.min(x + 5 + padding, 49), Math.min(y + 6 + padding, 49)];
rectArray.push({x1: x1, y1: y1, x2: x2, y2: y2});
}
if (colony.commandCenter) {
const {x, y} = colony.commandCenter.pos;
const [x1, y1] = [Math.max(x - 3 - padding, 0), Math.max(y - 0 - padding, 0)];
const [x2, y2] = [Math.min(x + 0 + padding, 49), Math.min(y + 5 + padding, 49)];
rectArray.push({x1: x1, y1: y1, x2: x2, y2: y2});
}
if (colony.upgradeSite) {
const {x, y} = colony.upgradeSite.pos;
const [x1, y1] = [Math.max(x - 1, 0), Math.max(y - 1, 0)];
const [x2, y2] = [Math.min(x + 1, 49), Math.min(y + 1, 49)];
rectArray.push({x1: x1, y1: y1, x2: x2, y2: y2});
}
// Get Min cut
// Positions is an array where to build walls/ramparts
const positions = getCutTiles(colonyName, rectArray, preferCloserBarriers, 2);
// Test output
// console.log('Positions returned', positions.length);
cpu = Game.cpu.getUsed() - cpu;
// console.log('Needed', cpu, ' cpu time');
log.info(`preferCloserBarriers = ${preferCloserBarriers}; positions returned: ${positions.length};` +
` CPU time: ${cpu}`);
return 'Finished';
}
/**
* Example function: demonstrates how to get a min cut with 2 rectangles, which define a "to protect" area
* while considering a subset of the larger room.
* @param roomName - the name of the room to use for the test, must be visible
*/
export function testMinCutSubset(colonyName: string) {
const colony = Overmind.colonies[colonyName];
if (!colony) {
return `No colony: ${colonyName}`;
}
let cpu = Game.cpu.getUsed();
// Rectangle Array, the Rectangles will be protected by the returned tiles
const rectArray = [];
const padding = 3;
if (colony.hatchery) {
const {x, y} = colony.hatchery.pos;
rectArray.push({x1: x - 5 - padding, y1: y - 4 - padding, x2: x + 5 + padding, y2: y + 6 + padding});
}
if (colony.commandCenter) {
const {x, y} = colony.commandCenter.pos;
rectArray.push({x1: x - 3 - padding, y1: y - 0 - padding, x2: x + 0 + padding, y2: y + 5 + padding});
}
// Get Min cut, returns the positions where ramparts/walls need to be
const positions = getCutTiles(colonyName, rectArray, true, Infinity, true,
{x1: 5, y1: 5, x2: 44, y2: 44});
// Test output
console.log('Positions returned', positions.length);
cpu = Game.cpu.getUsed() - cpu;
console.log('Needed', cpu, ' cpu time');
return 'Finished';
} | the_stack |
import { FocusTrap, FocusTrapFactory } from '@angular/cdk/a11y';
import { Direction, Directionality } from '@angular/cdk/bidi';
import { ESCAPE } from '@angular/cdk/keycodes';
import { Overlay, OverlayConfig, OverlayKeyboardDispatcher, OverlayRef } from '@angular/cdk/overlay';
import { CdkPortalOutlet, ComponentPortal, TemplatePortal } from '@angular/cdk/portal';
import { DOCUMENT } from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
EventEmitter,
Inject,
Injector,
Input,
OnChanges,
OnDestroy,
OnInit,
Optional,
Output,
Renderer2,
SimpleChanges,
TemplateRef,
Type,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { NzConfigKey, NzConfigService, WithConfig } from 'ng-zorro-antd/core/config';
import { BooleanInput, NgStyleInterface, NzSafeAny } from 'ng-zorro-antd/core/types';
import { InputBoolean, toCssPixel } from 'ng-zorro-antd/core/util';
import { NzDrawerContentDirective } from './drawer-content.directive';
import { NzDrawerOptionsOfComponent, NzDrawerPlacement } from './drawer-options';
import { NzDrawerRef } from './drawer-ref';
export const DRAWER_ANIMATE_DURATION = 300;
const NZ_CONFIG_MODULE_NAME: NzConfigKey = 'drawer';
@Component({
selector: 'nz-drawer',
exportAs: 'nzDrawer',
template: `
<ng-template #drawerTemplate>
<div
class="ant-drawer"
[nzNoAnimation]="nzNoAnimation"
[class.ant-drawer-rtl]="dir === 'rtl'"
[class.ant-drawer-open]="isOpen"
[class.no-mask]="!nzMask"
[class.ant-drawer-top]="nzPlacement === 'top'"
[class.ant-drawer-bottom]="nzPlacement === 'bottom'"
[class.ant-drawer-right]="nzPlacement === 'right'"
[class.ant-drawer-left]="nzPlacement === 'left'"
[style.transform]="offsetTransform"
[style.transition]="placementChanging ? 'none' : null"
[style.zIndex]="nzZIndex"
>
<div class="ant-drawer-mask" (click)="maskClick()" *ngIf="nzMask" [ngStyle]="nzMaskStyle"></div>
<div
class="ant-drawer-content-wrapper {{ nzWrapClassName }}"
[style.width]="width"
[style.height]="height"
[style.transform]="transform"
[style.transition]="placementChanging ? 'none' : null"
>
<div class="ant-drawer-content">
<div class="ant-drawer-wrapper-body" [style.height]="isLeftOrRight ? '100%' : null">
<div
*ngIf="nzTitle || nzClosable"
[class.ant-drawer-header]="!!nzTitle"
[class.ant-drawer-header-no-title]="!nzTitle"
>
<div *ngIf="nzTitle" class="ant-drawer-title">
<ng-container *nzStringTemplateOutlet="nzTitle">
<div [innerHTML]="nzTitle"></div>
</ng-container>
</div>
<button
*ngIf="nzClosable"
(click)="closeClick()"
aria-label="Close"
class="ant-drawer-close"
style="--scroll-bar: 0px;"
>
<ng-container *nzStringTemplateOutlet="nzCloseIcon; let closeIcon">
<i nz-icon [nzType]="closeIcon"></i>
</ng-container>
</button>
</div>
<div class="ant-drawer-body" [ngStyle]="nzBodyStyle">
<ng-template cdkPortalOutlet></ng-template>
<ng-container *ngIf="nzContent; else contentElseTemp">
<ng-container *ngIf="isTemplateRef(nzContent)">
<ng-container *ngTemplateOutlet="$any(nzContent); context: templateContext"></ng-container>
</ng-container>
</ng-container>
<ng-template #contentElseTemp>
<ng-container *ngIf="contentFromContentChild && (isOpen || inAnimation)">
<ng-template [ngTemplateOutlet]="contentFromContentChild"></ng-template>
</ng-container>
</ng-template>
</div>
<div *ngIf="nzFooter" class="ant-drawer-footer">
<ng-container *nzStringTemplateOutlet="nzFooter">
<div [innerHTML]="nzFooter"></div>
</ng-container>
</div>
</div>
</div>
</div>
</div>
</ng-template>
`,
preserveWhitespaces: false,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NzDrawerComponent<T = NzSafeAny, R = NzSafeAny, D = NzSafeAny>
extends NzDrawerRef<T, R>
implements OnInit, OnDestroy, AfterViewInit, OnChanges, NzDrawerOptionsOfComponent
{
readonly _nzModuleName: NzConfigKey = NZ_CONFIG_MODULE_NAME;
static ngAcceptInputType_nzClosable: BooleanInput;
static ngAcceptInputType_nzMaskClosable: BooleanInput;
static ngAcceptInputType_nzMask: BooleanInput;
static ngAcceptInputType_nzNoAnimation: BooleanInput;
static ngAcceptInputType_nzKeyboard: BooleanInput;
static ngAcceptInputType_nzCloseOnNavigation: BooleanInput;
@Input() nzContent!: TemplateRef<{ $implicit: D; drawerRef: NzDrawerRef<R> }> | Type<T>;
@Input() nzCloseIcon: string | TemplateRef<void> = 'close';
@Input() @InputBoolean() nzClosable: boolean = true;
@Input() @WithConfig() @InputBoolean() nzMaskClosable: boolean = true;
@Input() @WithConfig() @InputBoolean() nzMask: boolean = true;
@Input() @WithConfig() @InputBoolean() nzCloseOnNavigation: boolean = true;
@Input() @InputBoolean() nzNoAnimation = false;
@Input() @InputBoolean() nzKeyboard: boolean = true;
@Input() nzTitle?: string | TemplateRef<{}>;
@Input() nzFooter?: string | TemplateRef<{}>;
@Input() nzPlacement: NzDrawerPlacement = 'right';
@Input() nzMaskStyle: NgStyleInterface = {};
@Input() nzBodyStyle: NgStyleInterface = {};
@Input() nzWrapClassName?: string;
@Input() nzWidth: number | string = 256;
@Input() nzHeight: number | string = 256;
@Input() nzZIndex = 1000;
@Input() nzOffsetX = 0;
@Input() nzOffsetY = 0;
private componentInstance: T | null = null;
@Input()
set nzVisible(value: boolean) {
this.isOpen = value;
}
get nzVisible(): boolean {
return this.isOpen;
}
@Output() readonly nzOnViewInit = new EventEmitter<void>();
@Output() readonly nzOnClose = new EventEmitter<MouseEvent>();
@Output() readonly nzVisibleChange = new EventEmitter<boolean>();
@ViewChild('drawerTemplate', { static: true }) drawerTemplate!: TemplateRef<void>;
@ViewChild(CdkPortalOutlet, { static: false }) bodyPortalOutlet?: CdkPortalOutlet;
@ContentChild(NzDrawerContentDirective, { static: true, read: TemplateRef })
contentFromContentChild?: TemplateRef<NzSafeAny>;
private destroy$ = new Subject<void>();
previouslyFocusedElement?: HTMLElement;
placementChanging = false;
placementChangeTimeoutId = -1;
nzContentParams?: D; // only service
overlayRef?: OverlayRef | null;
portal?: TemplatePortal;
focusTrap?: FocusTrap;
isOpen = false;
inAnimation = false;
templateContext: { $implicit: D | undefined; drawerRef: NzDrawerRef<R> } = {
$implicit: undefined,
drawerRef: this as NzDrawerRef<R>
};
get offsetTransform(): string | null {
if (!this.isOpen || this.nzOffsetX + this.nzOffsetY === 0) {
return null;
}
switch (this.nzPlacement) {
case 'left':
return `translateX(${this.nzOffsetX}px)`;
case 'right':
return `translateX(-${this.nzOffsetX}px)`;
case 'top':
return `translateY(${this.nzOffsetY}px)`;
case 'bottom':
return `translateY(-${this.nzOffsetY}px)`;
}
}
get transform(): string | null {
if (this.isOpen) {
return null;
}
switch (this.nzPlacement) {
case 'left':
return `translateX(-100%)`;
case 'right':
return `translateX(100%)`;
case 'top':
return `translateY(-100%)`;
case 'bottom':
return `translateY(100%)`;
}
}
get width(): string | null {
return this.isLeftOrRight ? toCssPixel(this.nzWidth) : null;
}
get height(): string | null {
return !this.isLeftOrRight ? toCssPixel(this.nzHeight) : null;
}
get isLeftOrRight(): boolean {
return this.nzPlacement === 'left' || this.nzPlacement === 'right';
}
nzAfterOpen = new Subject<void>();
nzAfterClose = new Subject<R>();
get afterOpen(): Observable<void> {
return this.nzAfterOpen.asObservable();
}
get afterClose(): Observable<R> {
return this.nzAfterClose.asObservable();
}
isTemplateRef(value: {}): boolean {
return value instanceof TemplateRef;
}
// from service config
@WithConfig() nzDirection?: Direction = undefined;
dir: Direction = 'ltr';
constructor(
private cdr: ChangeDetectorRef,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@Optional() @Inject(DOCUMENT) private document: NzSafeAny,
public nzConfigService: NzConfigService,
private renderer: Renderer2,
private overlay: Overlay,
private injector: Injector,
private changeDetectorRef: ChangeDetectorRef,
private focusTrapFactory: FocusTrapFactory,
private viewContainerRef: ViewContainerRef,
private overlayKeyboardDispatcher: OverlayKeyboardDispatcher,
@Optional() private directionality: Directionality
) {
super();
}
ngOnInit(): void {
this.directionality.change?.pipe(takeUntil(this.destroy$)).subscribe((direction: Direction) => {
this.dir = direction;
this.cdr.detectChanges();
});
this.dir = this.nzDirection || this.directionality.value;
this.attachOverlay();
this.updateOverlayStyle();
this.updateBodyOverflow();
this.templateContext = { $implicit: this.nzContentParams, drawerRef: this as NzDrawerRef<R> };
this.changeDetectorRef.detectChanges();
}
ngAfterViewInit(): void {
this.attachBodyContent();
// The `setTimeout` triggers change detection. There's no sense to schedule the DOM timer if anyone is
// listening to the `nzOnViewInit` event inside the template, for instance `<nz-drawer (nzOnViewInit)="...">`.
if (this.nzOnViewInit.observers.length) {
setTimeout(() => {
this.nzOnViewInit.emit();
});
}
}
ngOnChanges(changes: SimpleChanges): void {
const { nzPlacement, nzVisible } = changes;
if (nzVisible) {
const value = changes.nzVisible.currentValue;
if (value) {
this.open();
} else {
this.close();
}
}
if (nzPlacement && !nzPlacement.isFirstChange()) {
this.triggerPlacementChangeCycleOnce();
}
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
clearTimeout(this.placementChangeTimeoutId);
this.disposeOverlay();
}
private getAnimationDuration(): number {
return this.nzNoAnimation ? 0 : DRAWER_ANIMATE_DURATION;
}
// Disable the transition animation temporarily when the placement changing
private triggerPlacementChangeCycleOnce(): void {
if (!this.nzNoAnimation) {
this.placementChanging = true;
this.changeDetectorRef.markForCheck();
clearTimeout(this.placementChangeTimeoutId);
this.placementChangeTimeoutId = setTimeout(() => {
this.placementChanging = false;
this.changeDetectorRef.markForCheck();
}, this.getAnimationDuration());
}
}
close(result?: R): void {
this.isOpen = false;
this.inAnimation = true;
this.nzVisibleChange.emit(false);
this.updateOverlayStyle();
this.overlayKeyboardDispatcher.remove(this.overlayRef!);
this.changeDetectorRef.detectChanges();
setTimeout(() => {
this.updateBodyOverflow();
this.restoreFocus();
this.inAnimation = false;
this.nzAfterClose.next(result);
this.nzAfterClose.complete();
this.componentInstance = null;
}, this.getAnimationDuration());
}
open(): void {
this.attachOverlay();
this.isOpen = true;
this.inAnimation = true;
this.nzVisibleChange.emit(true);
this.overlayKeyboardDispatcher.add(this.overlayRef!);
this.updateOverlayStyle();
this.updateBodyOverflow();
this.savePreviouslyFocusedElement();
this.trapFocus();
this.changeDetectorRef.detectChanges();
setTimeout(() => {
this.inAnimation = false;
this.changeDetectorRef.detectChanges();
this.nzAfterOpen.next();
}, this.getAnimationDuration());
}
getContentComponent(): T | null {
return this.componentInstance;
}
closeClick(): void {
this.nzOnClose.emit();
}
maskClick(): void {
if (this.nzMaskClosable && this.nzMask) {
this.nzOnClose.emit();
}
}
private attachBodyContent(): void {
this.bodyPortalOutlet!.dispose();
if (this.nzContent instanceof Type) {
const childInjector = Injector.create({
parent: this.injector,
providers: [{ provide: NzDrawerRef, useValue: this }]
});
const componentPortal = new ComponentPortal<T>(this.nzContent, null, childInjector);
const componentRef = this.bodyPortalOutlet!.attachComponentPortal(componentPortal);
this.componentInstance = componentRef.instance;
Object.assign(componentRef.instance, this.nzContentParams);
componentRef.changeDetectorRef.detectChanges();
}
}
private attachOverlay(): void {
if (!this.overlayRef) {
this.portal = new TemplatePortal(this.drawerTemplate, this.viewContainerRef);
this.overlayRef = this.overlay.create(this.getOverlayConfig());
}
if (this.overlayRef && !this.overlayRef.hasAttached()) {
this.overlayRef.attach(this.portal);
this.overlayRef!.keydownEvents()
.pipe(takeUntil(this.destroy$))
.subscribe((event: KeyboardEvent) => {
if (event.keyCode === ESCAPE && this.isOpen && this.nzKeyboard) {
this.nzOnClose.emit();
}
});
this.overlayRef
.detachments()
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.disposeOverlay();
});
}
}
private disposeOverlay(): void {
this.overlayRef?.dispose();
this.overlayRef = null;
}
private getOverlayConfig(): OverlayConfig {
return new OverlayConfig({
disposeOnNavigation: this.nzCloseOnNavigation,
positionStrategy: this.overlay.position().global(),
scrollStrategy: this.overlay.scrollStrategies.block()
});
}
private updateOverlayStyle(): void {
if (this.overlayRef && this.overlayRef.overlayElement) {
this.renderer.setStyle(this.overlayRef.overlayElement, 'pointer-events', this.isOpen ? 'auto' : 'none');
}
}
private updateBodyOverflow(): void {
if (this.overlayRef) {
if (this.isOpen) {
this.overlayRef.getConfig().scrollStrategy!.enable();
} else {
this.overlayRef.getConfig().scrollStrategy!.disable();
}
}
}
savePreviouslyFocusedElement(): void {
if (this.document && !this.previouslyFocusedElement) {
this.previouslyFocusedElement = this.document.activeElement as HTMLElement;
// We need the extra check, because IE's svg element has no blur method.
if (this.previouslyFocusedElement && typeof this.previouslyFocusedElement.blur === 'function') {
this.previouslyFocusedElement.blur();
}
}
}
private trapFocus(): void {
if (!this.focusTrap && this.overlayRef && this.overlayRef.overlayElement) {
this.focusTrap = this.focusTrapFactory.create(this.overlayRef!.overlayElement);
this.focusTrap.focusInitialElement();
}
}
private restoreFocus(): void {
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (this.previouslyFocusedElement && typeof this.previouslyFocusedElement.focus === 'function') {
this.previouslyFocusedElement.focus();
}
if (this.focusTrap) {
this.focusTrap.destroy();
}
}
} | the_stack |
import {TSNE} from './bh_tsne';
import * as knn from './knn';
import * as scatterPlot from './scatterPlot';
import {shuffle, getSearchPredicate, runAsyncTask} from './util';
import * as logging from './logging';
import * as vector from './vector';
import {SpriteMetadata} from './data-provider';
export type DistanceFunction = (a: number[], b: number[]) => number;
export type PointAccessor = (index: number) => number;
export type PointAccessors3D = [PointAccessor, PointAccessor, PointAccessor];
export interface PointMetadata {
[key: string]: number | string;
}
export interface DataProto {
shape: [number, number];
tensor: number[];
metadata: {
columns: Array<{
name: string;
stringValues: string[];
numericValues: number[];
}>;
};
}
/** Statistics for a metadata column. */
export interface ColumnStats {
name: string;
isNumeric: boolean;
tooManyUniqueValues: boolean;
uniqueEntries?: Array<{label: string, count: number}>;
min: number;
max: number;
}
export interface SpriteAndMetadataInfo {
stats?: ColumnStats[];
pointsInfo?: PointMetadata[];
spriteImage?: HTMLImageElement;
spriteMetadata?: SpriteMetadata;
}
export interface DataPoint extends scatterPlot.DataPoint {
/** The point in the original space. */
vector: Float32Array;
/*
* Metadata for each point. Each metadata is a set of key/value pairs
* where the value can be a string or a number.
*/
metadata: PointMetadata;
/** This is where the calculated projections space are cached */
projections: {[key: string]: number};
}
/** Checks to see if the browser supports webgl. */
function hasWebGLSupport(): boolean {
try {
let c = document.createElement('canvas');
let gl = c.getContext('webgl') || c.getContext('experimental-webgl');
return gl != null && typeof weblas !== 'undefined';
} catch (e) {
return false;
}
}
const WEBGL_SUPPORT = hasWebGLSupport();
const IS_FIREFOX = navigator.userAgent.toLowerCase().indexOf('firefox') >= 0;
/** Controls whether nearest neighbors computation is done on the GPU or CPU. */
const KNN_GPU_ENABLED = WEBGL_SUPPORT && !IS_FIREFOX;
/** Sampling is used when computing expensive operations such as T-SNE. */
export const SAMPLE_SIZE = 10000;
/** Number of dimensions to sample when doing approximate PCA. */
export const PCA_SAMPLE_DIM = 200;
/** Number of pca components to compute. */
const NUM_PCA_COMPONENTS = 10;
/** Reserved metadata attribute used for trace information. */
const TRACE_METADATA_ATTR = '__next__';
/**
* Dataset contains a DataPoints array that should be treated as immutable. This
* acts as a working subset of the original data, with cached properties
* from computationally expensive operations. Because creating a subset
* requires normalizing and shifting the vector space, we make a copy of the
* data so we can still always create new subsets based on the original data.
*/
export class DataSet {
points: DataPoint[];
traces: scatterPlot.DataTrace[];
sampledDataIndices: number[] = [];
/**
* This keeps a list of all current projections so you can easily test to see
* if it's been calculated already.
*/
projections = d3.set();
nearest: knn.NearestEntry[][];
nearestK: number;
tSNEIteration: number = 0;
tSNEShouldStop = true;
dim: [number, number] = [0, 0];
hasTSNERun: boolean = false;
spriteAndMetadataInfo: SpriteAndMetadataInfo;
private tsne: TSNE;
/** Creates a new Dataset */
constructor(points: DataPoint[],
spriteAndMetadataInfo?: SpriteAndMetadataInfo) {
this.points = points;
this.sampledDataIndices =
shuffle(d3.range(this.points.length)).slice(0, SAMPLE_SIZE);
this.traces = this.computeTraces(points);
this.dim = [this.points.length, this.points[0].vector.length];
this.spriteAndMetadataInfo = spriteAndMetadataInfo;
}
private computeTraces(points: DataPoint[]) {
// Keep a list of indices seen so we don't compute traces for a given
// point twice.
let indicesSeen = new Int8Array(points.length);
// Compute traces.
let indexToTrace: {[index: number]: scatterPlot.DataTrace} = {};
let traces: scatterPlot.DataTrace[] = [];
for (let i = 0; i < points.length; i++) {
if (indicesSeen[i]) {
continue;
}
indicesSeen[i] = 1;
// Ignore points without a trace attribute.
let next = points[i].metadata[TRACE_METADATA_ATTR];
if (next == null || next === '') {
continue;
}
if (next in indexToTrace) {
let existingTrace = indexToTrace[+next];
// Pushing at the beginning of the array.
existingTrace.pointIndices.unshift(i);
indexToTrace[i] = existingTrace;
continue;
}
// The current point is pointing to a new/unseen trace.
let newTrace: scatterPlot.DataTrace = {pointIndices: []};
indexToTrace[i] = newTrace;
traces.push(newTrace);
let currentIndex = i;
while (points[currentIndex]) {
newTrace.pointIndices.push(currentIndex);
let next = points[currentIndex].metadata[TRACE_METADATA_ATTR];
if (next != null && next !== '') {
indicesSeen[+next] = 1;
currentIndex = +next;
} else {
currentIndex = -1;
}
}
}
return traces;
}
getPointAccessors(projection: Projection, components: (number|string)[]):
[PointAccessor, PointAccessor, PointAccessor] {
if (components.length > 3) {
throw new RangeError('components length must be <= 3');
}
const accessors: [PointAccessor, PointAccessor, PointAccessor] =
[null, null, null];
const prefix = (projection === 'custom') ? 'linear' : projection;
for (let i = 0; i < components.length; ++i) {
if (components[i] == null) {
continue;
}
accessors[i] =
(index =>
this.points[index].projections[prefix + '-' + components[i]]);
}
return accessors;
}
projectionCanBeRendered(projection: Projection): boolean {
if (projection !== 'tsne') {
return true;
}
return this.tSNEIteration > 0;
}
/**
* Returns a new subset dataset by copying out data. We make a copy because
* we have to modify the vectors by normalizing them.
*
* @param subset Array of indices of points that we want in the subset.
*
* @return A subset of the original dataset.
*/
getSubset(subset?: number[]): DataSet {
let pointsSubset = subset && subset.length ?
subset.map(i => this.points[i]) : this.points;
let points = pointsSubset.map(dp => {
return {
metadata: dp.metadata,
index: dp.index,
vector: dp.vector.slice(),
projections: {} as {[key: string]: number}
};
});
return new DataSet(points, this.spriteAndMetadataInfo);
}
/**
* Computes the centroid, shifts all points to that centroid,
* then makes them all unit norm.
*/
normalize() {
// Compute the centroid of all data points.
let centroid = vector.centroid(this.points, a => a.vector);
if (centroid == null) {
throw Error('centroid should not be null');
}
// Shift all points by the centroid and make them unit norm.
for (let id = 0; id < this.points.length; ++id) {
let dataPoint = this.points[id];
dataPoint.vector = vector.sub(dataPoint.vector, centroid);
vector.unit(dataPoint.vector);
}
}
/** Projects the dataset onto a given vector and caches the result. */
projectLinear(dir: vector.Vector, label: string) {
this.projections.add(label);
this.points.forEach(dataPoint => {
dataPoint.projections[label] = vector.dot(dataPoint.vector, dir);
});
}
/** Projects the dataset along the top 10 principal components. */
projectPCA(): Promise<void> {
if (this.projections.has('pca-0')) {
return Promise.resolve<void>(null);
}
return runAsyncTask('Computing PCA...', () => {
// Approximate pca vectors by sampling the dimensions.
let dim = this.points[0].vector.length;
let vectors = this.points.map(d => d.vector);
if (dim > PCA_SAMPLE_DIM) {
vectors = vector.projectRandom(vectors, PCA_SAMPLE_DIM);
}
let sigma = numeric.div(
numeric.dot(numeric.transpose(vectors), vectors), vectors.length);
let U: any;
U = numeric.svd(sigma).U;
let pcaVectors = vectors.map(vector => {
let newV: number[] = [];
for (let d = 0; d < NUM_PCA_COMPONENTS; d++) {
let dot = 0;
for (let i = 0; i < vector.length; i++) {
dot += vector[i] * U[i][d];
}
newV.push(dot);
}
return newV;
});
for (let j = 0; j < NUM_PCA_COMPONENTS; j++) {
let label = 'pca-' + j;
this.projections.add(label);
this.points.forEach((d, i) => {
d.projections[label] = pcaVectors[i][j];
});
}
});
}
/** Runs tsne on the data. */
projectTSNE(
perplexity: number, learningRate: number, tsneDim: number,
stepCallback: (iter: number) => void) {
this.hasTSNERun = true;
let k = Math.floor(3 * perplexity);
let opt = {epsilon: learningRate, perplexity: perplexity, dim: tsneDim};
this.tsne = new TSNE(opt);
this.tSNEShouldStop = false;
this.tSNEIteration = 0;
let step = () => {
if (this.tSNEShouldStop) {
stepCallback(null);
this.tsne = null;
return;
}
this.tsne.step();
let result = this.tsne.getSolution();
this.sampledDataIndices.forEach((index, i) => {
let dataPoint = this.points[index];
dataPoint.projections['tsne-0'] = result[i * tsneDim + 0];
dataPoint.projections['tsne-1'] = result[i * tsneDim + 1];
if (tsneDim === 3) {
dataPoint.projections['tsne-2'] = result[i * tsneDim + 2];
}
});
this.tSNEIteration++;
stepCallback(this.tSNEIteration);
requestAnimationFrame(step);
};
// Nearest neighbors calculations.
let knnComputation: Promise<knn.NearestEntry[][]>;
if (this.nearest != null && k === this.nearestK) {
// We found the nearest neighbors before and will reuse them.
knnComputation = Promise.resolve(this.nearest);
} else {
let sampledData = this.sampledDataIndices.map(i => this.points[i]);
this.nearestK = k;
knnComputation = KNN_GPU_ENABLED ?
knn.findKNNGPUCosine(sampledData, k, (d => d.vector)) :
knn.findKNN(
sampledData, k, (d => d.vector),
(a, b, limit) => vector.cosDistNorm(a, b));
}
knnComputation.then(nearest => {
this.nearest = nearest;
runAsyncTask('Initializing T-SNE...', () => {
this.tsne.initDataDist(this.nearest);
}).then(step);
});
}
mergeMetadata(metadata: SpriteAndMetadataInfo) {
if (metadata.pointsInfo.length !== this.points.length) {
logging.setWarningMessage(
`Number of tensors (${this.points.length}) do not match` +
` the number of lines in metadata (${metadata.pointsInfo.length}).`);
}
this.spriteAndMetadataInfo = metadata;
metadata.pointsInfo.slice(0, this.points.length)
.forEach((m, i) => this.points[i].metadata = m);
}
stopTSNE() { this.tSNEShouldStop = true; }
/**
* Finds the nearest neighbors of the query point using a
* user-specified distance metric.
*/
findNeighbors(pointIndex: number, distFunc: DistanceFunction, numNN: number):
knn.NearestEntry[] {
// Find the nearest neighbors of a particular point.
let neighbors = knn.findKNNofPoint(this.points, pointIndex, numNN,
(d => d.vector), distFunc);
// TODO(smilkov): Figure out why we slice.
let result = neighbors.slice(0, numNN);
return result;
}
/**
* Search the dataset based on a metadata field.
*/
query(query: string, inRegexMode: boolean, fieldName: string): number[] {
let predicate = getSearchPredicate(query, inRegexMode, fieldName);
let matches: number[] = [];
this.points.forEach((point, id) => {
if (predicate(point)) {
matches.push(id);
}
});
return matches;
}
}
export type Projection = 'tsne' | 'pca' | 'custom';
export interface ColorOption {
name: string;
desc?: string;
map?: (value: string|number) => string;
/** List of items for the color map. Defined only for categorical map. */
items?: {label: string, count: number}[];
/** Threshold values and their colors. Defined for gradient color map. */
thresholds?: {value: number, color: string}[];
isSeparator?: boolean;
}
/**
* An interface that holds all the data for serializing the current state of
* the world.
*/
export class State {
/** A label identifying this state. */
label: string = '';
/** Whether this State is selected in the bookmarks pane. */
isSelected: boolean = false;
/** The selected projection tab. */
selectedProjection: Projection;
/** Dimensions of the DataSet. */
dataSetDimensions: [number, number];
/** t-SNE parameters */
tSNEIteration: number = 0;
tSNEPerplexity: number = 0;
tSNELearningRate: number = 0;
tSNEis3d: boolean = true;
/** PCA projection component dimensions */
pcaComponentDimensions: number[] = [];
/** Custom projection parameters */
customSelectedSearchByMetadataOption: string;
customXLeftText: string;
customXLeftRegex: boolean;
customXRightText: string;
customXRightRegex: boolean;
customYUpText: string;
customYUpRegex: boolean;
customYDownText: string;
customYDownRegex: boolean;
/** The computed projections of the tensors. */
projections: Array<{[key: string]: number}> = [];
/** The indices of selected points. */
selectedPoints: number[] = [];
/** Camera state (2d/3d, position, target, zoom, etc). */
cameraDef: scatterPlot.CameraDef;
/** Color by option. */
selectedColorOptionName: string;
/** Label by option. */
selectedLabelOption: string;
}
export function stateGetAccessorDimensions(state: State): Array<number|string> {
let dimensions: Array<number|string>;
switch (state.selectedProjection) {
case 'pca':
dimensions = state.pcaComponentDimensions.slice();
break;
case 'tsne':
dimensions = [0, 1];
if (state.tSNEis3d) {
dimensions.push(2);
}
break;
case 'custom':
dimensions = ['x', 'y'];
break;
default:
throw new Error('Unexpected fallthrough');
}
return dimensions;
} | the_stack |
import {AttributeMetadata} from './../metadata/attribute-metadata';
import {
DynamoEntityIndexesSchema,
DynamoEntityIndexSchema,
} from './../metadata/entity-metadata';
import {
EntityTarget,
Table,
SparseIndexParseError,
CONSUMED_CAPACITY_TYPE,
InvalidDynamicUpdateAttributeValueError,
} from '@typedorm/common';
import {getConstructorForInstance} from '../../helpers/get-constructor-for-instance';
import {isEmptyObject} from '../../helpers/is-empty-object';
import {isScalarType} from '../../helpers/is-scalar-type';
import {parseKey} from '../../helpers/parse-key';
import {Connection} from '../connection/connection';
import {IsAutoGeneratedAttributeMetadata} from '../metadata/auto-generated-attribute-metadata';
import {DynamoEntitySchemaPrimaryKey} from '../metadata/entity-metadata';
import {isDynamoEntityKeySchema} from '../../helpers/is-dynamo-entity-key-schema';
import {isKeyOfTypeAliasSchema} from '../../helpers/is-key-of-type-alias-schema';
import {classToPlain} from 'class-transformer';
import {ExpressionInputParser} from '../expression/expression-input-parser';
export interface MetadataOptions {
requestId?: string;
returnConsumedCapacity?: CONSUMED_CAPACITY_TYPE;
}
export abstract class BaseTransformer {
protected _expressionInputParser: ExpressionInputParser;
constructor(protected connection: Connection) {
this._expressionInputParser = new ExpressionInputParser();
}
/**
* Returns table name decorated for given entity class
* @param entityClass Entity Class
*/
getTableNameForEntity<Entity>(entityClass: EntityTarget<Entity>) {
const entityMetadata = this.connection.getEntityByTarget(entityClass);
return entityMetadata.table.name;
}
applyClassTransformerFormations<Entity>(entity: Entity) {
const transformedPlainEntity = classToPlain<Entity>(entity, {
enableImplicitConversion: true,
excludePrefixes: ['__'], // exclude internal attributes
});
return transformedPlainEntity as Entity;
}
/**
* Transforms entity to dynamo db entity schema
* @param entity Entity to transform to DynamoDB entity type
*/
toDynamoEntity<Entity>(entity: Entity) {
const entityClass = getConstructorForInstance(entity);
// retrieve metadata and parse it to schema
const entityMetadata = this.connection.getEntityByTarget(entityClass);
this.connection.getAttributesForEntity(entityClass).forEach(attr => {
// if no explicit value was provided, look for default/autoGenerate values
if (!Object.keys(entity).includes(attr.name)) {
// auto populate generated values
if (IsAutoGeneratedAttributeMetadata(attr)) {
entity = Object.assign(entity, {[attr.name]: attr.value});
}
const attributeDefaultValue = (attr as AttributeMetadata)?.default;
// include attribute with default value
if (
attributeDefaultValue &&
typeof attributeDefaultValue === 'function'
) {
const attrDefaultValue = attributeDefaultValue(entity);
entity = Object.assign(entity, {
[attr.name]: attrDefaultValue,
});
}
}
});
// pass through entity to class transformer to have all the metadata applied
const parsedEntity = this.applyClassTransformerFormations(entity);
const parsedPrimaryKey = this.recursiveParseEntity(
entityMetadata.schema.primaryKey.attributes,
parsedEntity
);
const indexesToParse = entityMetadata.schema.indexes ?? {};
const rawParsedIndexes = this.recursiveParseEntity(
indexesToParse,
parsedEntity
);
const parsedIndexes = Object.keys(rawParsedIndexes).reduce(
(acc, currIndexKey) => {
const {metadata, attributes} = indexesToParse[currIndexKey];
const currentParsedIndex = rawParsedIndexes[currIndexKey];
// validate if there are any duplicated attribute names
Object.keys(currentParsedIndex).forEach(attr => {
if (acc[attr]) {
throw new Error(
`Failed to parse entity "${entityMetadata.name}", duplicate attribute "${attr}".`
);
}
});
// if current index marked as sparse and one or more attribute is missing value, do not add it to schema
if (metadata.isSparse) {
const doesAllAttributesHaveValue = Object.keys(attributes).every(
attr => {
if (!currentParsedIndex[attr]) {
return false;
}
return true;
}
);
if (!doesAllAttributesHaveValue) {
return acc;
}
}
acc = {...acc, ...currentParsedIndex};
return acc;
},
{} as {[key: string]: string}
);
// clone and cleanup any redundant keys
const formattedSchema = {
...parsedPrimaryKey,
...parsedIndexes,
};
return {...parsedEntity, ...formattedSchema};
}
getAffectedPrimaryKeyAttributes<Entity>(
entityClass: EntityTarget<Entity>,
attributes: Record<string, any>,
attributesTypeMetadata: Record<string, 'static' | 'dynamic'>
) {
const {
schema: {primaryKey},
} = this.connection.getEntityByTarget(entityClass);
const interpolations = primaryKey.metadata._interpolations;
// if none of partition or sort key has any referenced attributes, return
if (!interpolations || isEmptyObject(interpolations)) {
return;
}
const affectedKeyAttributes = Object.entries(attributes).reduce(
(acc, [attrKey, attrValue]: [string, any]) => {
// bail early if current attribute type is not of type scalar
if (!isScalarType(attrValue)) {
return acc;
}
// resolve all interpolations
Object.entries(interpolations).forEach(
([primaryKeyAttrName, primaryKeyAttrRefs]) => {
// if no attributes are referenced for current primary key attribute, return
if (!primaryKeyAttrRefs.includes(attrKey)) {
return;
}
// if parsed value was of type we can not auto resolve indexes
// this must be resolved by the dev
if (attributesTypeMetadata[attrKey] === 'dynamic') {
throw new InvalidDynamicUpdateAttributeValueError(
attrKey,
attrValue
);
}
const parsedKey = parseKey(
primaryKey.attributes[primaryKeyAttrName],
attributes
);
acc[primaryKeyAttrName] = parsedKey;
}
);
return acc;
},
{} as Record<string, string>
);
return affectedKeyAttributes;
}
/**
* Returns all affected indexes for given attributes
* @param entityClass Entity class
* @param attributes Attributes to check affected indexes for
* @param options
*/
getAffectedIndexesForAttributes<Entity>(
entityClass: EntityTarget<Entity>,
attributes: Record<string, any>,
attributesTypeMetadata: Record<string, 'static' | 'dynamic'>,
options?: {nestedKeySeparator: string}
) {
const nestedKeySeparator = options?.nestedKeySeparator ?? '.';
const {
schema: {indexes},
} = this.connection.getEntityByTarget(entityClass);
const affectedIndexes = Object.entries(attributes).reduce(
(acc, [attrKey, currAttrValue]) => {
// if current value is not of scalar type skip checking index
if (
attrKey.includes(nestedKeySeparator) ||
!isScalarType(currAttrValue)
) {
return acc;
}
if (!indexes) {
return acc;
}
Object.keys(indexes).forEach(key => {
const currIndex = indexes[key];
const interpolationsForCurrIndex =
currIndex.metadata._interpolations ?? {};
// if current index does not have any interpolations to resolve, move onto next one
if (isEmptyObject(interpolationsForCurrIndex)) {
return acc;
}
// check if attribute we are looking to update is referenced by any index
Object.keys(interpolationsForCurrIndex).forEach(interpolationKey => {
const currentInterpolation =
interpolationsForCurrIndex[interpolationKey];
if (currentInterpolation.includes(attrKey)) {
// if parsed value was of type we can not auto resolve indexes
// this must be resolved by the dev
if (attributesTypeMetadata[attrKey] === 'dynamic') {
throw new InvalidDynamicUpdateAttributeValueError(
attrKey,
currAttrValue
);
}
try {
const parsedIndex = parseKey(
currIndex.attributes[interpolationKey],
attributes
);
acc[interpolationKey] = parsedIndex;
} catch (err) {
// if there was an error parsing sparse index, ignore
if (!(err instanceof SparseIndexParseError)) {
throw err;
}
}
}
});
});
return acc;
},
{} as any
);
return affectedIndexes;
}
/**
* Returns a primary key of an entity
* @param entityClass Class of entity
* @param attributes Attributes to parse into primary key
*/
getParsedPrimaryKey<Entity>(
table: Table,
primaryKey: DynamoEntitySchemaPrimaryKey,
attributes: Partial<Entity>
) {
return this.recursiveParseEntity(primaryKey.attributes, attributes);
}
/**
* Recursively parses all keys of given object and replaces placeholders with matching values
* @private
* @param schema schema to resolve
* @param entity entity to resolve schema against
*/
protected recursiveParseEntity<Entity = any>(
schema: DynamoEntitySchemaPrimaryKey | DynamoEntityIndexesSchema,
entity: Entity,
isSparse = false
) {
const parsedSchema = Object.keys(schema).reduce((acc, key) => {
const currentValue = (schema as any)[key];
if (
typeof currentValue === 'string' ||
isKeyOfTypeAliasSchema(currentValue)
) {
try {
acc[key] = parseKey(currentValue, entity, {
isSparseIndex: isSparse,
});
} catch (err) {
// if there was an error parsing sparse index, ignore
if (!(err instanceof SparseIndexParseError)) {
throw err;
}
}
} else if (isDynamoEntityKeySchema(currentValue)) {
acc[key] = this.recursiveParseEntity(
currentValue.attributes,
entity,
!!(currentValue.metadata as DynamoEntityIndexSchema)?.isSparse
);
} else {
acc[key] = this.recursiveParseEntity(currentValue, entity);
}
return acc;
}, {} as any);
return parsedSchema;
}
} | the_stack |
import { trace } from '../common/trace';
import { services } from '../common/coreservices';
import { stringify } from '../common/strings';
import { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';
import { isObject, isUndefined } from '../common/predicates';
import { prop, propEq, val, not, is } from '../common/hof';
import { StateDeclaration, StateOrName } from '../state/interface';
import {
TransitionOptions,
TreeChanges,
IHookRegistry,
TransitionHookPhase,
RegisteredHooks,
HookRegOptions,
HookMatchCriteria,
TransitionStateHookFn,
TransitionHookFn,
} from './interface'; // has or is using
import { TransitionHook } from './transitionHook';
import { matchState, makeEvent, RegisteredHook } from './hookRegistry';
import { HookBuilder } from './hookBuilder';
import { PathNode } from '../path/pathNode';
import { PathUtils } from '../path/pathUtils';
import { StateObject } from '../state/stateObject';
import { TargetState } from '../state/targetState';
import { Param } from '../params/param';
import { Resolvable } from '../resolve/resolvable';
import { ViewConfig } from '../view/interface';
import { ResolveContext } from '../resolve/resolveContext';
import { UIRouter } from '../router';
import { UIInjector } from '../interface';
import { RawParams } from '../params/interface';
import { ResolvableLiteral } from '../resolve/interface';
import { Rejection } from './rejectFactory';
import { applyPairs, flattenR, uniqR } from '../common';
/** @internal */
const stateSelf: (_state: StateObject) => StateDeclaration = prop('self');
/**
* Represents a transition between two states.
*
* When navigating to a state, we are transitioning **from** the current state **to** the new state.
*
* This object contains all contextual information about the to/from states, parameters, resolves.
* It has information about all states being entered and exited as a result of the transition.
*/
export class Transition implements IHookRegistry {
/** @internal */
static diToken = Transition;
/**
* A unique identifier for the transition.
*
* This is an auto incrementing integer, starting from `0`.
*/
$id: number;
/**
* A reference to the [[UIRouter]] instance
*
* This reference can be used to access the router services, such as the [[StateService]]
*/
router: UIRouter;
/** @internal */
private _deferred = services.$q.defer();
/**
* This promise is resolved or rejected based on the outcome of the Transition.
*
* When the transition is successful, the promise is resolved
* When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error
*/
promise: Promise<any> = this._deferred.promise;
/**
* A boolean which indicates if the transition was successful
*
* After a successful transition, this value is set to true.
* After an unsuccessful transition, this value is set to false.
*
* The value will be undefined if the transition is not complete
*/
success: boolean;
/** @internal */
_aborted: boolean;
/** @internal */
private _error: Rejection;
/** @internal Holds the hook registration functions such as those passed to Transition.onStart() */
_registeredHooks: RegisteredHooks = {};
/** @internal */
private _options: TransitionOptions;
/** @internal */
private _treeChanges: TreeChanges;
/** @internal */
private _targetState: TargetState;
/** @internal */
private _hookBuilder = new HookBuilder(this);
/** @internal */
onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @internal
* Creates the transition-level hook registration functions
* (which can then be used to register hooks)
*/
private createTransitionHookRegFns() {
this.router.transitionService._pluginapi
._getEvents()
.filter((type) => type.hookPhase !== TransitionHookPhase.CREATE)
.forEach((type) => makeEvent(this, this.router.transitionService, type));
}
/** @internal */
getHooks(hookName: string): RegisteredHook[] {
return this._registeredHooks[hookName];
}
/**
* Creates a new Transition object.
*
* If the target state is not valid, an error is thrown.
*
* @internal
*
* @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`
* encapsulates the "from state".
* @param targetState The target state and parameters being transitioned to (also, the transition options)
* @param router The [[UIRouter]] instance
* @internal
*/
constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {
this.router = router;
this._targetState = targetState;
if (!targetState.valid()) {
throw new Error(targetState.error());
}
// current() is assumed to come from targetState.options, but provide a naive implementation otherwise.
this._options = extend({ current: val(this) }, targetState.options());
this.$id = router.transitionService._transitionCount++;
const toPath = PathUtils.buildToPath(fromPath, targetState);
this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);
this.createTransitionHookRegFns();
const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);
TransitionHook.invokeHooks(onCreateHooks, () => null);
this.applyViewConfigs(router);
}
private applyViewConfigs(router: UIRouter) {
const enteringStates = this._treeChanges.entering.map((node) => node.state);
PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);
}
/**
* @internal
* @returns the internal from [State] object
*/
$from() {
return tail(this._treeChanges.from).state;
}
/**
* @internal
* @returns the internal to [State] object
*/
$to() {
return tail(this._treeChanges.to).state;
}
/**
* Returns the "from state"
*
* Returns the state that the transition is coming *from*.
*
* @returns The state declaration object for the Transition's ("from state").
*/
from(): StateDeclaration {
return this.$from().self;
}
/**
* Returns the "to state"
*
* Returns the state that the transition is going *to*.
*
* @returns The state declaration object for the Transition's target state ("to state").
*/
to(): StateDeclaration {
return this.$to().self;
}
/**
* Gets the Target State
*
* A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.
*
* @returns the [[TargetState]] of this Transition
*/
targetState() {
return this._targetState;
}
/**
* Determines whether two transitions are equivalent.
* @deprecated
*/
is(compare: Transition | { to?: any; from?: any }): boolean {
if (compare instanceof Transition) {
// TODO: Also compare parameters
return this.is({ to: compare.$to().name, from: compare.$from().name });
}
return !(
(compare.to && !matchState(this.$to(), compare.to, this)) ||
(compare.from && !matchState(this.$from(), compare.from, this))
);
}
/**
* Gets transition parameter values
*
* Returns the parameter values for a transition as key/value pairs.
* This object is immutable.
*
* By default, returns the new parameter values (for the "to state").
*
* #### Example:
* ```js
* var toParams = transition.params();
* ```
*
* To return the previous parameter values, supply `'from'` as the `pathname` argument.
*
* #### Example:
* ```js
* var fromParams = transition.params('from');
* ```
*
* @param pathname the name of the treeChanges path to get parameter values for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
*
* @returns transition parameter values for the desired path.
*/
params(pathname?: string): { [paramName: string]: any };
params<T>(pathname?: string): T;
params(pathname = 'to') {
return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));
}
/**
* Gets the new values of any parameters that changed during this transition.
*
* Returns any parameter values that have changed during a transition, as key/value pairs.
*
* - Any parameter values that have changed will be present on the returned object reflecting the new value.
* - Any parameters that *not* have changed will not be present on the returned object.
* - Any new parameters that weren't present in the "from" state, but are now present in the "to" state will be present on the returned object.
* - Any previous parameters that are no longer present (because the "to" state doesn't have them) will be included with a value of `undefined`.
*
* The returned object is immutable.
*
* #### Examples:
*
* Given:
* ```js
* var stateA = { name: 'stateA', url: '/stateA/:param1/param2' }
* var stateB = { name: 'stateB', url: '/stateB/:param3' }
* var stateC = { name: 'stateB.nest', url: '/nest/:param4' }
* ```
*
* #### Example 1
*
* From `/stateA/abc/def` to `/stateA/abc/xyz`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param2: 'xyz' }
* ```
*
* The value of `param2` changed to `xyz`.
* The value of `param1` stayed the same so its value is not present.
*
* #### Example 2
*
* From `/stateA/abc/def` to `/stateB/123`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param1: undefined, param2: undefined, param3: '123' }
* ```
*
* The value `param3` is present because it is a new param.
* Both `param1` and `param2` are no longer present so their value is undefined.
*
* #### Example 3
*
* From `/stateB/123` to `/stateB/123/nest/456`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param4: '456' }
* ```
*
* The value `param4` is present because it is a new param.
* The value of `param3` did not change, so its value is not present.
*
* @returns an immutable object with changed parameter keys/values.
*/
paramsChanged(): { [paramName: string]: any };
paramsChanged<T>(): T;
paramsChanged() {
const fromParams = this.params('from');
const toParams = this.params('to');
// All the parameters declared on both the "to" and "from" paths
const allParamDescriptors: Param[] = []
.concat(this._treeChanges.to)
.concat(this._treeChanges.from)
.map((pathNode) => pathNode.paramSchema)
.reduce(flattenR, [])
.reduce(uniqR, []);
const changedParamDescriptors = Param.changed(allParamDescriptors, fromParams, toParams);
return changedParamDescriptors.reduce((changedValues, descriptor) => {
changedValues[descriptor.id] = toParams[descriptor.id];
return changedValues;
}, {});
}
/**
* Creates a [[UIInjector]] Dependency Injector
*
* Returns a Dependency Injector for the Transition's target state (to state).
* The injector provides resolve values which the target state has access to.
*
* The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).
*
* #### Example:
* ```js
* .onEnter({ entering: 'myState' }, trans => {
* var myResolveValue = trans.injector().get('myResolve');
* // Inject a global service from the global/native injector (if it exists)
* var MyService = trans.injector().get('MyService');
* })
* ```
*
* In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.
* You can use [[UIInjector.getAsync]] to get a promise for the data.
* #### Example:
* ```js
* .onBefore({}, trans => {
* return trans.injector().getAsync('myResolve').then(myResolveValue =>
* return myResolveValue !== 'ABORT';
* });
* });
* ```
*
* If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.
* This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.
* #### Example:
* ```js
* .onEnter({ to: 'foo.bar' }, trans => {
* // returns result of `foo` state's `myResolve` resolve
* // even though `foo.bar` also has a `myResolve` resolve
* var fooData = trans.injector('foo').get('myResolve');
* });
* ```
*
* If you need resolve data from the exiting states, pass `'from'` as `pathName`.
* The resolve data from the `from` path will be returned.
* #### Example:
* ```js
* .onExit({ exiting: 'foo.bar' }, trans => {
* // Gets the resolve value of `myResolve` from the state being exited
* var fooData = trans.injector(null, 'from').get('myResolve');
* });
* ```
*
*
* @param state Limits the resolves provided to only the resolves the provided state has access to.
* @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.
*
* @returns a [[UIInjector]]
*/
injector(state?: StateOrName, pathName = 'to'): UIInjector {
let path: PathNode[] = this._treeChanges[pathName];
if (state) path = PathUtils.subPath(path, (node) => node.state === state || node.state.name === state);
return new ResolveContext(path).injector();
}
/**
* Gets all available resolve tokens (keys)
*
* This method can be used in conjunction with [[injector]] to inspect the resolve values
* available to the Transition.
*
* This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states
* in the Transition's [[TreeChanges.to]] path.
*
* #### Example:
* This example logs all resolve values
* ```js
* let tokens = trans.getResolveTokens();
* tokens.forEach(token => console.log(token + " = " + trans.injector().get(token)));
* ```
*
* #### Example:
* This example creates promises for each resolve value.
* This triggers fetches of resolves (if any have not yet been fetched).
* When all promises have all settled, it logs the resolve values.
* ```js
* let tokens = trans.getResolveTokens();
* let promise = tokens.map(token => trans.injector().getAsync(token));
* Promise.all(promises).then(values => console.log("Resolved values: " + values));
* ```
*
* Note: Angular 1 users whould use `$q.all()`
*
* @param pathname resolve context's path name (e.g., `to` or `from`)
*
* @returns an array of resolve tokens (keys)
*/
getResolveTokens(pathname = 'to'): any[] {
return new ResolveContext(this._treeChanges[pathname]).getTokens();
}
/**
* Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.
*
* Allows a transition hook to dynamically add a Resolvable to this Transition.
*
* Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).
*
* If a `state` argument is provided, the Resolvable is processed when that state is being entered.
* If no `state` is provided then the root state is used.
* If the given `state` has already been entered, the Resolvable is processed when any child state is entered.
* If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.
*
* The `state` argument also scopes the resolved data.
* The resolved data is available from the injector for that `state` and any children states.
*
* #### Example:
* ```js
* transitionService.onBefore({}, transition => {
* transition.addResolvable({
* token: 'myResolve',
* deps: ['MyService'],
* resolveFn: myService => myService.getData()
* });
* });
* ```
*
* @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])
* @param state the state in the "to path" which should receive the new resolve (otherwise, the root state)
*/
addResolvable(resolvable: Resolvable | ResolvableLiteral, state: StateOrName = ''): void {
resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);
const stateName: string = typeof state === 'string' ? state : state.name;
const topath = this._treeChanges.to;
const targetNode = find(topath, (node) => node.state.name === stateName);
const resolveContext: ResolveContext = new ResolveContext(topath);
resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);
}
/**
* Gets the transition from which this transition was redirected.
*
* If the current transition is a redirect, this method returns the transition that was redirected.
*
* #### Example:
* ```js
* let transitionA = $state.go('A').transition
* transitionA.onStart({}, () => $state.target('B'));
* $transitions.onSuccess({ to: 'B' }, (trans) => {
* trans.to().name === 'B'; // true
* trans.redirectedFrom() === transitionA; // true
* });
* ```
*
* @returns The previous Transition, or null if this Transition is not the result of a redirection
*/
redirectedFrom(): Transition {
return this._options.redirectedFrom || null;
}
/**
* Gets the original transition in a redirect chain
*
* A transition might belong to a long chain of multiple redirects.
* This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.
*
* #### Example:
* ```js
* // states
* registry.register({ name: 'A', redirectTo: 'B' });
* registry.register({ name: 'B', redirectTo: 'C' });
* registry.register({ name: 'C', redirectTo: 'D' });
* registry.register({ name: 'D' });
*
* let transitionA = $state.go('A').transition
*
* $transitions.onSuccess({ to: 'D' }, (trans) => {
* trans.to().name === 'D'; // true
* trans.redirectedFrom().to().name === 'C'; // true
* trans.originalTransition() === transitionA; // true
* trans.originalTransition().to().name === 'A'; // true
* });
* ```
*
* @returns The original Transition that started a redirect chain
*/
originalTransition(): Transition {
const rf = this.redirectedFrom();
return (rf && rf.originalTransition()) || this;
}
/**
* Get the transition options
*
* @returns the options for this Transition.
*/
options(): TransitionOptions {
return this._options;
}
/**
* Gets the states being entered.
*
* @returns an array of states that will be entered during this transition.
*/
entering(): StateDeclaration[] {
return map(this._treeChanges.entering, prop('state')).map(stateSelf);
}
/**
* Gets the states being exited.
*
* @returns an array of states that will be exited during this transition.
*/
exiting(): StateDeclaration[] {
return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse();
}
/**
* Gets the states being retained.
*
* @returns an array of states that are already entered from a previous Transition, that will not be
* exited during this Transition
*/
retained(): StateDeclaration[] {
return map(this._treeChanges.retained, prop('state')).map(stateSelf);
}
/**
* Get the [[ViewConfig]]s associated with this Transition
*
* Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.
* This method fetches the `ViewConfigs` for a given path in the Transition (e.g., "to" or "entering").
*
* @param pathname the name of the path to fetch views for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
* @param state If provided, only returns the `ViewConfig`s for a single state in the path
*
* @returns a list of ViewConfig objects for the given path.
*/
views(pathname = 'entering', state?: StateObject): ViewConfig[] {
let path = this._treeChanges[pathname];
path = !state ? path : path.filter(propEq('state', state));
return path.map(prop('views')).filter(identity).reduce(unnestR, []);
}
/**
* Return the transition's tree changes
*
* A transition goes from one state/parameters to another state/parameters.
* During a transition, states are entered and/or exited.
*
* This function returns various branches (paths) which represent the changes to the
* active state tree that are caused by the transition.
*
* @param pathname The name of the tree changes path to get:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
*/
treeChanges(pathname: string): PathNode[];
treeChanges(): TreeChanges;
treeChanges(pathname?: string) {
return pathname ? this._treeChanges[pathname] : this._treeChanges;
}
/**
* Creates a new transition that is a redirection of the current one.
*
* This transition can be returned from a [[TransitionService]] hook to
* redirect a transition to a new state and/or set of parameters.
*
* @internal
*
* @returns Returns a new [[Transition]] instance.
*/
redirect(targetState: TargetState): Transition {
let redirects = 1,
trans: Transition = this;
// tslint:disable-next-line:no-conditional-assignment
while ((trans = trans.redirectedFrom()) != null) {
if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);
}
const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };
// If the original transition was caused by URL sync, then use { location: 'replace' }
// on the new transition (unless the target state explicitly specifies location: false).
// This causes the original url to be replaced with the url for the redirect target
// so the original url disappears from the browser history.
if (this.options().source === 'url' && targetState.options().location !== false) {
redirectOpts.location = 'replace';
}
const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);
targetState = targetState.withOptions(newOptions, true);
const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);
const originalEnteringNodes = this._treeChanges.entering;
const redirectEnteringNodes = newTransition._treeChanges.entering;
// --- Re-use resolve data from original transition ---
// When redirecting from a parent state to a child state where the parent parameter values haven't changed
// (because of the redirect), the resolves fetched by the original transition are still valid in the
// redirected transition.
//
// This allows you to define a redirect on a parent state which depends on an async resolve value.
// You can wait for the resolve, then redirect to a child state based on the result.
// The redirected transition does not have to re-fetch the resolve.
// ---------------------------------------------------------
const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {
return reloadState && node.state.includes[reloadState.name];
};
// Find any "entering" nodes in the redirect path that match the original path and aren't being reloaded
const matchingEnteringNodes: PathNode[] = PathUtils.matching(
redirectEnteringNodes,
originalEnteringNodes,
PathUtils.nonDynamicParams
).filter(not(nodeIsReloading(targetState.options().reloadState)));
// Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.
matchingEnteringNodes.forEach((node, idx) => {
node.resolvables = originalEnteringNodes[idx].resolvables;
});
return newTransition;
}
/** @internal If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */
private _changedParams(): Param[] {
const tc = this._treeChanges;
/** Return undefined if it's not a "dynamic" transition, for the following reasons */
// If user explicitly wants a reload
if (this._options.reload) return undefined;
// If any states are exiting or entering
if (tc.exiting.length || tc.entering.length) return undefined;
// If to/from path lengths differ
if (tc.to.length !== tc.from.length) return undefined;
// If the to/from paths are different
const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)
.map((tuple) => tuple[0].state !== tuple[1].state)
.reduce(anyTrueR, false);
if (pathsDiffer) return undefined;
// Find any parameter values that differ
const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);
const [toValues, fromValues] = [tc.to, tc.from].map((path) => path.map((x) => x.paramValues));
const tuples = arrayTuples(nodeSchemas, toValues, fromValues);
return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);
}
/**
* Returns true if the transition is dynamic.
*
* A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.
*
* @returns true if the Transition is dynamic
*/
dynamic(): boolean {
const changes = this._changedParams();
return !changes ? false : changes.map((x) => x.dynamic).reduce(anyTrueR, false);
}
/**
* Returns true if the transition is ignored.
*
* A transition is ignored if no states are entered nor exited, and no parameter values have changed.
*
* @returns true if the Transition is ignored.
*/
ignored(): boolean {
return !!this._ignoredReason();
}
/** @internal */
_ignoredReason(): 'SameAsCurrent' | 'SameAsPending' | undefined {
const pending = this.router.globals.transition;
const reloadState = this._options.reloadState;
const same = (pathA, pathB) => {
if (pathA.length !== pathB.length) return false;
const matching = PathUtils.matching(pathA, pathB);
return pathA.length === matching.filter((node) => !reloadState || !node.state.includes[reloadState.name]).length;
};
const newTC = this.treeChanges();
const pendTC = pending && pending.treeChanges();
if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';
if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';
}
/**
* Runs the transition
*
* This method is generally called from the [[StateService.transitionTo]]
*
* @internal
*
* @returns a promise for a successful transition.
*/
run(): Promise<any> {
const runAllHooks = TransitionHook.runAllHooks;
// Gets transition hooks array for the given phase
const getHooksFor = (phase: TransitionHookPhase) => this._hookBuilder.buildHooksForPhase(phase);
// When the chain is complete, then resolve or reject the deferred
const transitionSuccess = () => {
trace.traceSuccess(this.$to(), this);
this.success = true;
this._deferred.resolve(this.to());
runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));
};
const transitionError = (reason: Rejection) => {
trace.traceError(reason, this);
this.success = false;
this._deferred.reject(reason);
this._error = reason;
runAllHooks(getHooksFor(TransitionHookPhase.ERROR));
};
const runTransition = () => {
// Wait to build the RUN hook chain until the BEFORE hooks are done
// This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.
const allRunHooks = getHooksFor(TransitionHookPhase.RUN);
const done = () => services.$q.when(undefined);
return TransitionHook.invokeHooks(allRunHooks, done);
};
const startTransition = () => {
const globals = this.router.globals;
globals.lastStartedTransitionId = this.$id;
globals.transition = this;
globals.transitionHistory.enqueue(this);
trace.traceTransitionStart(this);
return services.$q.when(undefined);
};
const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);
TransitionHook.invokeHooks(allBeforeHooks, startTransition)
.then(runTransition)
.then(transitionSuccess, transitionError);
return this.promise;
}
/** Checks if this transition is currently active/running. */
isActive = () => this.router.globals.transition === this;
/**
* Checks if the Transition is valid
*
* @returns true if the Transition is valid
*/
valid() {
return !this.error() || this.success !== undefined;
}
/**
* Aborts this transition
*
* Imperative API to abort a Transition.
* This only applies to Transitions that are not yet complete.
*/
abort() {
// Do not set flag if the transition is already complete
if (isUndefined(this.success)) {
this._aborted = true;
}
}
/**
* The Transition error reason.
*
* If the transition is invalid (and could not be run), returns the reason the transition is invalid.
* If the transition was valid and ran, but was not successful, returns the reason the transition failed.
*
* @returns a transition rejection explaining why the transition is invalid, or the reason the transition failed.
*/
error(): Rejection {
const state: StateObject = this.$to();
if (state.self.abstract) {
return Rejection.invalid(`Cannot transition to abstract state '${state.name}'`);
}
const paramDefs = state.parameters();
const values = this.params();
const invalidParams = paramDefs.filter((param) => !param.validates(values[param.id]));
if (invalidParams.length) {
const invalidValues = invalidParams.map((param) => `[${param.id}:${stringify(values[param.id])}]`).join(', ');
const detail = `The following parameter values are not valid for state '${state.name}': ${invalidValues}`;
return Rejection.invalid(detail);
}
if (this.success === false) return this._error;
}
/**
* A string representation of the Transition
*
* @returns A string representation of the Transition
*/
toString() {
const fromStateOrName = this.from();
const toStateOrName = this.to();
const avoidEmptyHash = (params: RawParams) =>
params['#'] !== null && params['#'] !== undefined ? params : omit(params, ['#']);
// (X) means the to state is invalid.
const id = this.$id,
from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,
fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),
toValid = this.valid() ? '' : '(X) ',
to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,
toParams = stringify(avoidEmptyHash(this.params()));
return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;
}
} | the_stack |
import { Octokit } from "@octokit/rest";
import { RequestRequestOptions } from "@octokit/types";
import * as createHttpsProxyAgent from "https-proxy-agent";
import pick = require("lodash.pick");
import { CONFIGURATION_KEY, CONFIGURATION_POKA_YOKE_THRESHOLD } from "../constants";
import { createError } from "../utils/errors";
import { diff } from "../utils/diffPatch";
import { getVSCodeSetting } from "../utils/vscodeAPI";
import { isEmptyString } from "../utils/lang";
import { ISetting, SettingType } from "../types/SyncingTypes";
import { localize } from "../i18n";
import { parse } from "../utils/jsonc";
import * as GitHubTypes from "../types/GitHubTypes";
import * as Toast from "./Toast";
/**
* GitHub Gist utils.
*/
export class Gist
{
private static _instance: Gist;
/**
* The description of Syncing's gists.
*/
private static readonly GIST_DESCRIPTION: string = "VSCode's Settings - Syncing";
private _api: Octokit;
private _proxy?: string;
private _token?: string;
private constructor(token?: string, proxy?: string)
{
this._proxy = proxy;
const options: { auth?: any; request: RequestRequestOptions } = { request: { timeout: 8000 } };
if (proxy != null && !isEmptyString(proxy))
{
options.request.agent = createHttpsProxyAgent(proxy);
}
this._token = token;
if (token != null && !isEmptyString(token))
{
options.auth = `token ${token}`;
}
this._api = new Octokit(options);
}
/**
* Creates an instance of the class `Gist`, only create a new instance if the params are changed.
*
* @param token GitHub Personal Access Token.
* @param proxy Proxy url.
*/
public static create(token?: string, proxy?: string): Gist
{
if (!Gist._instance || Gist._instance.token !== token || Gist._instance.proxy !== proxy)
{
Gist._instance = new Gist(token, proxy);
}
return Gist._instance;
}
/**
* Gets the GitHub Personal Access Token.
*/
public get token()
{
return this._token;
}
/**
* Gets the proxy url.
*/
public get proxy()
{
return this._proxy;
}
/**
* Gets the currently authenticated GitHub user.
*
* @throws {IEnhancedError}
*/
public async user(): Promise<GitHubTypes.IGistUser>
{
try
{
return (await this._api.users.getAuthenticated()).data;
}
catch (err: any)
{
throw this._createError(err);
}
}
/**
* Gets the gist of the currently authenticated user.
*
* @param id Gist id.
* @param showIndicator Defaults to `false`, don't show progress indicator.
*
* @throws {IEnhancedError}
*/
public async get(id: string, showIndicator: boolean = false): Promise<GitHubTypes.IGist>
{
if (showIndicator)
{
Toast.showSpinner(localize("toast.settings.checking.remote"));
}
try
{
const result = (await this._api.gists.get({ gist_id: id })).data as GitHubTypes.IGist;
if (showIndicator)
{
Toast.clearSpinner("");
}
return result;
}
catch (err: any)
{
const error = this._createError(err);
if (showIndicator)
{
Toast.statusError(localize("toast.settings.downloading.failed", error.message));
}
throw error;
}
}
/**
* Gets all the gists of the currently authenticated user.
*
* @throws {IEnhancedError}
*/
public async getAll(): Promise<GitHubTypes.IGist[]>
{
try
{
// Find and sort VSCode settings gists by time in ascending order.
const gists = (await this._api.gists.list()).data as unknown as GitHubTypes.IGist[];
const extensionsRemoteFilename = `${SettingType.Extensions}.json`;
return gists
.filter(gist => (gist.description === Gist.GIST_DESCRIPTION || gist.files[extensionsRemoteFilename]))
.sort((a, b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());
}
catch (err: any)
{
throw this._createError(err);
}
}
/**
* Delete gist.
*
* @param id Gist id.
*
* @throws {IEnhancedError}
*/
public async delete(id: string): Promise<void>
{
try
{
await this._api.gists.delete({ gist_id: id });
}
catch (err: any)
{
throw this._createError(err);
}
}
/**
* Update gist.
*
* @param {GitHubTypes.GistUpdateParam} content Gist content.
*
* @throws {IEnhancedError}
*/
public async update(content: GitHubTypes.GistUpdateParam): Promise<GitHubTypes.IGist>
{
try
{
return (await this._api.gists.update(content as any)).data as GitHubTypes.IGist;
}
catch (err: any)
{
throw this._createError(err);
}
}
/**
* Determines whether the specified gist exists.
*
* @param id Gist id.
*/
public async exists(id: string): Promise<false | GitHubTypes.IGist>
{
if (id != null && !isEmptyString(id))
{
try
{
const gist = await this.get(id);
if (this.token != null)
{
const user = await this.user();
// Determines whether the owner of the gist is the currently authenticated user.
if (user.id !== gist.owner.id)
{
return false;
}
}
return gist;
}
catch
{
// Ignore error.
}
}
return false;
}
/**
* Creates a new gist.
*
* @param {GitHubTypes.GistCreateParam} content Gist content.
*
* @throws {IEnhancedError}
*/
public async create(content: GitHubTypes.GistCreateParam): Promise<GitHubTypes.IGist>
{
try
{
return (await this._api.gists.create(content as any)).data as GitHubTypes.IGist;
}
catch (err: any)
{
throw this._createError(err);
}
}
/**
* Creates a new settings gist.
*
* @param files Settings files.
* @param isPublic Defaults to `false`, the gist is set to private.
*
* @throws {IEnhancedError}
*/
public createSettings(files = {}, isPublic = false): Promise<GitHubTypes.IGist>
{
return this.create({
files,
description: Gist.GIST_DESCRIPTION,
public: isPublic
});
}
/**
* Updates the gist.
*
* @param id Gist id.
* @param uploads Settings that will be uploaded.
* @param upsert Default is `true`, create new if gist not exists.
* @param showIndicator Defaults to `false`, don't show progress indicator.
*
* @throws {IEnhancedError}
*/
public async findAndUpdate(
id: string,
uploads: ISetting[],
upsert = true,
showIndicator = false
): Promise<GitHubTypes.IGist>
{
if (showIndicator)
{
Toast.showSpinner(localize("toast.settings.uploading"));
}
try
{
let result: GitHubTypes.IGist;
const exists = await this.exists(id);
// Preparing local gist.
const localGist: { gist_id: string; files: any } = { gist_id: id, files: {} };
for (const item of uploads)
{
// Filter out `null` content.
if (item.content != null)
{
localGist.files[item.remoteFilename] = { content: item.content };
}
}
if (exists)
{
// Upload if the local files are modified.
localGist.files = this.getModifiedFiles(localGist.files, exists.files);
if (localGist.files)
{
// poka-yoke - Determines whether there're too much changes since the last uploading.
const threshold = getVSCodeSetting<number>(CONFIGURATION_KEY, CONFIGURATION_POKA_YOKE_THRESHOLD);
if (threshold > 0)
{
// Note that the local settings here have already been excluded.
const localFiles = { ...localGist.files };
const remoteFiles = pick(exists.files, Object.keys(localFiles));
// Diff settings.
const changes = this._diffSettings(localFiles, remoteFiles);
if (changes >= threshold)
{
const okButton = localize("pokaYoke.continue.upload");
const message = localize("pokaYoke.continue.upload.message");
const selection = await Toast.showConfirmBox(
message,
okButton,
localize("pokaYoke.cancel")
);
if (selection !== okButton)
{
throw createError(localize("error.abort.synchronization"));
}
}
}
result = await this.update(localGist);
}
else
{
// Nothing changed.
result = exists;
}
}
else
{
if (upsert)
{
// TODO: Pass gist public option.
result = await this.createSettings(localGist.files);
}
else
{
throw createError(localize("error.gist.notfound", id));
}
}
if (showIndicator)
{
Toast.clearSpinner("");
}
return result;
}
catch (error: any)
{
if (showIndicator)
{
Toast.statusError(localize("toast.settings.uploading.failed", error.message));
}
throw error;
}
}
/**
* Compares the local and remote files, returns the modified files or `undefined`.
*
* @param {GitHubTypes.IGistFiles} localFiles Local files.
* @param {GitHubTypes.IGistFiles} [remoteFiles] Remote files.
*/
public getModifiedFiles(
localFiles: GitHubTypes.IGistFiles,
remoteFiles?: GitHubTypes.IGistFiles
): GitHubTypes.IGistFiles | undefined
{
if (!remoteFiles)
{
return localFiles;
}
let localFile: GitHubTypes.IGistFile;
let remoteFile: GitHubTypes.IGistFile;
const result = {} as GitHubTypes.IGistFiles;
const recordedKeys = [];
for (const key of Object.keys(remoteFiles))
{
localFile = localFiles[key];
remoteFile = remoteFiles[key];
if (localFile)
{
// Ignore null local file.
if (localFile.content != null && localFile.content !== remoteFile.content)
{
result[key] = localFile;
}
}
else
{
// Remove the remote files except keybindings and settings.
if (!key.includes(SettingType.Keybindings) && !key.includes(SettingType.Settings))
{
result[key] = null as any;
}
}
recordedKeys.push(key);
}
// Add the rest local files.
for (const key of Object.keys(localFiles))
{
if (!recordedKeys.includes(key))
{
// Ignore null local file.
localFile = localFiles[key];
if (localFile.content)
{
result[key] = localFile;
}
}
}
return (Object.keys(result).length === 0) ? undefined : result;
}
/**
* Creates the error from an error code.
*/
private _createError(error: Error & { status: number })
{
const { status } = error;
let message = localize("error.check.internet");
if (status === 401)
{
message = localize("error.check.github.token");
}
else if (status === 404)
{
message = localize("error.check.gist.id");
}
console.error("Syncing:", error);
return createError(message, status);
}
/**
* Calculates the number of differences between the local and remote files.
*/
private _diffSettings(localFiles: GitHubTypes.IGistFiles, remoteFiles: GitHubTypes.IGistFiles): number
{
const left = this._parseToJSON(localFiles);
const right = this._parseToJSON(pick(remoteFiles, Object.keys(localFiles)));
return diff(left, right);
}
/**
* Converts the `content` of `GitHubTypes.IGistFiles` into a `JSON object`.
*/
private _parseToJSON(files: GitHubTypes.IGistFiles): Record<string, any>
{
const extensionsRemoteFilename = `${SettingType.Extensions}.json`;
let parsed: any;
let file: GitHubTypes.IGistFile;
const result: Record<string, any> = {};
for (const key of Object.keys(files))
{
file = files[key];
if (file)
{
parsed = parse(file.content || "");
if (key === extensionsRemoteFilename && Array.isArray(parsed))
{
for (const ext of parsed)
{
if (ext["id"] != null)
{
ext["id"] = ext["id"].toLocaleLowerCase();
}
// Only compares id and version.
delete ext["name"];
delete ext["publisher"];
delete ext["uuid"];
}
}
result[key] = parsed;
}
else
{
result[key] = file;
}
}
return result;
}
} | the_stack |
const models = require('../../../../../db/mysqldb/index')
import moment from 'moment'
const { resClientJson } = require('../../../utils/resData')
const Op = require('sequelize').Op
const cheerio = require('cheerio')
const clientWhere = require('../../../utils/clientWhere')
const xss = require('xss')
const config = require('../../../../../config')
const lowdb = require('../../../../../db/lowdb/index')
const { TimeNow, TimeDistance } = require('../../../utils/time')
import {
statusList,
userMessageAction,
modelAction,
modelName
} from '../../../utils/constant'
const { reviewSuccess, freeReview, pendingReview, reviewFail } = statusList
import userVirtual from '../../../common/userVirtual'
import attention from '../../../common/attention'
class dynamic {
static async createDynamic(req: any, res: any, next: any) {
let reqData = req.body
console.log('reqData', req)
let { user = '' } = req
try {
if (!reqData.content) {
throw new Error('请输入片刻内容')
}
if (reqData.content.length > 600) {
throw new Error('动态内容过长,请小于600个字符')
}
let date = new Date()
let currDate = moment(date.setHours(date.getHours())).format(
'YYYY-MM-DD HH:mm:ss'
)
if (new Date(currDate).getTime() < new Date(user.ban_dt).getTime()) {
throw new Error(
`当前用户因违规已被管理员禁用发布片刻,时间到:${moment(
user.ban_dt
).format('YYYY年MM月DD日 HH时mm分ss秒')},如有疑问请联系网站管理员`
)
}
// 虚拟币判断是否可以进行继续的操作
const isVirtual = await userVirtual.isVirtual({
uid: user.uid,
type: modelName.dynamic,
action: modelAction.create
})
if (!isVirtual) {
throw new Error('贝壳余额不足!')
}
let oneDynamicTopic = await models.dynamic_topic.findOne({
where: {
topic_id: config.DYNAMIC.dfOfficialTopic
}
})
const website = lowdb
.read()
.get('website')
.value()
if (
reqData.topic_ids &&
~reqData.topic_ids.indexOf(config.DYNAMIC.dfOfficialTopic)
) {
// 判断使用的是否是官方才能使用的动态话题
if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) {
// 是的话再判断是否有权限,否则就弹出提示
throw new Error(
`${oneDynamicTopic.name}只有${website.website_name}管理团队才能发布`
)
}
}
let userRoleALL = await models.user_role.findAll({
where: {
user_role_id: {
[Op.or]: user.user_role_ids.split(',')
},
user_role_type: 1 // 用户角色类型1是默认角色
}
})
let userAuthorityIds = ''
userRoleALL.map((roleItem: any) => {
userAuthorityIds += roleItem.user_authority_ids + ','
})
let status = ~userAuthorityIds.indexOf(
config.USER_AUTHORITY.dfNoReviewDynamicId
) // 4无需审核, 1审核中
? freeReview // 免审核
: pendingReview // 待审核
const createDynamic = await models.dynamic.create({
uid: user.uid,
content: xss(reqData.content) /* 主内容 */,
origin_content: reqData.content /* 源内容 */,
attach: reqData.attach, // 摘要
status, // '状态(1:审核中;2:审核通过;3:审核失败;4:无需审核)'
type: reqData.type, // 类型 (1:默认动态;2:图片,3:连接,4:视频 )
topic_ids: reqData.topic_ids
})
await attention.attentionMessage({
uid: user.uid,
type: modelName.dynamic,
action: modelAction.create,
associate_id: createDynamic.id
})
await userVirtual.setVirtual({
uid: user.uid,
associate: createDynamic.id,
type: modelName.dynamic,
action: modelAction.create
})
resClientJson(res, {
state: 'success',
message: '动态创建成功'
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async getDynamicView(req: any, res: any, next: any) {
let id = req.query.id || ''
let whereParams = {} // 查询参数
try {
// sort
// hottest 全部热门:
whereParams = {
id: id,
status: {
[Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] // 审核成功、免审核
}
}
let oneDynamic = await models.dynamic.findOne({
where: whereParams // 为空,获取全部,也可以自己添加条件
})
if (oneDynamic) {
oneDynamic.setDataValue(
'create_dt',
await TimeDistance(oneDynamic.create_date)
)
oneDynamic.setDataValue(
'topic',
oneDynamic.topic_ids
? await models.dynamic_topic.findOne({
where: { topic_id: oneDynamic.topic_ids }
})
: ''
)
oneDynamic.setDataValue(
'thumbCount',
await models.thumb.count({
where: {
associate_id: oneDynamic.id,
type: modelName.dynamic,
is_associate: true
}
})
)
if (
oneDynamic.topic_ids &&
config.DYNAMIC.dfTreeHole === oneDynamic.topic_ids
) {
// 判断是不是树洞
oneDynamic.setDataValue('user', {
uid: 'tree',
avatar: config.DF_ARTICLE_TAG_IMG,
nickname: '树洞',
sex: '',
introduction: '树洞'
})
} else {
oneDynamic.setDataValue(
'user',
await models.user.findOne({
where: { uid: oneDynamic.uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
}
if (oneDynamic) {
resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
dynamic: oneDynamic
}
})
} else {
resClientJson(res, {
state: 'error',
message: '数据返回错误,请再次刷新尝试'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async getDynamicList(req: any, res: any, next: any) {
let page = req.query.page || 1
let pageSize = req.query.pageSize || 10
let topic_id = req.query.topic_id || ''
let sort = req.query.sort || '' // 排序
let whereDynamicParams: any = {} // 查询参数
let orderParams = [] // 排序参数
try {
// sort
// hottest 全部热门:
whereDynamicParams = {
status: {
[Op.or]: [reviewSuccess, freeReview]
}
}
if (!~['hot', 'newest'].indexOf(sort)) {
whereDynamicParams['topic_ids'] = topic_id
} else {
// 属于最热或者推荐
let allDynamicTopicId = [] // 全部禁止某些动态话题推送的id
let allDynamicTopic = await models.dynamic_topic.findAll({
where: {
is_push: false
} // 为空,获取全部,也可以自己添加条件
})
if (allDynamicTopic && allDynamicTopic.length > 0) {
for (let item in allDynamicTopic) {
allDynamicTopicId.push(allDynamicTopic[item].topic_id)
}
whereDynamicParams['topic_ids'] = {
[Op.or]: {
[Op.notIn]: allDynamicTopicId,
[Op.is]: null
}
}
}
}
sort === 'newest' && orderParams.push(['create_date', 'DESC'])
sort === 'hot' && orderParams.push(['thumb_count', 'DESC'])
// newest 最新推荐:
if (!sort || sort === 'new') {
orderParams.push(['create_date', 'DESC'])
}
let { count, rows } = await models.dynamic.findAndCountAll({
where: whereDynamicParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: orderParams
})
for (let i in rows) {
let topic = rows[i].topic_ids
? await models.dynamic_topic.findOne({
where: { topic_id: rows[i].topic_ids }
})
: ''
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
rows[i].setDataValue('topic', topic)
rows[i].setDataValue(
'thumbCount',
await models.thumb.count({
where: {
associate_id: rows[i].id,
type: modelName.dynamic,
is_associate: true
}
})
)
if (
rows[i].topic_ids &&
config.DYNAMIC.dfTreeHole === rows[i].topic_ids
) {
// 判断是不是树洞
rows[i].setDataValue('user', {
uid: 'tree',
avatar: config.DF_ARTICLE_TAG_IMG,
nickname: '树洞',
sex: '',
introduction: '树洞'
})
} else {
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
}
if (rows) {
resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
count,
page,
pageSize,
list: rows
}
})
} else {
resClientJson(res, {
state: 'error',
message: '数据返回错误,请再次刷新尝试'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async getDynamicListMe(req: any, res: any, next: any) {
let page = req.query.page || 1
let pageSize = req.query.pageSize || 10
let whereParams = {} // 查询参数
let orderParams = [['create_date', 'DESC']] // 排序参数
let { user = '' } = req
try {
// sort
// hottest 全部热门:
whereParams = {
uid: user.uid,
status: {
[Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail]
}
}
let { count, rows } = await models.dynamic.findAndCountAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: orderParams
})
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
rows[i].setDataValue(
'topic',
rows[i].topic_ids
? await models.dynamic_topic.findOne({
where: { topic_id: rows[i].topic_ids }
})
: ''
)
rows[i].setDataValue(
'thumbCount',
await models.thumb.count({
where: {
associate_id: rows[i].id,
type: modelName.dynamic,
is_associate: true
}
})
)
if (
rows[i].topic_ids &&
config.DYNAMIC.dfTreeHole === rows[i].topic_ids
) {
// 判断是不是树洞
rows[i].setDataValue('user', {
uid: 'tree',
avatar: config.DF_ARTICLE_TAG_IMG,
nickname: '树洞',
sex: '',
introduction: '树洞'
})
} else {
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
}
if (rows) {
resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
count,
page,
pageSize,
list: rows
}
})
} else {
resClientJson(res, {
state: 'error',
message: '数据返回错误,请再次刷新尝试'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
// 推荐动态
static async recommendDynamicList(req: any, res: any, next: any) {
let type = req.query.type || 'recommend'
let whereParams = {} // 查询参数
let orderParams: any = [] // 排序参数
try {
// 属于最热或者推荐
let allDynamicTopicId = [] // 全部禁止某些动态话题推送的id
let allDynamicTopic = await models.dynamic_topic.findAll({
where: {
is_push: false
} // 为空,获取全部,也可以自己添加条件
})
if (allDynamicTopic && allDynamicTopic.length > 0) {
for (let item in allDynamicTopic) {
allDynamicTopicId.push(allDynamicTopic[item].topic_id)
}
}
if (type === 'recommend') {
orderParams = [
['create_date', 'DESC'],
['comment_count', 'DESC']
]
// sort
// hottest 全部热门:
whereParams = {
topic_ids: {
[Op.or]: {
[Op.notIn]: allDynamicTopicId,
[Op.is]: null
}
},
status: {
[Op.or]: [reviewSuccess, freeReview]
},
create_date: {
[Op.between]: [
new Date(TimeNow.showMonthFirstDay()),
new Date(TimeNow.showMonthLastDay())
]
}
}
} else {
orderParams = [['create_date', 'DESC']]
whereParams = {
topic_ids: {
[Op.or]: {
[Op.notIn]: allDynamicTopicId,
[Op.is]: null
}
}
}
}
let allDynamic = await models.dynamic.findAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
limit: 5, // 每页限制返回的数据条数
order: orderParams
})
for (let i in allDynamic) {
allDynamic[i].setDataValue(
'create_dt',
await TimeDistance(allDynamic[i].create_date)
)
allDynamic[i].setDataValue(
'topic',
allDynamic[i].topic_ids
? await models.dynamic_topic.findOne({
where: { topic_id: allDynamic[i].topic_ids }
})
: ''
)
if (
allDynamic[i].topic_ids &&
config.DYNAMIC.dfTreeHole === allDynamic[i].topic_ids
) {
// 判断是不是树洞
allDynamic[i].setDataValue('user', {
uid: 'tree',
avatar: config.DF_ARTICLE_TAG_IMG,
nickname: '树洞',
sex: '',
introduction: '树洞'
})
} else {
allDynamic[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: allDynamic[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
}
if (allDynamic) {
resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
list: allDynamic
}
})
} else {
resClientJson(res, {
state: 'error',
message: '数据返回错误,请再次刷新尝试'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async dynamicTopicIndex(req: any, res: any, next: any) {
// 获取首页侧栏动态列表
try {
let allDynamicTopic = await models.dynamic_topic.findAll({
where: { enable: 1, is_show: 1 }, // 为空,获取全部,也可以自己添加条件
order: [
['sort', 'ASC'] // asc
]
})
resClientJson(res, {
state: 'success',
message: '返回成功',
data: {
list: allDynamicTopic
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async dynamicTopicList(req: any, res: any, next: any) {
// 获取所有动态列表
try {
let allDynamicTopic = await models.dynamic_topic.findAll({
where: { enable: 1 }, // 为空,获取全部,也可以自己添加条件
order: [
['sort', 'ASC'] // asc
]
})
for (let i in allDynamicTopic) {
allDynamicTopic[i].setDataValue(
'dynamicCount',
await models.dynamic.count({
where: { topic_ids: allDynamicTopic[i].topic_id }
})
)
allDynamicTopic[i].setDataValue(
'attention_count',
await models.attention.count({
where: {
associate_id: allDynamicTopic[i].id,
is_associate: true,
type: modelName.dynamic_topic
}
})
)
}
resClientJson(res, {
state: 'success',
message: '返回成功',
data: {
list: allDynamicTopic
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async getDynamicTopicInfo(req: any, res: any, next: any) {
const { topic_id } = req.query
try {
const oneDynamicTopic = await models.dynamic_topic.findOne({
where: {
topic_id
}
})
oneDynamicTopic.setDataValue(
'dynamic_count',
await models.dynamic.count({
where: { topic_ids: oneDynamicTopic.topic_id }
})
)
oneDynamicTopic.setDataValue(
'attention_count',
await models.attention.count({
where: {
associate_id: oneDynamicTopic.id,
is_associate: true,
type: modelName.dynamic_topic
}
})
)
resClientJson(res, {
state: 'success',
data: {
info: oneDynamicTopic
},
message: '动态专题详情获取成功'
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 删除动态
* @param {object} ctx 上下文对象
* 删除动态判断是否有动态
* 无关联则直接删除动态,有关联则开启事务同时删除与动态的关联
*/
static async deleteDynamic(req: any, res: any, next: any) {
const { id } = req.query
let { islogin = '', user = '' } = req
try {
let oneDynamic = await models.dynamic.findOne({
where: {
id,
uid: user.uid // 查询条件
}
})
if (!oneDynamic) {
throw new Error('动态不存在')
}
if (!islogin) {
throw new Error('请登录后尝试')
}
if (user.uid !== oneDynamic.uid) {
throw new Error('非法操作已禁止')
}
await models.dynamic.destroy({ where: { id } })
resClientJson(res, {
state: 'success',
message: '删除动态成功'
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
}
export default dynamic | the_stack |
import { orientationSupport } from '@src/common/constants'
import Shape from '@src/common/shape'
import { IElement, Options } from '@src/types/particle'
import { ValueOf } from '@src/types/utility-types'
import {
calcQuantity,
isElement,
isNull,
offset,
pInt,
randomInRange,
randomSpeed,
} from '@src/utils'
export default class Particle extends Shape<Options> {
static defaultConfig: Options = {
// 粒子个数,默认为容器宽度的 0.12 倍
// (0, 1) 显示为容器宽度相应倍数的个数,0 & [1, +∞) 显示具体个数
// 0 是没有意义的
num: 0.12,
// 粒子最大半径(0, +∞)
maxR: 2.4,
// 粒子最小半径(0, +∞)
minR: 0.6,
// 粒子最大运动速度(0, +∞)
maxSpeed: 1,
// 粒子最小运动速度(0, +∞)
minSpeed: 0.1,
// 两点连线的最大值
// 在 range 范围内的两点距离小于 proximity,则两点之间连线
// (0, 1) 显示为容器宽度相应倍数的个数,0 & [1, +∞) 显示具体个数
proximity: 0.2,
// 定位点的范围,范围越大连线越多
// 当 range 等于 0 时,不连线,相关值无效
// (0, 1) 显示为容器宽度相应倍数的个数,0 & [1, +∞) 显示具体个数
range: 0.2,
// 线段的宽度
lineWidth: 0.2,
// 连线的形状
// spider: 散开的蜘蛛状
// cube: 合拢的立方体状
lineShape: 'spider',
// 改变定位点坐标的事件元素
// null 表示 canvas 画布,或传入原生元素对象,如 document 等
eventElem: null,
// 视差效果 {boolean}
parallax: false,
// 定义粒子在视差图层里的层数及每层的层级大小,类似 css 里的 z-index。
// 取值范围: [0, +∞),值越小视差效果越强烈,0 则不动。
// 定义四层粒子示例:[1, 3, 5, 10]
parallaxLayer: [1, 2, 3],
// 视差强度,值越小视差效果越强烈
parallaxStrength: 3,
}
protected elements!: IElement[]
// 定位点坐标 X
private positionX?: number
// 定位点坐标 Y
private positionY?: number
// 鼠标坐标 X
private mouseX = 0
// 鼠标坐标 Y
private mouseY = 0
// 线条形状生成器
private lineShapeMaker?: (
// 粒子 x 坐标
x: number,
// 粒子 y 坐标
y: number,
// 兄弟粒子 x 坐标
sx: number,
// 兄弟粒子 y 坐标
sy: number,
// 回调函数
cb: () => void
) => void
constructor(selector: string | HTMLElement, options?: Partial<Options>) {
super(Particle.defaultConfig, selector, options)
this.bootstrap()
}
/**
* 初始化数据和运行程序
*/
protected init(): void {
this.ownResizeEvent()
this.optionsNormalize()
if (this.options.range > 0) {
// 定位点坐标
this.positionX = Math.random() * this.canvasWidth
this.positionY = Math.random() * this.canvasHeight
this.defineLineShape()
this.positionEvent()
}
// 初始化鼠标在视差上的坐标
this.mouseX = this.mouseY = 0
this.parallaxEvent()
// 创建粒子
this.createDots()
}
/**
* 标准化配置参数,参考 calcQuantity 方法描述。
* 如:
* num: 0.5 => 表示 0.5 倍画布宽度 => 标准化为具体数值,如 100
* num: 100 => 表示具体数值 => 标准化结果还是 100
*/
private optionsNormalize(): void {
const { canvasWidth, options } = this
const props = ['num', 'proximity', 'range'] as const
props.forEach((prop: ValueOf<typeof props>) => {
options[prop] = pInt(calcQuantity(options[prop], canvasWidth))
})
// 设置触发事件的元素
if (!isElement(options.eventElem) && options.eventElem !== document) {
options.eventElem = this.canvas
}
}
/**
* 根据配置参数生成对应形状的连线函数
*/
private defineLineShape(): void {
const { proximity, range, lineShape } = this.options
switch (lineShape) {
case 'cube':
this.lineShapeMaker = (x, y, sx, sy, cb) => {
const { positionX, positionY } = this
if (
Math.abs(x - sx) <= proximity &&
Math.abs(y - sy) <= proximity &&
Math.abs(x - positionX!) <= range &&
Math.abs(y - positionY!) <= range &&
Math.abs(sx - positionX!) <= range &&
Math.abs(sy - positionY!) <= range
) {
cb()
}
}
break
default:
this.lineShapeMaker = (x, y, sx, sy, cb) => {
const { positionX, positionY } = this
if (
Math.abs(x - sx) <= proximity &&
Math.abs(y - sy) <= proximity &&
((Math.abs(x - positionX!) <= range &&
Math.abs(y - positionY!) <= range) ||
(Math.abs(sx - positionX!) <= range &&
Math.abs(sy - positionY!) <= range))
) {
cb()
}
}
}
}
/**
* 根据配置参数创建许多粒子(纯数据)
* 最后通过 draw 函数绘制真实可见的图形
*/
private createDots(): void {
const { canvasWidth, canvasHeight, getColor } = this
const { maxR, minR, maxSpeed, minSpeed, parallaxLayer } = this.options
const layerLength = parallaxLayer.length
let { num } = this.options
while (num--) {
const r = randomInRange(maxR, minR)
this.elements.push({
r,
x: randomInRange(canvasWidth - r, r),
y: randomInRange(canvasHeight - r, r),
vx: randomSpeed(maxSpeed, minSpeed),
vy: randomSpeed(maxSpeed, minSpeed),
color: getColor(),
shape: this.getShapeData(),
// 定义粒子在视差图层里的层数及每层的层级大小
parallaxLayer: parallaxLayer[Math.floor(Math.random() * layerLength)],
// 定义粒子视差的偏移值
parallaxOffsetX: 0,
parallaxOffsetY: 0,
})
}
}
/**
* 绘制粒子
*/
protected draw(): void {
const { ctx } = this
const { lineWidth } = this.options
this.clearCanvasAndSetGlobalAttrs()
// 当 canvas 宽高改变的时候,全局属性需要重新设置
ctx.lineWidth = lineWidth
// 更新粒子坐标
this.updateXY()
// 绘制粒子
this.elements.forEach((dot) => {
const { x, y, parallaxOffsetX, parallaxOffsetY } = dot
this.drawShape({
...dot,
x: x + parallaxOffsetX,
y: y + parallaxOffsetY,
})
})
// 连接粒子
this.connectDots()
// 循环绘制
this.requestAnimationFrame()
}
/**
* 连接粒子,绘制线段
*/
private connectDots(): void {
// 当连接范围小于 0 时,不连接线段
if (this.options.range <= 0) return
const { elements, ctx, lineShapeMaker } = this
const length = elements.length
elements.forEach((dot, i) => {
const x = dot.x + dot.parallaxOffsetX
const y = dot.y + dot.parallaxOffsetY
while (++i < length) {
const sibDot = elements[i]
const sx = sibDot.x + sibDot.parallaxOffsetX
const sy = sibDot.y + sibDot.parallaxOffsetY
lineShapeMaker?.(x, y, sx, sy, () => {
ctx.save()
ctx.beginPath()
ctx.moveTo(x, y)
ctx.lineTo(sx, sy)
ctx.strokeStyle = dot.color
ctx.stroke()
ctx.restore()
})
}
})
}
/**
* 更新粒子坐标
*/
private updateXY(): void {
const { isPaused, mouseX, mouseY, canvasWidth, canvasHeight } = this
const { parallax, parallaxStrength } = this.options
// 暂停的时候,vx 和 vy 保持不变,
// 防止自适应窗口变化时出现粒子移动
if (isPaused) return
this.elements.forEach((dot) => {
if (parallax) {
// https://github.com/jnicol/particleground/blob/master/jquery.particleground.js#L279-L282
const divisor = parallaxStrength * dot.parallaxLayer
dot.parallaxOffsetX += (mouseX / divisor - dot.parallaxOffsetX) / 10
dot.parallaxOffsetY += (mouseY / divisor - dot.parallaxOffsetY) / 10
}
dot.x += dot.vx
dot.y += dot.vy
const { r, parallaxOffsetX, parallaxOffsetY } = dot
let { x, y } = dot
x += parallaxOffsetX
y += parallaxOffsetY
// 自然碰撞反向,视差事件移动反向
if (x + r >= canvasWidth) {
dot.vx = -Math.abs(dot.vx)
} else if (x - r <= 0) {
dot.vx = Math.abs(dot.vx)
}
if (y + r >= canvasHeight) {
dot.vy = -Math.abs(dot.vy)
} else if (y - r <= 0) {
dot.vy = Math.abs(dot.vy)
}
})
}
/**
* 获取绑定的 DOM 元素(eventElem)的 offset 值
*/
private getEventElemOffset(): null | { left: number; top: number } {
const { eventElem } = this.options
return eventElem === document ? null : offset(eventElem as HTMLElement)
}
/**
* 事件代理
* @param move 移动事件处理函数
* @param orientation 陀螺仪事件处理函数
*/
private eventProxy(
move: (left: number, top: number) => void,
orientation: (beta: number, gamma: number) => void
): void {
const { eventElem } = this.options
let handleOrientation: (e: DeviceOrientationEvent) => void
if (orientationSupport) {
handleOrientation = (e) => {
if (this.isPaused || isNull(e.beta)) return
// 转换 beta 范围 [-180, 180] 成 [-90, 90]
orientation(Math.min(Math.max(e.beta!, -90), 90), e.gamma!)
}
window.addEventListener('deviceorientation', handleOrientation)
}
const handleMove = (e: MouseEvent) => {
if (this.isPaused) return
let left = e.pageX
let top = e.pageY
const offset = this.getEventElemOffset()
if (offset) {
left -= offset.left
top -= offset.top
}
move(left, top)
}
eventElem!.addEventListener('mousemove', handleMove as EventListener)
// 实例销毁时移除绑定的事件
this.onDestroy(() => {
window.removeEventListener('deviceorientation', handleOrientation)
eventElem!.removeEventListener('mousemove', handleMove as EventListener)
})
}
/**
* 鼠标位置事件,根据鼠标的坐标将范围内的粒子连接起来
*/
private positionEvent(): void {
const { range } = this.options
// 性能优化
if (range > this.canvasWidth && range > this.canvasHeight) return
this.eventProxy(
// 鼠标移动事件
(left, top) => {
this.positionX = left
this.positionY = top
},
// 陀螺仪事件
(beta, gamma) => {
this.positionX = (-(gamma - 90) / 180) * this.canvasWidth
this.positionY = (-(beta - 90) / 180) * this.canvasHeight
}
)
}
/**
* 视差效果事件
*/
private parallaxEvent(): void {
if (!this.options.parallax) return
this.eventProxy(
(left, top) => {
this.mouseX = left - this.canvasWidth / 2
this.mouseY = top - this.canvasHeight / 2
},
(beta, gamma) => {
// 一半高度或宽度的对应比例值
// mouseX: - gamma / 90 * canvasWidth / 2;
// mouseY: - beta / 90 * canvasHeight / 2;
this.mouseX = (-gamma * this.canvasWidth) / 180
this.mouseY = (-beta * this.canvasHeight) / 180
}
)
}
/**
* 窗口尺寸调整事件
*/
private ownResizeEvent(): void {
this.onResize((scaleX, scaleY) => {
if (this.options.range > 0) {
this.positionX! *= scaleX
this.positionY! *= scaleY
this.mouseX *= scaleX
this.mouseY *= scaleY
}
})
}
} | the_stack |
import { isSafari } from '@antv/g-webgpu-core';
import { Camera } from '@antv/g-webgpu';
import { WebGPUEngine } from '@antv/g-webgpu-engine';
import * as WebGPUConstants from '@webgpu/types/dist/constants';
import { mat4, vec3 } from 'gl-matrix';
import { InteractionSystem } from './interaction';
import { Mesh } from './Mesh';
import { cornellBoxScene } from './scene/cornell';
import blitFragCode from './shaders/blit.frag.glsl';
import blitVertCode from './shaders/blit.vert.glsl';
// import rayComputeCode from './shaders/raycasting.comp.glsl';
import rayComputeCode from './shaders/whitted.comp.glsl';
export class RayTracer {
private engine: WebGPUEngine;
private inited: boolean = false;
private rafHandle: number;
private computeBindGroupLayout: GPUBindGroupLayout;
private computePipeline: GPUComputePipeline;
private renderBindGroupLayout: GPUBindGroupLayout;
private renderPipeline: GPURenderPipeline;
private outputTexture: GPUTexture;
private accumulatedTexture: GPUTexture;
private verticesBuffer: Float32Array;
private meshesBuffer: Float32Array;
private trianglesBuffer: Int32Array;
private camera: Camera;
private sampleCount = 0;
private randomSeed = 0;
private interactionSystem: InteractionSystem;
constructor(
private options: {
canvas: HTMLCanvasElement;
onInit?: (() => void) | null;
onUpdate?: (() => void) | null;
},
) {}
public async init() {
this.engine = new WebGPUEngine();
await this.engine.init({
canvas: this.options.canvas,
swapChainFormat: WebGPUConstants.TextureFormat.BGRA8Unorm,
antialiasing: false,
supportCompute: true,
});
await this.update();
}
public setSize(width: number, height: number) {
const canvas = this.engine.getCanvas();
const pixelRatio = window.devicePixelRatio;
canvas.width = Math.floor(width * pixelRatio);
canvas.height = Math.floor(height * pixelRatio);
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
this.engine.viewport({
x: 0,
y: 0,
width: canvas.width,
height: canvas.height,
});
}
public update = async () => {
await this.render();
// 考虑运行在 Worker 中,不能使用 window.requestAnimationFrame
this.rafHandle = requestAnimationFrame(this.update);
};
public destroy() {
this.engine.destroy();
this.interactionSystem.tearDown();
cancelAnimationFrame(this.rafHandle);
}
private async render() {
this.engine.beginFrame();
this.engine.clear({
color: [1, 1, 1, 1],
depth: 1,
});
if (!this.inited) {
if (this.options.onInit) {
this.options.onInit();
}
this.createCamera();
this.createInteraction();
this.createMeshes();
this.createOutputTexture();
await this.createComputePipeline();
await this.createRenderPipeline();
this.inited = true;
}
if (this.options.onUpdate) {
this.options.onUpdate();
}
this.runComputePipeline();
this.runRenderPipeline();
this.engine.endFrame();
}
private createInteraction() {
this.interactionSystem = new InteractionSystem(
this.options.canvas,
this.camera,
() => {
this.sampleCount = 0;
this.randomSeed = 0;
},
);
this.interactionSystem.initialize();
}
private createCamera() {
this.camera = new Camera();
this.camera.position = vec3.fromValues(-2.75, 2.75, 8.35);
this.camera.setFocalPoint(vec3.fromValues(-2.75, 2.75, 0));
this.camera.setPerspective(0.1, 100, 40, 1);
}
private createMeshes() {
let totalVerticeCount = 0;
let totalTriangleCount = 0;
cornellBoxScene.forEach((mesh) => {
totalVerticeCount += mesh.vertices.length;
totalTriangleCount += mesh.indices.length;
});
const verticesBuffer = new Float32Array((totalVerticeCount / 3) * 4);
let index = 0;
let trianglesArray = new Array();
let indicesOffset = 0;
let accumulatingTriangleCount = 0;
cornellBoxScene.forEach((mesh) => {
const vertices = mesh.vertices;
for (let i = 0; i < vertices.length; i += 3) {
verticesBuffer[index++] = vertices[i];
verticesBuffer[index++] = vertices[i + 1];
verticesBuffer[index++] = vertices[i + 2];
verticesBuffer[index++] = 0.0;
}
trianglesArray = trianglesArray.concat(
mesh.indices.map((i) => i + indicesOffset),
);
mesh.offset = accumulatingTriangleCount;
accumulatingTriangleCount += mesh.triangleCount * 3;
indicesOffset += mesh.verticeCount;
});
const trianglesBuffer = new Int32Array(trianglesArray);
const meshesBuffer = new Float32Array(
Mesh.createMeshesBuffer(cornellBoxScene),
);
this.verticesBuffer = verticesBuffer;
this.trianglesBuffer = trianglesBuffer;
this.meshesBuffer = meshesBuffer;
}
private createOutputTexture() {
this.outputTexture = this.engine.device.createTexture({
label: 'Output Texture',
size: {
width: this.options.canvas.width,
height: this.options.canvas.height,
depth: 1,
},
// TODO: arrayLayerCount is deprecated: use size.depth
// arrayLayerCount: 1,
mipLevelCount: 1,
sampleCount: 1,
dimension: WebGPUConstants.TextureDimension.E2d,
format: WebGPUConstants.TextureFormat.RGBA32Float,
usage: WebGPUConstants.TextureUsage.Storage,
});
this.accumulatedTexture = this.engine.device.createTexture({
label: 'Accumulated Texture',
size: {
width: this.options.canvas.width,
height: this.options.canvas.height,
depth: 1,
},
// TODO: arrayLayerCount is deprecated: use size.depth
// arrayLayerCount: 1,
mipLevelCount: 1,
sampleCount: 1,
dimension: WebGPUConstants.TextureDimension.E2d,
format: WebGPUConstants.TextureFormat.RGBA32Float,
usage: WebGPUConstants.TextureUsage.Storage,
});
}
private async createRenderPipeline() {
const {
vertexStage,
fragmentStage,
} = await this.compilePipelineStageDescriptor(blitVertCode, blitFragCode);
const bindGroupLayoutEntries = [
{
binding: 0,
visibility: WebGPUConstants.ShaderStage.Fragment,
type: 'readonly-storage-texture',
viewDimension: WebGPUConstants.TextureViewDimension.E2d,
storageTextureFormat: WebGPUConstants.TextureFormat.RGBA32Float,
},
];
this.renderBindGroupLayout = this.engine.device.createBindGroupLayout(
isSafari
? // @ts-ignore
{ bindings: bindGroupLayoutEntries }
: { entries: bindGroupLayoutEntries },
);
const pipelineLayout = this.engine.device.createPipelineLayout({
bindGroupLayouts: [this.renderBindGroupLayout],
});
this.renderPipeline = this.engine.device.createRenderPipeline({
sampleCount: this.engine.mainPassSampleCount,
primitiveTopology: WebGPUConstants.PrimitiveTopology.TriangleList,
rasterizationState: {
frontFace: WebGPUConstants.FrontFace.CCW,
cullMode: WebGPUConstants.CullMode.Back,
depthBias: 0,
depthBiasClamp: 0,
depthBiasSlopeScale: 0,
},
depthStencilState: {
depthWriteEnabled: false,
// depthCompare: depthFuncMap[depth?.func || gl.ALWAYS],
format: WebGPUConstants.TextureFormat.Depth24PlusStencil8,
// stencilFront: stencilFrontBack,
// stencilBack: stencilFrontBack,
stencilReadMask: 0xffffffff,
stencilWriteMask: 0xffffffff,
},
colorStates: [
{
format: this.engine.options.swapChainFormat!,
alphaBlend: {
srcFactor: WebGPUConstants.BlendFactor.One,
dstFactor: WebGPUConstants.BlendFactor.One,
operation: WebGPUConstants.BlendOperation.Add,
},
colorBlend: {
srcFactor: WebGPUConstants.BlendFactor.SrcAlpha,
dstFactor: WebGPUConstants.BlendFactor.OneMinusDstAlpha,
operation: WebGPUConstants.BlendOperation.Add,
},
writeMask: WebGPUConstants.ColorWrite.All,
},
],
alphaToCoverageEnabled: false,
layout: pipelineLayout,
vertexStage,
fragmentStage,
vertexState: {
indexFormat: WebGPUConstants.IndexFormat.Uint32,
vertexBuffers: [],
},
});
}
private async createComputePipeline() {
const { computeStage } = await this.compileComputePipelineStageDescriptor(
rayComputeCode,
);
const bindGroupLayoutEntries = [
{
binding: 0,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'uniform-buffer',
},
{
binding: 1,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'writeonly-storage-texture',
viewDimension: WebGPUConstants.TextureViewDimension.E2d,
storageTextureFormat: WebGPUConstants.TextureFormat.RGBA32Float,
},
{
binding: 2,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'readonly-storage-texture',
viewDimension: WebGPUConstants.TextureViewDimension.E2d,
storageTextureFormat: WebGPUConstants.TextureFormat.RGBA32Float,
},
{
binding: 3,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'readonly-storage-buffer',
},
{
binding: 4,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'readonly-storage-buffer',
},
{
binding: 5,
visibility: WebGPUConstants.ShaderStage.Compute,
type: 'readonly-storage-buffer',
},
];
this.computeBindGroupLayout = this.engine.device.createBindGroupLayout(
isSafari
? // @ts-ignore
{ bindings: bindGroupLayoutEntries }
: { entries: bindGroupLayoutEntries },
);
const pipelineLayout = this.engine.device.createPipelineLayout({
bindGroupLayouts: [this.computeBindGroupLayout],
});
this.computePipeline = this.engine.device.createComputePipeline({
layout: pipelineLayout,
computeStage,
});
}
private runComputePipeline() {
if (this.engine.currentComputePass) {
const cameraWorldMatrix = this.camera.matrix;
const projectionInverseMatrix = mat4.invert(
mat4.create(),
this.camera.getPerspective(),
);
const NDCToScreenMatrix = mat4.create();
mat4.identity(NDCToScreenMatrix);
mat4.translate(NDCToScreenMatrix, NDCToScreenMatrix, [-1, -1, 0]);
mat4.scale(NDCToScreenMatrix, NDCToScreenMatrix, [2, 2, 1]);
mat4.multiply(
projectionInverseMatrix,
projectionInverseMatrix,
NDCToScreenMatrix,
);
const mergedUniformData = [
...cameraWorldMatrix,
...projectionInverseMatrix,
this.randomSeed,
this.sampleCount,
0,
0,
];
const uniformBuffer = this.engine.createBuffer({
data: new Float32Array(mergedUniformData),
usage:
WebGPUConstants.BufferUsage.Uniform |
WebGPUConstants.BufferUsage.CopyDst,
});
const verticeBuffer = this.engine.createBuffer({
data: this.verticesBuffer,
// @ts-ignore
usage:
WebGPUConstants.BufferUsage.Storage |
WebGPUConstants.BufferUsage.CopyDst,
});
const trianglesBuffer = this.engine.createBuffer({
data: this.trianglesBuffer,
// @ts-ignore
usage:
WebGPUConstants.BufferUsage.Storage |
WebGPUConstants.BufferUsage.CopyDst,
});
const meshesBuffer = this.engine.createBuffer({
data: this.meshesBuffer,
// @ts-ignore
usage:
WebGPUConstants.BufferUsage.Storage |
WebGPUConstants.BufferUsage.CopyDst,
});
const bindGroupEntries = [
{
binding: 0,
// https://gpuweb.github.io/gpuweb/#typedefdef-gpubindingresource
resource: {
// @ts-ignore
buffer: uniformBuffer.get(),
},
},
{
binding: 1,
resource: isSafari
? // @ts-ignore
this.outputTexture.createDefaultView()
: this.outputTexture.createView(),
},
{
binding: 2,
resource: isSafari
? // @ts-ignore
this.accumulatedTexture.createDefaultView()
: this.accumulatedTexture.createView(),
},
{
binding: 3,
resource: {
// @ts-ignore
buffer: verticeBuffer.get(),
},
},
{
binding: 4,
resource: {
// @ts-ignore
buffer: trianglesBuffer.get(),
},
},
{
binding: 5,
resource: {
// @ts-ignore
buffer: meshesBuffer.get(),
},
},
];
const computeBindGroup = this.engine.device.createBindGroup(
isSafari
? {
label: 'Compute Bind Group',
layout: this.computeBindGroupLayout,
// @ts-ignore
bindings: bindGroupEntries,
}
: {
label: 'Compute Bind Group',
layout: this.computeBindGroupLayout,
entries: bindGroupEntries,
},
);
this.engine.currentComputePass.setPipeline(this.computePipeline);
this.engine.currentComputePass.setBindGroup(0, computeBindGroup);
this.engine.currentComputePass.dispatch(
this.options.canvas.width / 16,
this.options.canvas.height / 16,
1,
);
this.sampleCount++;
this.randomSeed++;
}
}
private runRenderPipeline() {
const renderPass =
this.engine.bundleEncoder || this.engine.currentRenderPass!;
if (this.renderPipeline) {
renderPass.setPipeline(this.renderPipeline);
}
const bindGroupEntries = [
{
binding: 0,
resource: isSafari
? // @ts-ignore
this.outputTexture.createDefaultView()
: this.outputTexture.createView(),
},
];
const renderBindGroup = this.engine.device.createBindGroup(
isSafari
? {
label: 'Render Bind Group',
layout: this.renderBindGroupLayout,
// @ts-ignore
bindings: bindGroupEntries,
}
: {
label: 'Render Bind Group',
layout: this.renderBindGroupLayout,
entries: bindGroupEntries,
},
);
renderPass.setBindGroup(0, renderBindGroup);
renderPass.draw(3);
// swap
const tmp = this.accumulatedTexture;
this.accumulatedTexture = this.outputTexture;
this.outputTexture = tmp;
}
private compileShaderToSpirV(
source: string,
type: string,
shaderVersion: string,
): Promise<Uint32Array> {
return this.compileRawShaderToSpirV(shaderVersion + source, type);
}
private compileRawShaderToSpirV(
source: string,
type: string,
): Promise<Uint32Array> {
return this.engine.glslang.compileGLSL(source, type);
}
private async compilePipelineStageDescriptor(
vertexCode: string,
fragmentCode: string,
): Promise<
Pick<GPURenderPipelineDescriptor, 'vertexStage' | 'fragmentStage'>
> {
const shaderVersion = '#version 450\n';
const vertexShader = await this.compileShaderToSpirV(
vertexCode,
'vertex',
shaderVersion,
);
const fragmentShader = await this.compileShaderToSpirV(
fragmentCode,
'fragment',
shaderVersion,
);
return this.createPipelineStageDescriptor(vertexShader, fragmentShader);
}
private createPipelineStageDescriptor(
vertexShader: Uint32Array,
fragmentShader: Uint32Array,
): Pick<GPURenderPipelineDescriptor, 'vertexStage' | 'fragmentStage'> {
return {
vertexStage: {
module: this.engine.device.createShaderModule({
code: vertexShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
fragmentStage: {
module: this.engine.device.createShaderModule({
code: fragmentShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
};
}
private async compileComputePipelineStageDescriptor(
computeCode: string,
): Promise<Pick<GPUComputePipelineDescriptor, 'computeStage'>> {
let computeShader;
if (isSafari) {
computeShader = computeCode;
} else {
const shaderVersion = '#version 450\n';
computeShader = await this.compileShaderToSpirV(
computeCode,
'compute',
shaderVersion,
);
}
return {
computeStage: {
module: this.engine.device.createShaderModule({
code: computeShader,
// @ts-ignore
isWHLSL: isSafari,
}),
entryPoint: 'main',
},
};
}
} | the_stack |
/// <reference types="node" />
// See Karma public API https://karma-runner.github.io/latest/dev/public-api.html
import Promise = require('bluebird');
import https = require('https');
import { Appender } from 'log4js';
import { EventEmitter } from 'events';
import * as constants from './lib/constants';
import { VERSION } from './lib/constants';
export { constants, VERSION };
/**
* `start` method is deprecated since 0.13. It will be removed in 0.14.
* Please use
* <code>
* server = new Server(config, [done])
* server.start()
* </code>
* instead.
*
* @deprecated
*/
export const server: DeprecatedServer;
export const runner: Runner;
export const stopper: Stopper;
export namespace launcher {
class Launcher {
static generateId(): string;
constructor(emitter: NodeJS.EventEmitter, injector: any);
// TODO: Can this return value ever be typified?
launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[];
kill(id: string, callback: () => void): boolean;
restart(id: string): boolean;
killAll(callback: () => void): void;
areAllCaptured(): boolean;
markCaptured(id: string): void;
}
}
/** @deprecated */
export interface DeprecatedServer {
/** @deprecated */
start(options?: any, callback?: ServerCallback): void;
}
export interface Runner {
run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;
}
export interface Stopper {
/**
* This function will signal a running server to stop. The equivalent of karma stop.
*/
stop(options?: ConfigOptions, callback?: ServerCallback): void;
}
export interface TestResults {
disconnected: boolean;
error: boolean;
exitCode: number;
failed: number;
success: number;
}
export class Server extends EventEmitter {
constructor(options?: ConfigOptions | ConfigFile, callback?: ServerCallback);
/**
* Start the server
*/
start(): void;
/**
* Get properties from the injector
* @param token
*/
get(token: string): any;
/**
* Force a refresh of the file list
*/
refreshFiles(): Promise<any>;
on(event: string, listener: (...args: any[]) => void): this;
/**
* Listen to the 'run_complete' event.
*/
on(event: 'run_complete', listener: (browsers: any, results: TestResults) => void): this;
/**
* Backward-compatibility with karma-intellij bundled with WebStorm.
* Deprecated since version 0.13, to be removed in 0.14
*/
// static start(): void;
}
export type ServerCallback = (exitCode: number) => void;
export interface Config {
set: (config: ConfigOptions) => void;
LOG_DISABLE: string;
LOG_ERROR: string;
LOG_WARN: string;
LOG_INFO: string;
LOG_DEBUG: string;
}
export interface ConfigFile {
configFile: string;
}
// For documentation and intellisense list Karma browsers
/**
* Available browser launchers
* - `Chrome` - launcher requires `karma-chrome-launcher` plugin
* - `ChromeCanary` - launcher requires `karma-chrome-launcher` plugin
* - `ChromeHeadless` - launcher requires `karma-chrome-launcher` plugin
* - `PhantomJS` - launcher requires `karma-phantomjs-launcher` plugin
* - `Firefox` - launcher requires `karma-firefox-launcher` plugin
* - `Opera` - launcher requires `karma-opera-launcher` plugin
* - `IE` - launcher requires `karma-ie-launcher` plugin
* - `Safari` - launcher requires karma-safari-launcher plugin
*/
export type AutomatedBrowsers =
| 'Chrome'
| 'ChromeCanary'
| 'ChromeHeadless'
| 'PhantomJS'
| 'Firefox'
| 'Opera'
| 'IE'
| 'Safari';
export interface CustomHeaders {
/** Regular expression string to match files */
match: string;
/** HTTP header name */
name: string;
/** HTTP header value */
value: string;
}
export interface ProxyOptions {
/** The target url or path (mandatory) */
target: string;
/**
* Whether or not the proxy should override the Host header using the host from the target
* @defult false
*/
changeOrigin?: boolean | undefined;
}
/** A map of path-proxy pairs. */
export interface PathProxyPairs {
[path: string]: string | ProxyOptions;
}
/** For use when the Karma server needs to be run behind a proxy that changes the base url, etc */
export interface UpstreamProxy {
/**
* Will be prepended to the base url when launching browsers and prepended to internal urls as loaded by the browsers
* @default '/'
*/
path?: string | undefined;
/**
* Will be used as the port when launching browsers
* @default 9875
*/
port?: number | undefined;
/**
* Will be used as the hostname when launching browsers
* @default 'localhost'
*/
hostname?: string | undefined;
/**
* Will be used as the protocol when launching browsers
* @default 'http'
*/
protocol?: string | undefined;
}
// description of inline plugins
export type PluginName = string;
// tslint:disable-next-line:ban-types support for constructor function and classes
export type ConstructorFn = Function | (new (...params: any[]) => any);
export type FactoryFn = (...params: any[]) => any;
export type ConstructorFnType = ['type', ConstructorFn];
export type FactoryFnType = ['factory', FactoryFn];
export type ValueType = ['value', any];
export type InlinePluginType = FactoryFnType | ConstructorFnType | ValueType;
export type InlinePluginDef = Record<PluginName, InlinePluginType>;
export interface ConfigOptions {
/**
* @description Enable or disable watching files and executing the tests whenever one of these files changes.
* @default true
*/
autoWatch?: boolean | undefined;
/**
* @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run
* so that the test runner doesn't try to start and restart running tests more than it should.
* The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred
* before starting the test process again.
* @default 250
*/
autoWatchBatchDelay?: number | undefined;
/**
* @default ''
* @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>.
* If the basePath configuration is a relative path then it will be resolved to
* the <code>__dirname</code> of the configuration file.
*/
basePath?: string | undefined;
/**
* Configure how the browser console is logged with the following properties, all of which are optional
*/
browserConsoleLogOptions?: BrowserConsoleLogOptions | undefined;
/**
* @default 2000
* @description How long does Karma wait for a browser to reconnect (in ms).
* <p>
* With a flaky connection it is pretty common that the browser disconnects,
* but the actual test execution is still running without any problems. Karma does not treat a disconnection
* as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms).
* If the browser reconnects during that time, everything is fine.
* </p>
*/
browserDisconnectTimeout?: number | undefined;
/**
* @default 0
* @description The number of disconnections tolerated.
* <p>
* The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt
* in the case of a disconnection. Usually any disconnection is considered a failure,
* but this option allows you to define a tolerance level when there is a flaky network link between
* the Karma server and the browsers.
* </p>
*/
browserDisconnectTolerance?: number | undefined;
/**
* @default 10000
* @description How long will Karma wait for a message from a browser before disconnecting from it (in ms).
* <p>
* If, during test execution, Karma does not receive any message from a browser within
* <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser
* </p>
*/
browserNoActivityTimeout?: number | undefined;
/**
* Timeout for the client socket connection (in ms)
* @default 20000
*/
browserSocketTimeout?: number | undefined;
/**
* @default []
* Possible Values:
* <ul>
* <li>Chrome (launcher comes installed with Karma)</li>
* <li>ChromeCanary (launcher comes installed with Karma)</li>
* <li>PhantomJS (launcher comes installed with Karma)</li>
* <li>Firefox (launcher requires karma-firefox-launcher plugin)</li>
* <li>Opera (launcher requires karma-opera-launcher plugin)</li>
* <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li>
* <li>Safari (launcher requires karma-safari-launcher plugin)</li>
* </ul>
* @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser
* which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well.
* You can capture any browser manually by opening the browser and visiting the URL where
* the Karma web server is listening (by default it is <code>http://localhost:9876/</code>).
*/
browsers?: Array<AutomatedBrowsers | string> | undefined;
/**
* @default 60000
* @description Timeout for capturing a browser (in ms).
* <p>
* The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a
* browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma
* will kill it and try to launch it again and, after three attempts to capture it, Karma will give up.
* </p>
*/
captureTimeout?: number | undefined;
client?: ClientOptions | undefined;
/**
* @default true
* @description Enable or disable colors in the output (reporters and logs).
*/
colors?: boolean | undefined;
/**
* @default 'Infinity'
* @description How many browsers Karma launches in parallel.
* Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited
* amount of browsers at once, and only start more when those have finished. Using this configuration,
* you can specify how many browsers should be running at once at any given point in time.
*/
concurrency?: number | undefined;
/**
* When true, this will append the crossorigin attribute to generated script tags,
* which enables better error reporting for JavaScript files served from a different origin
* @default true
*/
crossOriginAttribute?: boolean | undefined;
/**
* If null (default), uses karma's own context.html file.
* @default undefined
*/
customContextFile?: string | undefined;
/**
* If null (default), uses karma's own client_with_context.html file (which is used when client.runInParent set to true).
* @default undefined
*/
customClientContextFile?: string | undefined;
/**
* If null (default), uses karma's own debug.html file.
* @default undefined
*/
customDebugFile?: string | undefined;
/**
* Custom HTTP headers that will be set upon serving files by Karma's web server.
* Custom headers are useful, especially with upcoming browser features like Service Workers.
* @default undefined
*/
customHeaders?: CustomHeaders[] | undefined;
customLaunchers?: { [key: string]: CustomLauncher } | undefined;
/**
* When true, this will start the karma server in another process, writing no output to the console.
* The server can be stopped using the karma stop command.
* @default false
*/
detached?: boolean | undefined;
/**
* @default []
* @description List of files/patterns to exclude from loaded files.
*/
exclude?: string[] | undefined;
/**
* Enable or disable failure on running empty test-suites.
* If disabled the program will return exit-code 0 and display a warning.
* @default true
*/
failOnEmptyTestSuite?: boolean | undefined;
/**
* Enable or disable failure on tests deliberately disabled, eg fit() or xit() tests in jasmine.
* Use this to prevent accidental disabling tests needed to validate production.
* @default true
*/
failOnSkippedTests?: boolean | undefined;
/**
* Enable or disable failure on failing tests.
* @default true
*/
failOnFailingTestSuite?: boolean | undefined;
/**
* @default []
* @description List of files/patterns to load in the browser.
*/
files?: Array<FilePattern | string> | undefined;
/**
* Force socket.io to use JSONP polling instead of XHR polling
* @default false
*/
forceJSONP?: boolean | undefined;
/**
* A new error message line
* @default undefined
*/
formatError?: ((msg: string) => string) | undefined;
/**
* @default []
* @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...
* Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
*/
frameworks?: string[] | undefined;
/**
* @default 'localhost'
* @description Hostname to be used when capturing browsers.
*/
hostname?: string | undefined;
/**
* Module used for Karma webserver
* @default undefined
*/
httpModule?: string | undefined;
/**
* @default {}
* @description Options object to be used by Node's https class.
* Object description can be found in the
* [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener)
*/
httpsServerOptions?: https.ServerOptions | undefined;
/**
* Address that the server will listen on. Change to 'localhost' to only listen to the loopback, or '::' to listen on all IPv6 interfaces
* @default '0.0.0.0' or `LISTEN_ADDR`
*/
listenAddress?: string | undefined;
/**
* @default config.LOG_INFO
* Possible values:
* <ul>
* <li>config.LOG_DISABLE</li>
* <li>config.LOG_ERROR</li>
* <li>config.LOG_WARN</li>
* <li>config.LOG_INFO</li>
* <li>config.LOG_DEBUG</li>
* </ul>
* @description Level of logging.
*/
logLevel?: string | undefined;
/**
* @default [{type: 'console'}]
* @description A list of log appenders to be used. See the documentation for [log4js] for more information.
*/
loggers?: { [name: string]: Appender } | Appender[] | undefined;
/**
* @default []
* @description List of names of additional middleware you want the
* Karma server to use. Middleware will be used in the order listed.
* You must have installed the middleware via a plugin/framework
* (either inline or via NPM). Additional information can be found in
* [plugins](http://karma-runner.github.io/2.0/config/plugins.html).
* The plugin must provide an express/connect middleware function
* (details about this can be found in the
* [Express](http://expressjs.com/guide/using-middleware.html) docs).
*/
middleware?: string[] | undefined;
/**
* This is the same as middleware except that these middleware will be run before karma's own middleware.
* @default []
*/
beforeMiddleware?: string[] | undefined;
/**
* @default {}
* @description Redefine default mapping from file extensions to MIME-type.
* Set property name to required MIME, provide Array of extensions (without dots) as it's value.
*/
mime?: { [type: string]: string[] } | undefined;
/**
* Socket.io pingTimeout in ms, https://socket.io/docs/server-api/#new-Server-httpServer-options.
* Very slow networks may need values up to 60000. Larger values delay discovery of deadlock in tests or browser crashes.
* @default 5000
*/
pingTimeout?: number | undefined;
/**
* @default ['karma-*']
* @description List of plugins to load. A plugin can be a string (in which case it will be required
* by Karma) or an inlined plugin - Object.
* By default, Karma loads all sibling NPM modules which have a name starting with karma-*.
* Note: Just about all plugins in Karma require an additional library to be installed (via NPM).
*/
plugins?: Array<PluginName | InlinePluginDef> | undefined;
/**
* @default 9876
* @description The port where the web server will be listening.
*/
port?: number | undefined;
/**
* How long will Karma wait for browser process to terminate before sending a SIGKILL signal
* @default 2000
*/
processKillTimeout?: number | undefined;
/**
* @default {'**\/*.coffee': 'coffee'}
* @description A map of preprocessors to use.
*
* Preprocessors can be loaded through [plugins].
*
* Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults)
* require an additional library to be installed (via NPM).
*
* Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance,
* if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug
* your tests, you'll discover that your expected source code is completely changed from what you expected. Because
* of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list,
* but your interactive debugging does not.
*
*/
preprocessors?: { [name: string]: string | string[] } | undefined;
/**
* @default 'http:'
* Possible Values:
* <ul>
* <li>http:</li>
* <li>https:</li>
* </ul>
* @description Protocol used for running the Karma webserver.
* Determines the use of the Node http or https class.
* Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>.
*/
protocol?: string | undefined;
/**
* @default {}
* @description A map of path-proxy pairs
* The proxy can be specified directly by the target url or path, or with an object to configure more options
*/
proxies?: PathProxyPairs | undefined;
/**
* Called when requesting Proxy
* @default undefined
*/
proxyReq?: ((proxyReq: any, req: any, res: any, options: object) => void) | undefined;
/**
* Called when respnsing Proxy
* @default undefined
*/
proxyRes?: ((proxyRes: any, req: any, res: any) => void) | undefined;
/**
* @default true
* @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found.
*/
proxyValidateSSL?: boolean | undefined;
/**
* @default 0
* @description Karma will report all the tests that are slower than given time limit (in ms).
* This is disabled by default (since the default value is 0).
*/
reportSlowerThan?: number | undefined;
/**
* @default ['progress']
* Possible Values:
* <ul>
* <li>dots</li>
* <li>progress</li>
* </ul>
* @description A list of reporters to use.
* Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins.
* Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM).
*/
reporters?: string[] | undefined;
/**
* When Karma is watching the files for changes, it will delay a new run
* until the current run is finished. Enabling this setting
* will cancel the current run and start a new run immediately when a change is detected.
*/
restartOnFileChange?: boolean | undefined;
/**
* When a browser crashes, karma will try to relaunch. This defines how many times karma should relaunch a browser before giving up.
* @default 2
*/
retryLimit?: number | undefined;
/**
* @default false
* @description Continuous Integration mode.
* If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending
* on whether all tests passed or any tests failed.
*/
singleRun?: boolean | undefined;
/**
* @default ['polling', 'websocket']
* @description An array of allowed transport methods between the browser and testing server. This configuration setting
* is handed off to [socket.io](http://socket.io/) (which manages the communication
* between browsers and the testing server).
*/
transports?: string[] | undefined;
/**
* For use when the Karma server needs to be run behind a proxy that changes the base url, etc
*/
upstreamProxy?: UpstreamProxy | undefined;
/**
* @default '/'
* @description The base url, where Karma runs.
* All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as
* sometimes you might want to proxy a url that is already taken by Karma.
*/
urlRoot?: string | undefined;
}
export interface ClientOptions {
/**
* @default undefined
* @description When karma run is passed additional arguments on the command-line, they
* are passed through to the test adapter as karma.config.args (an array of strings).
* The client.args option allows you to set this value for actions other than run.
* How this value is used is up to your test adapter - you should check your adapter's
* documentation to see how (and if) it uses this value.
*/
args?: string[] | undefined;
/**
* @default false
* @description Set style display none on client elements.
* If true, Karma does not display the banner and browser list.
* Useful when using karma on component tests with screenshots
*/
clientDisplayNone?: boolean | undefined;
/**
* @default true
* @description Run the tests inside an iFrame or a new window
* If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an
* iFrame and may need a new window to run.
*/
useIframe?: boolean | undefined;
/**
* @default true
* @description Capture all console output and pipe it to the terminal.
*/
captureConsole?: boolean | undefined;
/**
* @default false
* @description Run the tests on the same window as the client, without using iframe or a new window
*/
runInParent?: boolean | undefined;
/**
* @default true
* @description Clear the context window
* If true, Karma clears the context window upon the completion of running the tests.
* If false, Karma does not clear the context window upon the completion of running the tests.
* Setting this to false is useful when embedding a Jasmine Spec Runner Template.
*/
clearContext?: boolean | undefined;
}
/** type to use when including a file */
export type FilePatternTypes = 'css' | 'html' | 'js' | 'dart' | 'module' | 'dom';
export interface FilePattern {
/**
* The pattern to use for matching.
*/
pattern: string;
/**
* @default true
* @description If <code>autoWatch</code> is true all files that have set watched to true will be watched
* for changes.
*/
watched?: boolean | undefined;
/**
* @default true
* @description Should the files be included in the browser using <script> tag? Use false if you want to
* load them manually, eg. using Require.js.
*/
included?: boolean | undefined;
/**
* @default true
* @description Should the files be served by Karma's webserver?
*/
served?: boolean | undefined;
/**
* Choose the type to use when including a file
* @default 'js'
* @description The type determines the mechanism for including the file.
* The css and html types create link elements; the js, dart, and module elements create script elements.
* The dom type includes the file content in the page, used, for example, to test components combining HTML and JS.
*/
type?: FilePatternTypes | undefined;
/**
* @default false
* @description Should the files be served from disk on each request by Karma's webserver?
*/
nocache?: boolean | undefined;
}
export interface CustomLauncher {
base: string;
browserName?: string | undefined;
flags?: string[] | undefined;
platform?: string | undefined;
}
export interface BrowserConsoleLogOptions {
/** the desired log-level, where level log always is logged */
level?: 'log' | 'error' | 'warn' | 'info' | 'debug' | undefined;
/**
* The format is a string where `%b`, `%t`, `%T`, and `%m` are replaced with the browser string,
* log type in lower-case, log type in uppercase, and log message, respectively.
* This format will only effect the output file
*/
format?: string | undefined;
/** output-path of the output-file */
path?: string | undefined;
/** if the log should be written in the terminal, or not */
terminal?: boolean | undefined;
}
export namespace config {
function parseConfig(configFilePath: string, cliOptions: ConfigOptions): Config;
} | the_stack |
import { BlockCiper, BlockCiperOperation } from "./block_ciper_operator.ts";
import type { BlockCiperConfig } from "./common.ts";
import type { AESBase } from "./aes_base.ts";
// deno-fmt-ignore
const SBOX: number[] = [
0x63,
0x7c,
0x77,
0x7b,
0xf2,
0x6b,
0x6f,
0xc5,
0x30,
0x01,
0x67,
0x2b,
0xfe,
0xd7,
0xab,
0x76,
0xca,
0x82,
0xc9,
0x7d,
0xfa,
0x59,
0x47,
0xf0,
0xad,
0xd4,
0xa2,
0xaf,
0x9c,
0xa4,
0x72,
0xc0,
0xb7,
0xfd,
0x93,
0x26,
0x36,
0x3f,
0xf7,
0xcc,
0x34,
0xa5,
0xe5,
0xf1,
0x71,
0xd8,
0x31,
0x15,
0x04,
0xc7,
0x23,
0xc3,
0x18,
0x96,
0x05,
0x9a,
0x07,
0x12,
0x80,
0xe2,
0xeb,
0x27,
0xb2,
0x75,
0x09,
0x83,
0x2c,
0x1a,
0x1b,
0x6e,
0x5a,
0xa0,
0x52,
0x3b,
0xd6,
0xb3,
0x29,
0xe3,
0x2f,
0x84,
0x53,
0xd1,
0x00,
0xed,
0x20,
0xfc,
0xb1,
0x5b,
0x6a,
0xcb,
0xbe,
0x39,
0x4a,
0x4c,
0x58,
0xcf,
0xd0,
0xef,
0xaa,
0xfb,
0x43,
0x4d,
0x33,
0x85,
0x45,
0xf9,
0x02,
0x7f,
0x50,
0x3c,
0x9f,
0xa8,
0x51,
0xa3,
0x40,
0x8f,
0x92,
0x9d,
0x38,
0xf5,
0xbc,
0xb6,
0xda,
0x21,
0x10,
0xff,
0xf3,
0xd2,
0xcd,
0x0c,
0x13,
0xec,
0x5f,
0x97,
0x44,
0x17,
0xc4,
0xa7,
0x7e,
0x3d,
0x64,
0x5d,
0x19,
0x73,
0x60,
0x81,
0x4f,
0xdc,
0x22,
0x2a,
0x90,
0x88,
0x46,
0xee,
0xb8,
0x14,
0xde,
0x5e,
0x0b,
0xdb,
0xe0,
0x32,
0x3a,
0x0a,
0x49,
0x06,
0x24,
0x5c,
0xc2,
0xd3,
0xac,
0x62,
0x91,
0x95,
0xe4,
0x79,
0xe7,
0xc8,
0x37,
0x6d,
0x8d,
0xd5,
0x4e,
0xa9,
0x6c,
0x56,
0xf4,
0xea,
0x65,
0x7a,
0xae,
0x08,
0xba,
0x78,
0x25,
0x2e,
0x1c,
0xa6,
0xb4,
0xc6,
0xe8,
0xdd,
0x74,
0x1f,
0x4b,
0xbd,
0x8b,
0x8a,
0x70,
0x3e,
0xb5,
0x66,
0x48,
0x03,
0xf6,
0x0e,
0x61,
0x35,
0x57,
0xb9,
0x86,
0xc1,
0x1d,
0x9e,
0xe1,
0xf8,
0x98,
0x11,
0x69,
0xd9,
0x8e,
0x94,
0x9b,
0x1e,
0x87,
0xe9,
0xce,
0x55,
0x28,
0xdf,
0x8c,
0xa1,
0x89,
0x0d,
0xbf,
0xe6,
0x42,
0x68,
0x41,
0x99,
0x2d,
0x0f,
0xb0,
0x54,
0xbb,
0x16,
];
// deno-fmt-ignore
const INV_SBOX: number[] = [
0x52,
0x09,
0x6a,
0xd5,
0x30,
0x36,
0xa5,
0x38,
0xbf,
0x40,
0xa3,
0x9e,
0x81,
0xf3,
0xd7,
0xfb,
0x7c,
0xe3,
0x39,
0x82,
0x9b,
0x2f,
0xff,
0x87,
0x34,
0x8e,
0x43,
0x44,
0xc4,
0xde,
0xe9,
0xcb,
0x54,
0x7b,
0x94,
0x32,
0xa6,
0xc2,
0x23,
0x3d,
0xee,
0x4c,
0x95,
0x0b,
0x42,
0xfa,
0xc3,
0x4e,
0x08,
0x2e,
0xa1,
0x66,
0x28,
0xd9,
0x24,
0xb2,
0x76,
0x5b,
0xa2,
0x49,
0x6d,
0x8b,
0xd1,
0x25,
0x72,
0xf8,
0xf6,
0x64,
0x86,
0x68,
0x98,
0x16,
0xd4,
0xa4,
0x5c,
0xcc,
0x5d,
0x65,
0xb6,
0x92,
0x6c,
0x70,
0x48,
0x50,
0xfd,
0xed,
0xb9,
0xda,
0x5e,
0x15,
0x46,
0x57,
0xa7,
0x8d,
0x9d,
0x84,
0x90,
0xd8,
0xab,
0x00,
0x8c,
0xbc,
0xd3,
0x0a,
0xf7,
0xe4,
0x58,
0x05,
0xb8,
0xb3,
0x45,
0x06,
0xd0,
0x2c,
0x1e,
0x8f,
0xca,
0x3f,
0x0f,
0x02,
0xc1,
0xaf,
0xbd,
0x03,
0x01,
0x13,
0x8a,
0x6b,
0x3a,
0x91,
0x11,
0x41,
0x4f,
0x67,
0xdc,
0xea,
0x97,
0xf2,
0xcf,
0xce,
0xf0,
0xb4,
0xe6,
0x73,
0x96,
0xac,
0x74,
0x22,
0xe7,
0xad,
0x35,
0x85,
0xe2,
0xf9,
0x37,
0xe8,
0x1c,
0x75,
0xdf,
0x6e,
0x47,
0xf1,
0x1a,
0x71,
0x1d,
0x29,
0xc5,
0x89,
0x6f,
0xb7,
0x62,
0x0e,
0xaa,
0x18,
0xbe,
0x1b,
0xfc,
0x56,
0x3e,
0x4b,
0xc6,
0xd2,
0x79,
0x20,
0x9a,
0xdb,
0xc0,
0xfe,
0x78,
0xcd,
0x5a,
0xf4,
0x1f,
0xdd,
0xa8,
0x33,
0x88,
0x07,
0xc7,
0x31,
0xb1,
0x12,
0x10,
0x59,
0x27,
0x80,
0xec,
0x5f,
0x60,
0x51,
0x7f,
0xa9,
0x19,
0xb5,
0x4a,
0x0d,
0x2d,
0xe5,
0x7a,
0x9f,
0x93,
0xc9,
0x9c,
0xef,
0xa0,
0xe0,
0x3b,
0x4d,
0xae,
0x2a,
0xf5,
0xb0,
0xc8,
0xeb,
0xbb,
0x3c,
0x83,
0x53,
0x99,
0x61,
0x17,
0x2b,
0x04,
0x7e,
0xba,
0x77,
0xd6,
0x26,
0xe1,
0x69,
0x14,
0x63,
0x55,
0x21,
0x0c,
0x7d,
];
const RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
function xtime(n: number, x: number): number {
if (x === 1) return n;
let output = 0;
let multiply = n;
while (x > 0) {
if (x & 0x01) output ^= multiply;
multiply = multiply & 0x80 ? (multiply << 1) ^ 0x011b : multiply << 1;
x = x >> 1;
}
return output & 0xff;
}
function rotWord(keySchedule: Uint8Array, column: number) {
const offset = column * 4;
const tmp = keySchedule[offset];
keySchedule[offset] = keySchedule[offset + 1];
keySchedule[offset + 1] = keySchedule[offset + 2];
keySchedule[offset + 2] = keySchedule[offset + 3];
keySchedule[offset + 3] = tmp;
}
function subWord(keySchedule: Uint8Array, column: number) {
const offset = column * 4;
for (let i = 0; i < 4; i++) {
keySchedule[offset + i] = SBOX[keySchedule[offset + i]];
}
}
function keyExpansion(key: Uint8Array) {
const Nb = 4;
const Nk = key.length / 4;
const Nr = Nk + 6;
const keySchedule = new Uint8Array(16 * (Nr + 1));
keySchedule.set(key, 0);
for (let i = Nk; i < Nb * (Nr + 1); i++) {
const prevOffset = (i - Nk) * 4;
const offset = i * 4;
keySchedule[offset] = keySchedule[offset - 4];
keySchedule[offset + 1] = keySchedule[offset - 3];
keySchedule[offset + 2] = keySchedule[offset - 2];
keySchedule[offset + 3] = keySchedule[offset - 1];
if (i % Nk === 0) {
rotWord(keySchedule, i);
subWord(keySchedule, i);
keySchedule[offset] ^= RCON[i / Nk];
} else if (Nk > 6 && i % Nk === 4) {
subWord(keySchedule, i);
}
keySchedule[offset] ^= keySchedule[prevOffset];
keySchedule[offset + 1] ^= keySchedule[prevOffset + 1];
keySchedule[offset + 2] ^= keySchedule[prevOffset + 2];
keySchedule[offset + 3] ^= keySchedule[prevOffset + 3];
}
return keySchedule;
}
class AESBlockCiper implements BlockCiper {
protected keySchedule: Uint8Array;
constructor(key: Uint8Array) {
this.keySchedule = keyExpansion(key);
}
subBytes(block: Uint8Array) {
for (let i = 0; i < block.length; i++) {
block[i] = SBOX[block[i]];
}
}
inverseSubBytes(block: Uint8Array) {
for (let i = 0; i < block.length; i++) {
block[i] = INV_SBOX[block[i]];
}
}
shiftRow(block: Uint8Array) {
let t = block[1];
block[1] = block[5];
block[5] = block[9];
block[9] = block[13];
block[13] = t;
t = block[10];
block[10] = block[2];
block[2] = t;
t = block[14];
block[14] = block[6];
block[6] = t;
t = block[15];
block[15] = block[11];
block[11] = block[7];
block[7] = block[3];
block[3] = t;
}
inverseShiftRow(block: Uint8Array) {
let t = block[13];
block[13] = block[9];
block[9] = block[5];
block[5] = block[1];
block[1] = t;
t = block[10];
block[10] = block[2];
block[2] = t;
t = block[14];
block[14] = block[6];
block[6] = t;
t = block[3];
block[3] = block[7];
block[7] = block[11];
block[11] = block[15];
block[15] = t;
}
protected addRoundKey(state: Uint8Array, round: number) {
for (let i = 0; i < 16; i++) {
state[i] ^= this.keySchedule[round * 16 + i];
}
}
mixColumn(block: Uint8Array) {
for (let i = 0; i < 4; i++) {
const offset = i * 4;
const a = [
block[offset],
block[offset + 1],
block[offset + 2],
block[offset + 3],
];
block[offset] = xtime(a[0], 0x2) ^
xtime(a[1], 0x3) ^
xtime(a[2], 0x1) ^
xtime(a[3], 0x1);
block[offset + 1] = xtime(a[0], 0x1) ^
xtime(a[1], 0x2) ^
xtime(a[2], 0x3) ^
xtime(a[3], 0x1);
block[offset + 2] = xtime(a[0], 0x1) ^
xtime(a[1], 0x1) ^
xtime(a[2], 0x2) ^
xtime(a[3], 0x3);
block[offset + 3] = xtime(a[0], 0x3) ^
xtime(a[1], 0x1) ^
xtime(a[2], 0x1) ^
xtime(a[3], 0x2);
}
}
inverseMixColumn(block: Uint8Array) {
for (let i = 0; i < 4; i++) {
const offset = i * 4;
const a = [
block[offset],
block[offset + 1],
block[offset + 2],
block[offset + 3],
];
block[offset] = xtime(a[0], 0xe) ^
xtime(a[1], 0xb) ^
xtime(a[2], 0xd) ^
xtime(a[3], 0x9);
block[offset + 1] = xtime(a[0], 0x9) ^
xtime(a[1], 0xe) ^
xtime(a[2], 0xb) ^
xtime(a[3], 0xd);
block[offset + 2] = xtime(a[0], 0xd) ^
xtime(a[1], 0x9) ^
xtime(a[2], 0xe) ^
xtime(a[3], 0xb);
block[offset + 3] = xtime(a[0], 0xb) ^
xtime(a[1], 0xd) ^
xtime(a[2], 0x9) ^
xtime(a[3], 0xe);
}
}
encrypt(m: Uint8Array): Uint8Array {
const nb = 4;
const nr = this.keySchedule.length / 16 - 1;
const state = new Uint8Array(m);
this.addRoundKey(state, 0);
for (let i = 1; i < nr; i++) {
this.subBytes(state);
this.shiftRow(state);
this.mixColumn(state);
this.addRoundKey(state, i);
}
this.subBytes(state);
this.shiftRow(state);
this.addRoundKey(state, nr);
return state;
}
decrypt(m: Uint8Array): Uint8Array {
const nb = 4;
const nr = this.keySchedule.length / 16 - 1;
const state = new Uint8Array(m);
this.addRoundKey(state, nr);
for (let i = nr - 1; i > 0; i--) {
this.inverseShiftRow(state);
this.inverseSubBytes(state);
this.addRoundKey(state, i);
this.inverseMixColumn(state);
}
this.inverseShiftRow(state);
this.inverseSubBytes(state);
this.addRoundKey(state, 0);
return state;
}
}
export class PureAES implements AESBase {
protected ciper: AESBlockCiper;
protected config?: BlockCiperConfig;
constructor(key: Uint8Array, config?: BlockCiperConfig) {
this.ciper = new AESBlockCiper(key);
this.config = config;
}
async encrypt(m: Uint8Array): Promise<Uint8Array> {
return BlockCiperOperation.encrypt(m, this.ciper, 16, this.config);
}
async decrypt(m: Uint8Array): Promise<Uint8Array> {
return BlockCiperOperation.decrypt(m, this.ciper, 16, this.config);
}
} | the_stack |
import {
CommandClasses,
getCCName,
Maybe,
MessageOrCCLogEntry,
MessageRecord,
parseCCId,
validatePayload,
ValueID,
ZWaveError,
ZWaveErrorCodes,
} from "@zwave-js/core";
import { cpp2js, getEnumMemberName, num2hex } from "@zwave-js/shared";
import type { Driver } from "../driver/Driver";
import { MessagePriority } from "../message/Constants";
import { PhysicalCCAPI } from "./API";
import type { AssociationCC } from "./AssociationCC";
import {
API,
CCCommand,
CCCommandOptions,
ccKeyValuePair,
ccValue,
CommandClass,
commandClass,
CommandClassDeserializationOptions,
CommandClassOptions,
expectedCCResponse,
gotDeserializationOptions,
implementedVersion,
} from "./CommandClass";
import type { MultiChannelAssociationCC } from "./MultiChannelAssociationCC";
// @noSetValueAPI This CC only has get-type commands
// All the supported commands
export enum AssociationGroupInfoCommand {
NameGet = 0x01,
NameReport = 0x02,
InfoGet = 0x03,
InfoReport = 0x04,
CommandListGet = 0x05,
CommandListReport = 0x06,
}
// TODO: Check if this should be in a config file instead
/**
* @publicAPI
*/
export enum AssociationGroupInfoProfile {
"General: N/A" = 0x00_00,
"General: Lifeline" = 0x00_01,
"Control: Key 01" = 0x20_01,
"Control: Key 02",
"Control: Key 03",
"Control: Key 04",
"Control: Key 05",
"Control: Key 06",
"Control: Key 07",
"Control: Key 08",
"Control: Key 09",
"Control: Key 10",
"Control: Key 11",
"Control: Key 12",
"Control: Key 13",
"Control: Key 14",
"Control: Key 15",
"Control: Key 16",
"Control: Key 17",
"Control: Key 18",
"Control: Key 19",
"Control: Key 20",
"Control: Key 21",
"Control: Key 22",
"Control: Key 23",
"Control: Key 24",
"Control: Key 25",
"Control: Key 26",
"Control: Key 27",
"Control: Key 28",
"Control: Key 29",
"Control: Key 30",
"Control: Key 31",
"Control: Key 32",
"Sensor: Air temperature" = 0x31_01,
"Sensor: General purpose",
"Sensor: Illuminance",
"Sensor: Power",
"Sensor: Humidity",
"Sensor: Velocity",
"Sensor: Direction",
"Sensor: Atmospheric pressure",
"Sensor: Barometric pressure",
"Sensor: Solar radiation",
"Sensor: Dew point",
"Sensor: Rain rate",
"Sensor: Tide level",
"Sensor: Weight",
"Sensor: Voltage",
"Sensor: Current",
"Sensor: Carbon dioxide (CO2) level",
"Sensor: Air flow",
"Sensor: Tank capacity",
"Sensor: Distance",
"Sensor: Angle position",
"Sensor: Rotation",
"Sensor: Water temperature",
"Sensor: Soil temperature",
"Sensor: Seismic Intensity",
"Sensor: Seismic magnitude",
"Sensor: Ultraviolet",
"Sensor: Electrical resistivity",
"Sensor: Electrical conductivity",
"Sensor: Loudness",
"Sensor: Moisture",
"Sensor: Frequency",
"Sensor: Time",
"Sensor: Target temperature",
"Sensor: Particulate Matter 2.5",
"Sensor: Formaldehyde (CH2O) level",
"Sensor: Radon concentration",
"Sensor: Methane (CH4) density",
"Sensor: Volatile Organic Compound level",
"Sensor: Carbon monoxide (CO) level",
"Sensor: Soil humidity",
"Sensor: Soil reactivity",
"Sensor: Soil salinity",
"Sensor: Heart rate",
"Sensor: Blood pressure",
"Sensor: Muscle mass",
"Sensor: Fat mass",
"Sensor: Bone mass",
"Sensor: Total body water (TBW)",
"Sensor: Basis metabolic rate (BMR)",
"Sensor: Body Mass Index (BMI)",
"Sensor: Acceleration X-axis",
"Sensor: Acceleration Y-axis",
"Sensor: Acceleration Z-axis",
"Sensor: Smoke density",
"Sensor: Water flow",
"Sensor: Water pressure",
"Sensor: RF signal strength",
"Sensor: Particulate Matter 10",
"Sensor: Respiratory rate",
"Sensor: Relative Modulation level",
"Sensor: Boiler water temperature",
"Sensor: Domestic Hot Water (DHW) temperature",
"Sensor: Outside temperature",
"Sensor: Exhaust temperature",
"Sensor: Water Chlorine level",
"Sensor: Water acidity",
"Sensor: Water Oxidation reduction potential",
"Sensor: Heart Rate LF/HF ratio",
"Sensor: Motion Direction",
"Sensor: Applied force on the sensor",
"Sensor: Return Air temperature",
"Sensor: Supply Air temperature",
"Sensor: Condenser Coil temperature",
"Sensor: Evaporator Coil temperature",
"Sensor: Liquid Line temperature",
"Sensor: Discharge Line temperature",
"Sensor: Suction Pressure",
"Sensor: Discharge Pressure",
"Sensor: Defrost temperature",
"Notification: Smoke Alarm" = 0x71_01,
"Notification: CO Alarm",
"Notification: CO2 Alarm",
"Notification: Heat Alarm",
"Notification: Water Alarm",
"Notification: Access Control",
"Notification: Home Security",
"Notification: Power Management",
"Notification: System",
"Notification: Emergency Alarm",
"Notification: Clock",
"Notification: Appliance",
"Notification: Home Health",
"Notification: Siren",
"Notification: Water Valve",
"Notification: Weather Alarm",
"Notification: Irrigation",
"Notification: Gas alarm",
"Notification: Pest Control",
"Notification: Light sensor",
"Notification: Water Quality Monitoring",
"Notification: Home monitoring",
"Meter: Electric" = 0x32_01,
"Meter: Gas",
"Meter: Water",
"Meter: Heating",
"Meter: Cooling",
"Irrigation: Channel 01" = 0x6b_01,
"Irrigation: Channel 02",
"Irrigation: Channel 03",
"Irrigation: Channel 04",
"Irrigation: Channel 05",
"Irrigation: Channel 06",
"Irrigation: Channel 07",
"Irrigation: Channel 08",
"Irrigation: Channel 09",
"Irrigation: Channel 10",
"Irrigation: Channel 11",
"Irrigation: Channel 12",
"Irrigation: Channel 13",
"Irrigation: Channel 14",
"Irrigation: Channel 15",
"Irrigation: Channel 16",
"Irrigation: Channel 17",
"Irrigation: Channel 18",
"Irrigation: Channel 19",
"Irrigation: Channel 20",
"Irrigation: Channel 21",
"Irrigation: Channel 22",
"Irrigation: Channel 23",
"Irrigation: Channel 24",
"Irrigation: Channel 25",
"Irrigation: Channel 26",
"Irrigation: Channel 27",
"Irrigation: Channel 28",
"Irrigation: Channel 29",
"Irrigation: Channel 30",
"Irrigation: Channel 31",
"Irrigation: Channel 32",
}
/**
* @publicAPI
*/
export interface AssociationGroup {
/** How many nodes this association group supports */
maxNodes: number;
/** Whether this is the lifeline association (where the Controller must not be removed) */
isLifeline: boolean;
/** Whether multi channel associations are allowed */
multiChannel: boolean;
/** The name of the group */
label: string;
/** The association group profile (if known) */
profile?: AssociationGroupInfoProfile;
/** A map of Command Classes and commands issued by this group (if known) */
issuedCommands?: ReadonlyMap<CommandClasses, readonly number[]>;
}
/** Returns the ValueID used to store the name of an association group */
function getGroupNameValueID(endpointIndex: number, groupId: number): ValueID {
return {
commandClass: CommandClasses["Association Group Information"],
endpoint: endpointIndex,
property: "name",
propertyKey: groupId,
};
}
/** Returns the ValueID used to store info for an association group */
function getGroupInfoValueID(endpointIndex: number, groupId: number): ValueID {
return {
commandClass: CommandClasses["Association Group Information"],
endpoint: endpointIndex,
property: "info",
propertyKey: groupId,
};
}
/** Returns the ValueID used to store info for an association group */
function getIssuedCommandsValueID(
endpointIndex: number,
groupId: number,
): ValueID {
return {
commandClass: CommandClasses["Association Group Information"],
endpoint: endpointIndex,
property: "issuedCommands",
propertyKey: groupId,
};
}
function getHasDynamicInfoValueID(endpointIndex: number): ValueID {
return {
commandClass: CommandClasses["Association Group Information"],
endpoint: endpointIndex,
property: "hasDynamicInfo",
};
}
@API(CommandClasses["Association Group Information"])
export class AssociationGroupInfoCCAPI extends PhysicalCCAPI {
public supportsCommand(cmd: AssociationGroupInfoCommand): Maybe<boolean> {
switch (cmd) {
case AssociationGroupInfoCommand.NameGet:
case AssociationGroupInfoCommand.InfoGet:
case AssociationGroupInfoCommand.CommandListGet:
return true; // This is mandatory
}
return super.supportsCommand(cmd);
}
public async getGroupName(groupId: number): Promise<string | undefined> {
this.assertSupportsCommand(
AssociationGroupInfoCommand,
AssociationGroupInfoCommand.NameGet,
);
const cc = new AssociationGroupInfoCCNameGet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
groupId,
});
const response =
await this.driver.sendCommand<AssociationGroupInfoCCNameReport>(
cc,
this.commandOptions,
);
if (response) return response.name;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async getGroupInfo(groupId: number, refreshCache: boolean = false) {
this.assertSupportsCommand(
AssociationGroupInfoCommand,
AssociationGroupInfoCommand.InfoGet,
);
const cc = new AssociationGroupInfoCCInfoGet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
groupId,
refreshCache,
});
const response =
await this.driver.sendCommand<AssociationGroupInfoCCInfoReport>(
cc,
this.commandOptions,
);
// SDS13782 says: If List Mode is set to 0, the Group Count field MUST be set to 1.
// But that's not always the case. Apparently some endpoints return 0 groups
// although they support AGI CC
if (response && response.groups.length > 0) {
const { groupId: _, ...info } = response.groups[0];
return {
hasDynamicInfo: response.hasDynamicInfo,
...info,
};
}
}
public async getCommands(
groupId: number,
allowCache: boolean = true,
): Promise<
AssociationGroupInfoCCCommandListReport["commands"] | undefined
> {
this.assertSupportsCommand(
AssociationGroupInfoCommand,
AssociationGroupInfoCommand.CommandListGet,
);
const cc = new AssociationGroupInfoCCCommandListGet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
groupId,
allowCache,
});
const response =
await this.driver.sendCommand<AssociationGroupInfoCCCommandListReport>(
cc,
this.commandOptions,
);
if (response) return response.commands;
}
}
@commandClass(CommandClasses["Association Group Information"])
@implementedVersion(3)
export class AssociationGroupInfoCC extends CommandClass {
declare ccCommand: AssociationGroupInfoCommand;
public constructor(driver: Driver, options: CommandClassOptions) {
super(driver, options);
this.registerValue(getGroupNameValueID(0, 0).property, true);
this.registerValue(getGroupInfoValueID(0, 0).property, true);
}
public determineRequiredCCInterviews(): readonly CommandClasses[] {
// AssociationCC must be interviewed after Z-Wave+ if that is supported
return [
...super.determineRequiredCCInterviews(),
CommandClasses.Association,
CommandClasses["Multi Channel Association"],
];
}
/** Returns the name of an association group */
public getGroupNameCached(groupId: number): string | undefined {
return this.getValueDB().getValue(
getGroupNameValueID(this.endpointIndex, groupId),
);
}
/** Returns the association profile for an association group */
public getGroupProfileCached(
groupId: number,
): AssociationGroupInfoProfile | undefined {
return this.getValueDB().getValue<{
profile: AssociationGroupInfoProfile;
}>(getGroupInfoValueID(this.endpointIndex, groupId))?.profile;
}
/** Returns the dictionary of all commands issued by the given association group */
public getIssuedCommandsCached(
groupId: number,
): ReadonlyMap<CommandClasses, readonly number[]> | undefined {
return this.getValueDB().getValue(
getIssuedCommandsValueID(this.endpointIndex, groupId),
);
}
public findGroupsForIssuedCommand(
ccId: CommandClasses,
command: number,
): number[] {
const ret: number[] = [];
const associationGroupCount = this.getAssociationGroupCountCached();
for (let groupId = 1; groupId <= associationGroupCount; groupId++) {
// Scan the issued commands of all groups if there's a match
const issuedCommands = this.getIssuedCommandsCached(groupId);
if (!issuedCommands) continue;
if (
issuedCommands.has(ccId) &&
issuedCommands.get(ccId)!.includes(command)
) {
ret.push(groupId);
continue;
}
}
return ret;
}
private getAssociationGroupCountCached(): number {
const endpoint = this.getEndpoint()!;
// The association group count is either determined by the
// Association CC or the Multi Channel Association CC
// First query the Multi Channel Association CC
return (
endpoint
.createCCInstanceUnsafe<MultiChannelAssociationCC>(
CommandClasses["Multi Channel Association"],
)
?.getGroupCountCached() ||
// Then the Association CC
endpoint
.createCCInstanceUnsafe<AssociationCC>(
CommandClasses.Association,
)
?.getGroupCountCached() ||
// And fall back to 0
0
);
}
public async interview(): Promise<void> {
const node = this.getNode()!;
const endpoint = this.getEndpoint()!;
const api = endpoint.commandClasses[
"Association Group Information"
].withOptions({ priority: MessagePriority.NodeQuery });
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: `Interviewing ${this.ccName}...`,
direction: "none",
});
const associationGroupCount = this.getAssociationGroupCountCached();
for (let groupId = 1; groupId <= associationGroupCount; groupId++) {
// First get the group's name
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: `Association group #${groupId}: Querying name...`,
direction: "outbound",
});
const name = await api.getGroupName(groupId);
if (name) {
const logMessage = `Association group #${groupId} has name "${name}"`;
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: logMessage,
direction: "inbound",
});
}
// Then the command list
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: `Association group #${groupId}: Querying command list...`,
direction: "outbound",
});
await api.getCommands(groupId);
// Not sure how to log this
}
// Finally query each group for its information
await this.refreshValues();
// Remember that the interview is complete
this.interviewComplete = true;
}
public async refreshValues(): Promise<void> {
const node = this.getNode()!;
const endpoint = this.getEndpoint()!;
const api = endpoint.commandClasses[
"Association Group Information"
].withOptions({ priority: MessagePriority.NodeQuery });
// Query the information for each group (this is the only thing that could be dynamic)
const associationGroupCount = this.getAssociationGroupCountCached();
const hasDynamicInfo = this.getValueDB().getValue(
getHasDynamicInfoValueID(this.endpointIndex),
);
for (let groupId = 1; groupId <= associationGroupCount; groupId++) {
// Then its information
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: `Association group #${groupId}: Querying info...`,
direction: "outbound",
});
const info = await api.getGroupInfo(groupId, !!hasDynamicInfo);
if (info) {
const logMessage = `Received info for association group #${groupId}:
info is dynamic: ${info.hasDynamicInfo}
profile: ${getEnumMemberName(
AssociationGroupInfoProfile,
info.profile,
)}`;
this.driver.controllerLog.logNode(node.id, {
endpoint: this.endpointIndex,
message: logMessage,
direction: "inbound",
});
}
}
}
}
@CCCommand(AssociationGroupInfoCommand.NameReport)
export class AssociationGroupInfoCCNameReport extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options: CommandClassDeserializationOptions,
) {
super(driver, options);
validatePayload(this.payload.length >= 2);
this.groupId = this.payload[0];
const nameLength = this.payload[1];
validatePayload(this.payload.length >= 2 + nameLength);
// The specs don't allow 0-terminated string, but some devices use them
// So we need to cut them off
this.name = cpp2js(
this.payload.slice(2, 2 + nameLength).toString("utf8"),
);
this.persistValues();
}
public persistValues(): boolean {
const valueId = getGroupNameValueID(this.endpointIndex, this.groupId);
this.getValueDB().setValue(valueId, this.name);
return true;
}
public readonly groupId: number;
public readonly name: string;
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"group id": this.groupId,
name: this.name,
},
};
}
}
interface AssociationGroupInfoCCNameGetOptions extends CCCommandOptions {
groupId: number;
}
@CCCommand(AssociationGroupInfoCommand.NameGet)
@expectedCCResponse(AssociationGroupInfoCCNameReport)
export class AssociationGroupInfoCCNameGet extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| AssociationGroupInfoCCNameGetOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
// TODO: Deserialize payload
throw new ZWaveError(
`${this.constructor.name}: deserialization not implemented`,
ZWaveErrorCodes.Deserialization_NotImplemented,
);
} else {
this.groupId = options.groupId;
}
}
public groupId: number;
public serialize(): Buffer {
this.payload = Buffer.from([this.groupId]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: { "group id": this.groupId },
};
}
}
export interface AssociationGroupInfo {
groupId: number;
mode: number;
profile: number;
eventCode: number;
}
@CCCommand(AssociationGroupInfoCommand.InfoReport)
export class AssociationGroupInfoCCInfoReport extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options: CommandClassDeserializationOptions,
) {
super(driver, options);
validatePayload(this.payload.length >= 1);
this.isListMode = !!(this.payload[0] & 0b1000_0000);
this.hasDynamicInfo = !!(this.payload[0] & 0b0100_0000);
const groupCount = this.payload[0] & 0b0011_1111;
// each group requires 7 bytes of payload
validatePayload(this.payload.length >= 1 + groupCount * 7);
const _groups: AssociationGroupInfo[] = [];
for (let i = 0; i < groupCount; i++) {
const offset = 1 + i * 7;
// Parse the payload
const groupBytes = this.payload.slice(offset, offset + 7);
const groupId = groupBytes[0];
const mode = 0; //groupBytes[1];
const profile = groupBytes.readUInt16BE(2);
const eventCode = 0; // groupBytes.readUInt16BE(5);
_groups.push({ groupId, mode, profile, eventCode });
}
this.groups = _groups;
this.persistValues();
}
public persistValues(): boolean {
if (!super.persistValues()) return false;
for (const group of this.groups) {
const { groupId, mode, profile, eventCode } = group;
const valueId = getGroupInfoValueID(this.endpointIndex, groupId);
this.getValueDB().setValue(valueId, {
mode,
profile,
eventCode,
});
}
return true;
}
public readonly isListMode: boolean;
@ccValue({ internal: true })
public readonly hasDynamicInfo: boolean;
public readonly groups: readonly AssociationGroupInfo[];
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"is list mode": this.isListMode,
"has dynamic info": this.hasDynamicInfo,
groups: `${this.groups
.map(
(g) => `
· Group #${g.groupId}
mode: ${g.mode}
profile: ${g.profile}
event code: ${g.eventCode}`,
)
.join("")}`,
},
};
}
}
type AssociationGroupInfoCCInfoGetOptions = CCCommandOptions & {
refreshCache: boolean;
} & (
| {
listMode: boolean;
}
| {
groupId: number;
}
);
@CCCommand(AssociationGroupInfoCommand.InfoGet)
@expectedCCResponse(AssociationGroupInfoCCInfoReport)
export class AssociationGroupInfoCCInfoGet extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| AssociationGroupInfoCCInfoGetOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
// TODO: Deserialize payload
throw new ZWaveError(
`${this.constructor.name}: deserialization not implemented`,
ZWaveErrorCodes.Deserialization_NotImplemented,
);
} else {
this.refreshCache = options.refreshCache;
if ("listMode" in options) this.listMode = options.listMode;
if ("groupId" in options) this.groupId = options.groupId;
}
}
public refreshCache: boolean;
public listMode?: boolean;
public groupId?: number;
public serialize(): Buffer {
const isListMode = this.listMode === true;
const optionByte =
(this.refreshCache ? 0b1000_0000 : 0) |
(isListMode ? 0b0100_0000 : 0);
this.payload = Buffer.from([
optionByte,
isListMode ? 0 : this.groupId!,
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
const message: MessageRecord = {};
if (this.groupId != undefined) {
message["group id"] = this.groupId;
}
if (this.listMode != undefined) {
message["list mode"] = this.listMode;
}
message["refresh cache"] = this.refreshCache;
return {
...super.toLogEntry(),
message,
};
}
}
@CCCommand(AssociationGroupInfoCommand.CommandListReport)
export class AssociationGroupInfoCCCommandListReport extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options: CommandClassDeserializationOptions,
) {
super(driver, options);
validatePayload(this.payload.length >= 2);
const groupId = this.payload[0];
const listLength = this.payload[1];
validatePayload(this.payload.length >= 2 + listLength);
const listBytes = this.payload.slice(2, 2 + listLength);
// Parse all CC ids and commands
let offset = 0;
const commands = new Map<CommandClasses, number[]>();
while (offset < listLength) {
const { ccId, bytesRead } = parseCCId(listBytes, offset);
const command = listBytes[offset + bytesRead];
if (!commands.has(ccId)) commands.set(ccId, []);
commands.get(ccId)!.push(command);
offset += bytesRead + 1;
}
this.issuedCommands = [groupId, commands];
this.persistValues();
}
@ccKeyValuePair({ internal: true })
private issuedCommands: [number, this["commands"]];
public get groupId(): number {
return this.issuedCommands[0];
}
public get commands(): ReadonlyMap<CommandClasses, readonly number[]> {
return this.issuedCommands[1];
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"group id": this.groupId,
commands: `${[...this.commands]
.map(([cc, cmds]) => {
return `\n· ${getCCName(cc)}: ${cmds
.map((cmd) => num2hex(cmd))
.join(", ")}`;
})
.join("")}`,
},
};
}
}
interface AssociationGroupInfoCCCommandListGetOptions extends CCCommandOptions {
allowCache: boolean;
groupId: number;
}
@CCCommand(AssociationGroupInfoCommand.CommandListGet)
@expectedCCResponse(AssociationGroupInfoCCCommandListReport)
export class AssociationGroupInfoCCCommandListGet extends AssociationGroupInfoCC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| AssociationGroupInfoCCCommandListGetOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
// TODO: Deserialize payload
throw new ZWaveError(
`${this.constructor.name}: deserialization not implemented`,
ZWaveErrorCodes.Deserialization_NotImplemented,
);
} else {
this.allowCache = options.allowCache;
this.groupId = options.groupId;
}
}
public allowCache: boolean;
public groupId: number;
public serialize(): Buffer {
this.payload = Buffer.from([
this.allowCache ? 0b1000_0000 : 0,
this.groupId,
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"group id": this.groupId,
"allow cache": this.allowCache,
},
};
}
} | the_stack |
import * as dom from 'vs/base/browser/dom';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { Orientation } from 'vs/base/browser/ui/sash/sash';
import { Sizing, SplitView } from 'vs/base/browser/ui/splitview/splitview';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { KeyCode } from 'vs/base/common/keyCodes';
import { DisposableStore, dispose, IDisposable, IReference } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { basenameOrAuthority, dirname } from 'vs/base/common/resources';
import 'vs/css!./referencesWidget';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { IRange, Range } from 'vs/editor/common/core/range';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { IModelDeltaDecoration, TrackedRangeStickiness } from 'vs/editor/common/model';
import { ModelDecorationOptions, TextModel } from 'vs/editor/common/model/textModel';
import { Location } from 'vs/editor/common/modes';
import { ILanguageConfigurationService } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { AccessibilityProvider, DataSource, Delegate, FileReferencesRenderer, IdentityProvider, OneReferenceRenderer, StringRepresentationProvider, TreeElement } from 'vs/editor/contrib/gotoSymbol/peek/referencesTree';
import * as peekView from 'vs/editor/contrib/peekView/peekView';
import * as nls from 'vs/nls';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ILabelService } from 'vs/platform/label/common/label';
import { IWorkbenchAsyncDataTreeOptions, WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService';
import { activeContrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { IColorTheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo';
import { FileReferences, OneReference, ReferencesModel } from '../referencesModel';
class DecorationsManager implements IDisposable {
private static readonly DecorationOptions = ModelDecorationOptions.register({
description: 'reference-decoration',
stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
className: 'reference-decoration'
});
private _decorations = new Map<string, OneReference>();
private _decorationIgnoreSet = new Set<string>();
private readonly _callOnDispose = new DisposableStore();
private readonly _callOnModelChange = new DisposableStore();
constructor(private _editor: ICodeEditor, private _model: ReferencesModel) {
this._callOnDispose.add(this._editor.onDidChangeModel(() => this._onModelChanged()));
this._onModelChanged();
}
dispose(): void {
this._callOnModelChange.dispose();
this._callOnDispose.dispose();
this.removeDecorations();
}
private _onModelChanged(): void {
this._callOnModelChange.clear();
const model = this._editor.getModel();
if (!model) {
return;
}
for (let ref of this._model.references) {
if (ref.uri.toString() === model.uri.toString()) {
this._addDecorations(ref.parent);
return;
}
}
}
private _addDecorations(reference: FileReferences): void {
if (!this._editor.hasModel()) {
return;
}
this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(() => this._onDecorationChanged()));
const newDecorations: IModelDeltaDecoration[] = [];
const newDecorationsActualIndex: number[] = [];
for (let i = 0, len = reference.children.length; i < len; i++) {
let oneReference = reference.children[i];
if (this._decorationIgnoreSet.has(oneReference.id)) {
continue;
}
if (oneReference.uri.toString() !== this._editor.getModel().uri.toString()) {
continue;
}
newDecorations.push({
range: oneReference.range,
options: DecorationsManager.DecorationOptions
});
newDecorationsActualIndex.push(i);
}
const decorations = this._editor.deltaDecorations([], newDecorations);
for (let i = 0; i < decorations.length; i++) {
this._decorations.set(decorations[i], reference.children[newDecorationsActualIndex[i]]);
}
}
private _onDecorationChanged(): void {
const toRemove: string[] = [];
const model = this._editor.getModel();
if (!model) {
return;
}
for (let [decorationId, reference] of this._decorations) {
const newRange = model.getDecorationRange(decorationId);
if (!newRange) {
continue;
}
let ignore = false;
if (Range.equalsRange(newRange, reference.range)) {
continue;
}
if (Range.spansMultipleLines(newRange)) {
ignore = true;
} else {
const lineLength = reference.range.endColumn - reference.range.startColumn;
const newLineLength = newRange.endColumn - newRange.startColumn;
if (lineLength !== newLineLength) {
ignore = true;
}
}
if (ignore) {
this._decorationIgnoreSet.add(reference.id);
toRemove.push(decorationId);
} else {
reference.range = newRange;
}
}
for (let i = 0, len = toRemove.length; i < len; i++) {
this._decorations.delete(toRemove[i]);
}
this._editor.deltaDecorations(toRemove, []);
}
removeDecorations(): void {
this._editor.deltaDecorations([...this._decorations.keys()], []);
this._decorations.clear();
}
}
export class LayoutData {
ratio: number = 0.7;
heightInLines: number = 18;
static fromJSON(raw: string): LayoutData {
let ratio: number | undefined;
let heightInLines: number | undefined;
try {
const data = <LayoutData>JSON.parse(raw);
ratio = data.ratio;
heightInLines = data.heightInLines;
} catch {
//
}
return {
ratio: ratio || 0.7,
heightInLines: heightInLines || 18
};
}
}
export interface SelectionEvent {
readonly kind: 'goto' | 'show' | 'side' | 'open';
readonly source: 'editor' | 'tree' | 'title';
readonly element?: Location;
}
class ReferencesTree extends WorkbenchAsyncDataTree<ReferencesModel | FileReferences, TreeElement, FuzzyScore> { }
/**
* ZoneWidget that is shown inside the editor
*/
export class ReferenceWidget extends peekView.PeekViewWidget {
private _model?: ReferencesModel;
private _decorationsManager?: DecorationsManager;
private readonly _disposeOnNewModel = new DisposableStore();
private readonly _callOnDispose = new DisposableStore();
private readonly _onDidSelectReference = new Emitter<SelectionEvent>();
readonly onDidSelectReference = this._onDidSelectReference.event;
private _tree!: ReferencesTree;
private _treeContainer!: HTMLElement;
private _splitView!: SplitView;
private _preview!: ICodeEditor;
private _previewModelReference!: IReference<ITextEditorModel>;
private _previewNotAvailableMessage!: TextModel;
private _previewContainer!: HTMLElement;
private _messageContainer!: HTMLElement;
private _dim = new dom.Dimension(0, 0);
constructor(
editor: ICodeEditor,
private _defaultTreeKeyboardSupport: boolean,
public layoutData: LayoutData,
@IThemeService themeService: IThemeService,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@peekView.IPeekViewService private readonly _peekViewService: peekView.IPeekViewService,
@ILabelService private readonly _uriLabel: ILabelService,
@IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
@IKeybindingService private readonly _keybindingService: IKeybindingService,
@IModeService private readonly _modeService: IModeService,
@ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService,
) {
super(editor, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, _instantiationService);
this._applyTheme(themeService.getColorTheme());
this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
this._peekViewService.addExclusiveWidget(editor, this);
this.create();
}
override dispose(): void {
this.setModel(undefined);
this._callOnDispose.dispose();
this._disposeOnNewModel.dispose();
dispose(this._preview);
dispose(this._previewNotAvailableMessage);
dispose(this._tree);
dispose(this._previewModelReference);
this._splitView.dispose();
super.dispose();
}
private _applyTheme(theme: IColorTheme) {
const borderColor = theme.getColor(peekView.peekViewBorder) || Color.transparent;
this.style({
arrowColor: borderColor,
frameColor: borderColor,
headerBackgroundColor: theme.getColor(peekView.peekViewTitleBackground) || Color.transparent,
primaryHeadingColor: theme.getColor(peekView.peekViewTitleForeground),
secondaryHeadingColor: theme.getColor(peekView.peekViewTitleInfoForeground)
});
}
override show(where: IRange) {
this.editor.revealRangeInCenterIfOutsideViewport(where, ScrollType.Smooth);
super.show(where, this.layoutData.heightInLines || 18);
}
focusOnReferenceTree(): void {
this._tree.domFocus();
}
focusOnPreviewEditor(): void {
this._preview.focus();
}
isPreviewEditorFocused(): boolean {
return this._preview.hasTextFocus();
}
protected override _onTitleClick(e: IMouseEvent): void {
if (this._preview && this._preview.getModel()) {
this._onDidSelectReference.fire({
element: this._getFocusedReference(),
kind: e.ctrlKey || e.metaKey || e.altKey ? 'side' : 'open',
source: 'title'
});
}
}
protected _fillBody(containerElement: HTMLElement): void {
this.setCssClass('reference-zone-widget');
// message pane
this._messageContainer = dom.append(containerElement, dom.$('div.messages'));
dom.hide(this._messageContainer);
this._splitView = new SplitView(containerElement, { orientation: Orientation.HORIZONTAL });
// editor
this._previewContainer = dom.append(containerElement, dom.$('div.preview.inline'));
let options: IEditorOptions = {
scrollBeyondLastLine: false,
scrollbar: {
verticalScrollbarSize: 14,
horizontal: 'auto',
useShadows: true,
verticalHasArrows: false,
horizontalHasArrows: false,
alwaysConsumeMouseWheel: false
},
overviewRulerLanes: 2,
fixedOverflowWidgets: true,
minimap: {
enabled: false
}
};
this._preview = this._instantiationService.createInstance(EmbeddedCodeEditorWidget, this._previewContainer, options, this.editor);
dom.hide(this._previewContainer);
this._previewNotAvailableMessage = new TextModel(nls.localize('missingPreviewMessage', "no preview available"), TextModel.DEFAULT_CREATION_OPTIONS, null, null, this._undoRedoService, this._modeService, this._languageConfigurationService);
// tree
this._treeContainer = dom.append(containerElement, dom.$('div.ref-tree.inline'));
const treeOptions: IWorkbenchAsyncDataTreeOptions<TreeElement, FuzzyScore> = {
keyboardSupport: this._defaultTreeKeyboardSupport,
accessibilityProvider: new AccessibilityProvider(),
keyboardNavigationLabelProvider: this._instantiationService.createInstance(StringRepresentationProvider),
identityProvider: new IdentityProvider(),
openOnSingleClick: true,
selectionNavigation: true,
overrideStyles: {
listBackground: peekView.peekViewResultsBackground
}
};
if (this._defaultTreeKeyboardSupport) {
// the tree will consume `Escape` and prevent the widget from closing
this._callOnDispose.add(dom.addStandardDisposableListener(this._treeContainer, 'keydown', (e) => {
if (e.equals(KeyCode.Escape)) {
this._keybindingService.dispatchEvent(e, e.target);
e.stopPropagation();
}
}, true));
}
this._tree = this._instantiationService.createInstance(
ReferencesTree,
'ReferencesWidget',
this._treeContainer,
new Delegate(),
[
this._instantiationService.createInstance(FileReferencesRenderer),
this._instantiationService.createInstance(OneReferenceRenderer),
],
this._instantiationService.createInstance(DataSource),
treeOptions,
);
// split stuff
this._splitView.addView({
onDidChange: Event.None,
element: this._previewContainer,
minimumSize: 200,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
this._preview.layout({ height: this._dim.height, width });
}
}, Sizing.Distribute);
this._splitView.addView({
onDidChange: Event.None,
element: this._treeContainer,
minimumSize: 100,
maximumSize: Number.MAX_VALUE,
layout: (width) => {
this._treeContainer.style.height = `${this._dim.height}px`;
this._treeContainer.style.width = `${width}px`;
this._tree.layout(this._dim.height, width);
}
}, Sizing.Distribute);
this._disposables.add(this._splitView.onDidSashChange(() => {
if (this._dim.width) {
this.layoutData.ratio = this._splitView.getViewSize(0) / this._dim.width;
}
}, undefined));
// listen on selection and focus
let onEvent = (element: any, kind: 'show' | 'goto' | 'side') => {
if (element instanceof OneReference) {
if (kind === 'show') {
this._revealReference(element, false);
}
this._onDidSelectReference.fire({ element, kind, source: 'tree' });
}
};
this._tree.onDidOpen(e => {
if (e.sideBySide) {
onEvent(e.element, 'side');
} else if (e.editorOptions.pinned) {
onEvent(e.element, 'goto');
} else {
onEvent(e.element, 'show');
}
});
dom.hide(this._treeContainer);
}
protected override _onWidth(width: number) {
if (this._dim) {
this._doLayoutBody(this._dim.height, width);
}
}
protected override _doLayoutBody(heightInPixel: number, widthInPixel: number): void {
super._doLayoutBody(heightInPixel, widthInPixel);
this._dim = new dom.Dimension(widthInPixel, heightInPixel);
this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines;
this._splitView.layout(widthInPixel);
this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio);
}
setSelection(selection: OneReference): Promise<any> {
return this._revealReference(selection, true).then(() => {
if (!this._model) {
// disposed
return;
}
// show in tree
this._tree.setSelection([selection]);
this._tree.setFocus([selection]);
});
}
setModel(newModel: ReferencesModel | undefined): Promise<any> {
// clean up
this._disposeOnNewModel.clear();
this._model = newModel;
if (this._model) {
return this._onNewModel();
}
return Promise.resolve();
}
private _onNewModel(): Promise<any> {
if (!this._model) {
return Promise.resolve(undefined);
}
if (this._model.isEmpty) {
this.setTitle('');
this._messageContainer.innerText = nls.localize('noResults', "No results");
dom.show(this._messageContainer);
return Promise.resolve(undefined);
}
dom.hide(this._messageContainer);
this._decorationsManager = new DecorationsManager(this._preview, this._model);
this._disposeOnNewModel.add(this._decorationsManager);
// listen on model changes
this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange(reference => this._tree.rerender(reference)));
// listen on editor
this._disposeOnNewModel.add(this._preview.onMouseDown(e => {
const { event, target } = e;
if (event.detail !== 2) {
return;
}
const element = this._getFocusedReference();
if (!element) {
return;
}
this._onDidSelectReference.fire({
element: { uri: element.uri, range: target.range! },
kind: (event.ctrlKey || event.metaKey || event.altKey) ? 'side' : 'open',
source: 'editor'
});
}));
// make sure things are rendered
this.container!.classList.add('results-loaded');
dom.show(this._treeContainer);
dom.show(this._previewContainer);
this._splitView.layout(this._dim.width);
this.focusOnReferenceTree();
// pick input and a reference to begin with
return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model);
}
private _getFocusedReference(): OneReference | undefined {
const [element] = this._tree.getFocus();
if (element instanceof OneReference) {
return element;
} else if (element instanceof FileReferences) {
if (element.children.length > 0) {
return element.children[0];
}
}
return undefined;
}
async revealReference(reference: OneReference): Promise<void> {
await this._revealReference(reference, false);
this._onDidSelectReference.fire({ element: reference, kind: 'goto', source: 'tree' });
}
private _revealedReference?: OneReference;
private async _revealReference(reference: OneReference, revealParent: boolean): Promise<void> {
// check if there is anything to do...
if (this._revealedReference === reference) {
return;
}
this._revealedReference = reference;
// Update widget header
if (reference.uri.scheme !== Schemas.inMemory) {
this.setTitle(basenameOrAuthority(reference.uri), this._uriLabel.getUriLabel(dirname(reference.uri)));
} else {
this.setTitle(nls.localize('peekView.alternateTitle', "References"));
}
const promise = this._textModelResolverService.createModelReference(reference.uri);
if (this._tree.getInput() === reference.parent) {
this._tree.reveal(reference);
} else {
if (revealParent) {
this._tree.reveal(reference.parent);
}
await this._tree.expand(reference.parent);
this._tree.reveal(reference);
}
const ref = await promise;
if (!this._model) {
// disposed
ref.dispose();
return;
}
dispose(this._previewModelReference);
// show in editor
const model = ref.object;
if (model) {
const scrollType = this._preview.getModel() === model.textEditorModel ? ScrollType.Smooth : ScrollType.Immediate;
const sel = Range.lift(reference.range).collapseToStart();
this._previewModelReference = ref;
this._preview.setModel(model.textEditorModel);
this._preview.setSelection(sel);
this._preview.revealRangeInCenter(sel, scrollType);
} else {
this._preview.setModel(this._previewNotAvailableMessage);
ref.dispose();
}
}
}
// theming
registerThemingParticipant((theme, collector) => {
const findMatchHighlightColor = theme.getColor(peekView.peekViewResultsMatchHighlight);
if (findMatchHighlightColor) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { background-color: ${findMatchHighlightColor}; }`);
}
const referenceHighlightColor = theme.getColor(peekView.peekViewEditorMatchHighlight);
if (referenceHighlightColor) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .reference-decoration { background-color: ${referenceHighlightColor}; }`);
}
const referenceHighlightBorder = theme.getColor(peekView.peekViewEditorMatchHighlightBorder);
if (referenceHighlightBorder) {
collector.addRule(`.monaco-editor .reference-zone-widget .preview .reference-decoration { border: 2px solid ${referenceHighlightBorder}; box-sizing: border-box; }`);
}
const hcOutline = theme.getColor(activeContrastBorder);
if (hcOutline) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .referenceMatch .highlight { border: 1px dotted ${hcOutline}; box-sizing: border-box; }`);
}
const resultsBackground = theme.getColor(peekView.peekViewResultsBackground);
if (resultsBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree { background-color: ${resultsBackground}; }`);
}
const resultsMatchForeground = theme.getColor(peekView.peekViewResultsMatchForeground);
if (resultsMatchForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree { color: ${resultsMatchForeground}; }`);
}
const resultsFileForeground = theme.getColor(peekView.peekViewResultsFileForeground);
if (resultsFileForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .reference-file { color: ${resultsFileForeground}; }`);
}
const resultsSelectedBackground = theme.getColor(peekView.peekViewResultsSelectionBackground);
if (resultsSelectedBackground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { background-color: ${resultsSelectedBackground}; }`);
}
const resultsSelectedForeground = theme.getColor(peekView.peekViewResultsSelectionForeground);
if (resultsSelectedForeground) {
collector.addRule(`.monaco-editor .reference-zone-widget .ref-tree .monaco-list:focus .monaco-list-rows > .monaco-list-row.selected:not(.highlighted) { color: ${resultsSelectedForeground} !important; }`);
}
const editorBackground = theme.getColor(peekView.peekViewEditorBackground);
if (editorBackground) {
collector.addRule(
`.monaco-editor .reference-zone-widget .preview .monaco-editor .monaco-editor-background,` +
`.monaco-editor .reference-zone-widget .preview .monaco-editor .inputarea.ime-input {` +
` background-color: ${editorBackground};` +
`}`);
}
const editorGutterBackground = theme.getColor(peekView.peekViewEditorGutterBackground);
if (editorGutterBackground) {
collector.addRule(
`.monaco-editor .reference-zone-widget .preview .monaco-editor .margin {` +
` background-color: ${editorGutterBackground};` +
`}`);
}
}); | the_stack |
import * as BigQuery from "@google-cloud/bigquery";
import * as async from "async";
export class BigQueryStore {
public projectId: string;
public dataSetId: string;
public revisionsTable: string;
public revertedTable: string;
public cronLogs: string;
public bigquery: any;
constructor(config) {
this.projectId = config.bigQuery.projectId;
this.dataSetId = config.bigQuery.dataSetId;
this.revisionsTable = config.bigQuery.revisionsTable;
this.revertedTable = config.bigQuery.revertedTable;
this.cronLogs = config.bigQuery.cronLogs;
this.bigquery = BigQuery({
keyFilename: config.gcloudKey,
projectId: this.projectId,
});
}
public validateSchema(row) {
const schemaStructure = {
attack: true,
author: false,
namespace: true,
page: true,
page_id: true,
// revision_text: true,
revision_id: true,
// revert_id: true,
sha1: true,
timestamp: true,
};
let isInvalidValid = false;
Object.keys(schemaStructure).forEach((field) => {
if (row[field] === null || row[field] === "" || row[field] === undefined) {
if (schemaStructure[field]) {
isInvalidValid = true;
}
}
});
return isInvalidValid;
}
public addCommentData(rows, cb) {
const dataset = this.bigquery.dataset(this.dataSetId);
const table = dataset.table(this.revisionsTable);
rows = rows.filter((d) => {
if (this.validateSchema(d)) {
console.log("Invalid data : ", d);
return false;
} else {
return true;
}
});
// Inserts data into a table
table.insert(rows)
.then((insertErrors, data) => {
console.log(rows.length + " rows inserted.");
cb(null, rows.length + " rows inserted.");
return insertErrors;
}).catch((err) => {
console.log(JSON.stringify(err));
cb(err);
});
}
public makeQuery(query, cb) {
const options = {
query,
useLegacySql: false, // Use standard SQL syntax for queries.
};
let job;
return this.bigquery
.startQuery(options)
.then((results) => {
job = results[0];
// console.log(`Job ${job.id} started.`);
return job.promise();
})
.then(() => {
// console.log(`Job ${job.id} completed.`);
return job.getQueryResults();
})
.then((results) => {
const rows = results[0];
cb(null, rows);
})
.catch((err) => {
console.error("ERROR:", err);
cb(err);
});
}
public flagReverted(startNextJob) {
// Query options list: https://cloud.google.com/bigquery/docs/reference/v2/jobs/query
const that = this;
const revertedQueries = {
addRevertedRevisions: (rows, cb) => {
if (rows.length === 0) {
cb(null, []);
return;
}
const revertedRevisions = [];
const revisionId = {};
rows.forEach((row) => {
row.forEach((rev) => {
if (!revisionId[rev.revision_id]) {
revertedRevisions.push({
revert_id: String(rev.revert_id),
revision_id: String(rev.revision_id),
timestamp: rev.timestamp.value,
});
revisionId[rev.revision_id] = true;
}
});
});
const dataset = this.bigquery.dataset(this.dataSetId);
const table = dataset.table(this.revertedTable);
// Inserts data into a table
table.insert(revertedRevisions)
.then((insertErrors, data) => {
console.log(revertedRevisions.length + " rows inserted.");
cb(null, revertedRevisions.length + " rows inserted.");
return insertErrors;
}).catch((err) => {
console.log(JSON.stringify(err));
cb(err);
});
},
getAllRepeatedSha1s: () => {
const tComments = this.dataSetId + "." + this.revisionsTable;
const tReverted = this.dataSetId + "." + this.revertedTable;
return `SELECT
t_comments.page_id AS page_id,
t_comments.sha1 AS sha1,
COUNT(*) AS count
FROM
${tComments} as t_comments
LEFT JOIN
${tReverted} as t_reverted
ON
t_reverted.revision_id = t_comments.revision_id
WHERE
t_reverted.revision_id IS NULL
AND t_comments.revision_id IS NOT NULL
AND t_comments.sha1 IS NOT NULL
GROUP BY
sha1,
page_id
HAVING
COUNT(*) > 1
ORDER BY
count DESC`;
},
// markAllEntriesAsRevertedBetween: (pageId, firstOccerence, lastOccerence) => {
// return `UPDATE toxic_comments_test.comments_test_copy SET is_reverted = true
// WHERE page_id='${pageId}' AND
// timestamp >= '${firstOccerence}' AND timestamp < '${lastOccerence}'`;
// },
getAllRevertedRevisions: (pageId, firstOccerence, lastOccerence) => {
const tComments = this.dataSetId + "." + this.revisionsTable;
if (firstOccerence === lastOccerence) {
return `SELECT timestamp,revision_id,revert_id FROM ${tComments} WHERE page_id='${pageId}' AND
timestamp = '${firstOccerence}'`;
}
return `SELECT timestamp,revision_id,revert_id FROM ${tComments} WHERE page_id='${pageId}' AND
timestamp >= '${firstOccerence}' AND timestamp < '${lastOccerence}'`;
},
getAllRowsWithSameSha1s: (pageId, sha1) => {
const tComments = this.dataSetId + "." + this.revisionsTable;
return `SELECT page_id,sha1,timestamp FROM ${tComments}
WHERE page_id='${pageId}' AND sha1='${sha1}'
ORDER BY timestamp ASC`;
},
};
function getAllRepeatedSha1s(cb) {
that.makeQuery(revertedQueries.getAllRepeatedSha1s(), function (err, rows) {
if (!err) {
cb(null, rows);
} else {
cb(err);
}
});
}
function getAllRowsWithSameSha1s(shaRows, cb) {
console.log("Found " + shaRows.length + " repeated sha1 ....");
if (shaRows.length === 0) {
cb(null, []);
return;
}
const queryListGetAllRowsWithSameSha1s = shaRows.map((row) => {
const pageId = row.page_id;
const sha1 = row.sha1;
return revertedQueries.getAllRowsWithSameSha1s(pageId, sha1);
});
const queryFunctions = queryListGetAllRowsWithSameSha1s.map((query) => {
return (cbQueryFunctions) => {
that.makeQuery(query, (err, rows) => {
if (!err) {
const firstOccurrence = rows[0].timestamp.value;
const lastOccurrence = rows[rows.length - 1].timestamp.value;
const pageId = rows[0].page_id;
cbQueryFunctions(null, { rowsLength: rows.length, firstOccurrence, lastOccurrence, pageId });
} else {
cbQueryFunctions(err);
}
});
};
});
async.parallelLimit(queryFunctions, 10, (err, results) => {
if (err) {
cb(err);
return;
}
cb(null, results);
});
}
function getAllReverted(list, cb) {
if (list.length === 0) {
cb(null, []);
}
const queryList = list.map((row) => {
return revertedQueries.getAllRevertedRevisions(row.pageId, row.firstOccurrence, row.lastOccurrence);
});
const queryFunctions = queryList.map((query) => {
return (cb) => {
that.makeQuery(query, (err, rows) => {
if (!err) {
cb(null, rows);
} else {
cb(err);
}
});
};
});
async.series(queryFunctions, (err, results) => {
if (err) {
cb(err);
return;
}
cb(null, results);
});
}
async.waterfall([
getAllRepeatedSha1s,
getAllRowsWithSameSha1s,
getAllReverted,
revertedQueries.addRevertedRevisions,
], (err, result) => {
console.log("Done");
startNextJob(true);
});
}
public logStreamTask(options) {
const dataset = this.bigquery.dataset(this.dataSetId);
const table = dataset.table(this.cronLogs);
// Inserts data into a table
table.insert([{
cron_runtime: options.cron_runtime,
end_time: options.end_time,
rows_added: options.rows_added,
start_time: options.start_time,
timestamp: options.timestamp,
}]).then((insertErrors, data) => {
return insertErrors;
}).catch((err) => {
console.log(JSON.stringify(err));
});
}
public getMonthData(start, end, send) {
const tComments = this.dataSetId + "." + this.revisionsTable;
const tReveverted = this.dataSetId + "." + this.revertedTable;
const monthSt = new Date(start).toISOString();
const monthEnd = new Date(end).toISOString();
const toxicLimit = 0.75;
const getMonthsData = (cb) => {
const query = `SELECT timestamp,revision_text, attack, author, page, revision_id FROM ${tComments}
WHERE timestamp > '${monthSt}' AND timestamp < '${monthEnd}' AND attack >= ${toxicLimit}
ORDER BY timestamp ASC`;
this.makeQuery(query, (err, d) => {
cb(err, d);
});
};
const getMonthsNonToxicCount = (cb) => {
const query = ` SELECT count(revision_id) as count from ${tComments}
WHERE attack < ${toxicLimit} AND timestamp > '${monthSt}' AND timestamp < '${monthEnd}'`;
this.makeQuery(query, (err, d) => {
cb(err, d);
});
};
const getRevertedData = (cb) => {
const query = `SELECT t_reverted.revision_id as revision_id FROM ${tReveverted} as t_reverted
LEFT JOIN ${tComments} as t_scores ON t_scores.revision_id = t_reverted.revision_id
WHERE t_scores.timestamp > '${monthSt}' AND t_scores.timestamp < '${monthEnd}' AND t_scores.attack >= ${toxicLimit}
GROUP BY revision_id ORDER BY revision_id `;
this.makeQuery(query, (err, d) => {
cb(err, d);
});
};
async.parallel([
getMonthsData,
getRevertedData,
getMonthsNonToxicCount],
(err, result) => {
send(err, result);
});
}
public getCalendarData(send) {
const tComments = this.dataSetId + "." + this.revisionsTable;
const tReveverted = this.dataSetId + "." + this.revertedTable;
const toxicLimit = 0.75;
const getMonthsList = (cb) => {
const query = `SELECT EXTRACT(month FROM timestamp) as month, EXTRACT(year FROM timestamp) as year , COUNT (revision_id) as total,
COUNT( CASE WHEN attack >= ${toxicLimit} THEN 1 END ) as toxic
FROM ${tComments} GROUP BY month, year`;
this.makeQuery(query, cb);
};
const getRevertedCount = (cb) => {
const query = `SELECT EXTRACT(month FROM t_scores.timestamp) as month, EXTRACT(year FROM t_scores.timestamp) as year,
count(t_reverted.revision_id) as count
FROM ${tReveverted} as t_reverted
RIGHT JOIN ${tComments} as t_scores ON t_scores.revision_id = t_reverted.revision_id WHERE t_scores.attack >= ${toxicLimit}
GROUP BY month, year`;
this.makeQuery(query, cb);
};
async.parallel([
getMonthsList,
getRevertedCount],
(err, result) => {
send(err, result);
});
}
} | the_stack |
import { CollectionDivider, CollectionItem, CollectionNode, CollectionSection, NodeType, useCollection, useScrollableCollection } from "../../collection";
import { ComponentProps, KeyboardEvent, ReactNode, SyntheticEvent, forwardRef } from "react";
import {
InternalProps,
Keys,
OmitInternalProps,
StyledComponentProps,
appendEventKey,
cssModule,
isEmptyArray,
isNil,
isNumber,
mergeProps,
useAutoFocusChild,
useControllableState,
useDisposables,
useEventCallback,
useFocusManager,
useFocusScope,
useId,
useKeyedRovingFocus,
useMergedRefs,
useRefState
} from "../../shared";
import { ResponsiveProp, useResponsiveValue } from "../../styling";
import { Box } from "../../box";
import { MenuContext } from "./MenuContext";
import { MenuItem } from "./MenuItem";
import { MenuSection } from "./MenuSection";
import { ValidationState } from "../../input";
export type SelectionMode = "none" | "single" | "multiple";
export const ItemKeyProp = "data-o-ui-key";
const DefaultElement = "ul";
export interface InnerMenuProps extends InternalProps, StyledComponentProps<typeof DefaultElement> {
/**
* Whether or not the menu should autofocus on render.
*/
autoFocus?: boolean | number;
/**
* React children.
*/
children: ReactNode;
/**
* Default focus target when enabling autofocus.
*/
defaultFocusTarget?: string;
/**
* The initial value of `selectedKeys` when uncontrolled.
*/
defaultSelectedKeys?: string[];
/**
* Whether or not the menu items are disabled.
*/
disabled?: boolean;
/**
* Whether or not the listbox take up the width of its container.
*/
fluid?: ResponsiveProp<boolean>;
/**
* A collection of nodes to render instead of children. It should only be used if you embed a Menu inside another component.
*/
nodes?: CollectionNode[];
/**
* Called when the selected keys change.
* @param {SyntheticEvent} event - React's original event.
* @param {String[]} keys - The keys of the selected items..
* @returns {void}
*/
onSelectionChange?: (event: SyntheticEvent, keys: string[]) => void;
/**
* A controlled set of the selected item keys.
*/
selectedKeys?: string[] | null;
/**
* The type of selection that is allowed.
*/
selectionMode?: SelectionMode;
/**
* Whether or not the menu should display as "valid" or "invalid".
*/
validationState?: ValidationState;
}
function useCollectionNodes(children: ReactNode, nodes: CollectionNode[]) {
const collectionNodes = useCollection(children);
return nodes ?? collectionNodes;
}
export function InnerMenu({
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
as = DefaultElement,
autoFocus,
children,
defaultFocusTarget,
defaultSelectedKeys,
fluid,
forwardedRef,
id,
nodes: nodesProp,
onSelectionChange,
selectedKeys: selectedKeysProp,
selectionMode = "none",
validationState,
...rest
}: InnerMenuProps) {
const fluidValue = useResponsiveValue(fluid);
const [selectedKeys, setSelectedKeys] = useControllableState(selectedKeysProp, defaultSelectedKeys, []);
const [typeaheadQueryRef, setTypeaheadQuery] = useRefState("");
const [focusScope, setFocusRef] = useFocusScope();
const containerRef = useMergedRefs(setFocusRef, forwardedRef);
const focusManager = useFocusManager(focusScope, { keyProp: ItemKeyProp });
const handleSelectItem = useEventCallback((event: SyntheticEvent, key: string) => {
let newKeys;
if (selectionMode === "multiple") {
newKeys = selectedKeys.includes(key) ? selectedKeys.filter(x => x !== key) : [...selectedKeys, key];
} else {
newKeys = selectedKeys.includes(key) ? [] : [key];
}
if (selectionMode !== "none") {
setSelectedKeys(newKeys);
}
if (!isNil(onSelectionChange)) {
onSelectionChange(event, newKeys);
}
});
const typeaheadDisposables = useDisposables();
const handleKeyDown = useEventCallback((event: KeyboardEvent) => {
typeaheadDisposables.dispose();
switch (event.key) {
case Keys.arrowDown: {
event.preventDefault();
focusManager.focusNext();
break;
}
case Keys.arrowUp: {
event.preventDefault();
focusManager.focusPrevious();
break;
}
case Keys.home:
event.preventDefault();
focusManager.focusFirst();
break;
case Keys.end:
event.preventDefault();
focusManager.focusLast();
break;
case Keys.enter:
case Keys.space:
event.preventDefault();
handleSelectItem(event, document.activeElement.getAttribute(ItemKeyProp));
break;
// eslint-disable-next-line no-fallthrough
default:
if (event.key.length === 1) {
event.preventDefault();
const query = appendEventKey(typeaheadQueryRef.current, event.key);
setTypeaheadQuery(query);
focusManager.focusFirstQueryMatch(query);
// Clear search query.
typeaheadDisposables.setTimeout(() => {
setTypeaheadQuery("");
}, 350);
}
}
});
useKeyedRovingFocus(focusScope, selectedKeys[0], {
keyProp: ItemKeyProp
});
useAutoFocusChild(focusManager, {
delay: isNumber(autoFocus) ? autoFocus : undefined,
isDisabled: !autoFocus,
target: selectedKeys[0] ?? defaultFocusTarget
});
const nodes = useCollectionNodes(children, nodesProp);
const scrollableProps = useScrollableCollection(containerRef, nodes, {
disabled: selectionMode === "none",
dividerSelector: ".o-ui-menu-divider",
// A menu have a border-size of 1px
itemSelector: ".o-ui-menu-item",
maxHeight: 12 * 32,
// 32px is the default menu item height.
paddingHeight: 2 * 1,
sectionSelector: ".o-ui-menu-section-title"
});
const rootId = useId(id, "o-ui-menu");
const renderItem = ({
content,
elementType: As = MenuItem,
index,
key,
props,
ref,
tooltip
}: CollectionItem) => (
<As
{...mergeProps(
props,
{
id: `${rootId}-item-${index + 1}`,
item: { key, tooltip },
key,
ref
}
)}
>
{content}
</As>
);
const renderSection = ({
key,
index,
elementType: As = MenuSection,
ref,
props,
items: sectionItems
}: CollectionSection) => {
if (isEmptyArray(sectionItems)) {
return null;
}
return (
<As
{...mergeProps(
props,
{
id: `${rootId}-section-${index + 1}`,
key,
ref
}
)}
>
{sectionItems.map(x => renderItem(x))}
</As>
);
};
const renderDivider = ({
content,
elementType: As,
key,
props,
ref
}: CollectionDivider) => (
<As
{...mergeProps(
props,
{
as: "li",
className: "o-ui-menu-divider",
key,
ref
}
)}
>
{content}
</As>
);
return (
<Box
{...mergeProps(
rest,
{
"aria-invalid": validationState === "invalid" ? true : undefined,
"aria-label": ariaLabel,
"aria-labelledby": isNil(ariaLabel) ? ariaLabelledBy : undefined,
"aria-orientation": "vertical",
as,
className: cssModule(
"o-ui-menu",
fluidValue && "fluid",
selectionMode !== "none" && "with-selection",
validationState
),
id: rootId,
onKeyDown: handleKeyDown,
ref: containerRef,
role: "menu"
},
scrollableProps
)}
>
<MenuContext.Provider
value={{
onSelect: handleSelectItem,
selectedKeys,
selectionMode
}}
>
{nodes.map(node => {
switch (node.type) {
case NodeType.item:
return renderItem(node as CollectionItem);
case NodeType.section:
return renderSection(node as CollectionSection);
case NodeType.divider:
return renderDivider(node as CollectionDivider);
default:
return null;
}
})}
</MenuContext.Provider>
</Box>
);
}
InnerMenu.defaultElement = DefaultElement;
export const Menu = forwardRef<any, OmitInternalProps<InnerMenuProps>>((props, ref) => (
<InnerMenu {...props} forwardedRef={ref} />
));
export type MenuProps = ComponentProps<typeof Menu>; | the_stack |
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { YDocument, MapChange } from '@jupyterlab/shared-models';
import { IModelDB, ModelDB } from '@jupyterlab/observables';
import { IChangedArgs } from '@jupyterlab/coreutils';
import { PartialJSONObject } from '@lumino/coreutils';
import { ISignal, Signal } from '@lumino/signaling';
import * as Y from 'yjs';
export type SharedObject = {
x: number;
y: number;
content: string;
};
export type Position = {
x: number;
y: number;
};
/**
* DocumentModel: this Model represents the content of the file
*/
export class ExampleDocModel implements DocumentRegistry.IModel {
/**
* Construct a new ExampleDocModel.
*
* @param languagePreference Language
* @param modelDB Document model database
*/
constructor(languagePreference?: string, modelDB?: IModelDB) {
this.modelDB = modelDB || new ModelDB();
// Listening for changes on the shared model to propagate them
this.sharedModel.changed.connect(this._onSharedModelChanged);
this.sharedModel.awareness.on('change', this._onClientChanged);
}
/**
* get/set the dirty attribute to know when the
* content in the document differs from disk
*
* @returns dirty attribute
*/
get dirty(): boolean {
return this._dirty;
}
set dirty(value: boolean) {
this._dirty = value;
}
/**
* get/set the readOnly attribute to know whether this model
* is read only or not
*
* @returns readOnly attribute
*/
get readOnly(): boolean {
return this._readOnly;
}
set readOnly(value: boolean) {
this._readOnly = value;
}
/**
* get the isDisposed attribute to know whether this model
* has been disposed or not
*
* @returns Model status
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* get the signal contentChange to listen for changes on the content
* of the model.
*
* NOTE: The content refers to de data stored in the model while the state refers
* to the metadata or attributes of the model.
*
* @returns The signal
*/
get contentChanged(): ISignal<this, void> {
return this._contentChanged;
}
/**
* get the signal stateChanged to listen for changes on the state
* of the model.
*
* NOTE: The content refers to de data stored in the model while the state refers
* to the metadata or attributes of the model.
*
* @returns The signal
*/
get stateChanged(): ISignal<this, IChangedArgs<any, any, string>> {
return this._stateChanged;
}
/**
* get the signal sharedModelChanged to listen for changes on the content
* of the shared model.
*
* @returns The signal
*/
get sharedModelChanged(): ISignal<this, ExampleDocChange> {
return this._sharedModelChanged;
}
/**
* get the signal clientChanged to listen for changes on the clients sharing
* the same document.
*
* @returns The signal
*/
get clientChanged(): ISignal<this, Map<number, any>> {
return this._clientChanged;
}
/**
* defaultKernelName and defaultKernelLanguage are only used by the Notebook widget
* or documents that use kernels, and they store the name and the language of the kernel.
*/
readonly defaultKernelName: string;
readonly defaultKernelLanguage: string;
/**
* modelBD is the datastore for the content of the document.
* modelDB is not a shared datastore so we don't use it on this example since
* this example is a shared document.
*/
readonly modelDB: IModelDB;
/**
* New datastore introduced in JupyterLab v3.1 to store shared data and make notebooks
* collaborative
*/
readonly sharedModel: ExampleDoc = ExampleDoc.create();
/**
* Dispose of the resources held by the model.
*/
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Should return the data that you need to store in disk as a string.
* The context will call this method to get the file's content and save it
* to disk
*
* @returns The data
*/
toString(): string {
const pos = this.sharedModel.getContent('position');
const obj = {
x: pos?.x || 10,
y: pos?.y || 10,
content: this.sharedModel.getContent('content') || '',
};
return JSON.stringify(obj, null, 2);
}
/**
* The context will call this method when loading data from disk.
* This method should implement the logic to parse the data and store it
* on the datastore.
*
* @param data Serialized data
*/
fromString(data: string): void {
const obj = JSON.parse(data);
this.sharedModel.transact(() => {
this.sharedModel.setContent('position', { x: obj.x, y: obj.y });
this.sharedModel.setContent('content', obj.content);
});
}
/**
* Should return the data that you need to store in disk as a JSON object.
* The context will call this method to get the file's content and save it
* to disk.
*
* NOTE: This method is only used by the context of the notebook, every other
* document will load/save the data through toString/fromString.
*
* @returns Model JSON representation
*/
toJSON(): PartialJSONObject {
const pos = this.sharedModel.getContent('position');
const obj = {
x: pos?.x || 10,
y: pos?.y || 10,
content: this.sharedModel.getContent('content') || '',
};
return obj;
}
/**
* The context will call this method when loading data from disk.
* This method should implement the logic to parse the data and store it
* on the datastore.
*
* NOTE: This method is only used by the context of the notebook, every other
* document will load/save the data through toString/fromString.
*
* @param data Serialized model
*/
fromJSON(data: PartialJSONObject): void {
this.sharedModel.transact(() => {
this.sharedModel.setContent('position', { x: data.x, y: data.y });
this.sharedModel.setContent('content', data.content);
});
}
initialize(): void {
// nothing to do
}
/**
* Returns the Id of the client from the YDoc
*
* @returns client id
*/
getClientId(): number {
return this.sharedModel.awareness.clientID;
}
/**
* Returns the SharedObject
*
* @returns SharedObject
*/
getSharedObject(): SharedObject {
const pos = this.sharedModel.getContent('position');
const obj = {
x: pos?.x || 10,
y: pos?.y || 10,
content: this.sharedModel.getContent('content') || '',
};
return obj;
}
/**
* Sets the position of the SharedObject
*
* @param pos Position
*/
setPosition(pos: Position): void {
this.sharedModel.setContent('position', pos);
}
/**
* Sets the text inside the SharedObject
*
* @param content Text
*/
setContent(content: string): void {
this.sharedModel.setContent('content', content);
}
/**
* Sets the mouse's position of the client
*
* @param pos Mouse position
*/
setClient(pos: Position): void {
// Adds the position of the mouse from the client to the shared state.
this.sharedModel.awareness.setLocalStateField('mouse', pos);
}
/**
* Callback to listen for changes on the sharedModel. This callback listens
* to changes on shared model's content and propagates them to the DocumentWidget.
*
* @param sender The sharedModel that triggers the changes.
* @param changes The changes on the sharedModel.
*/
private _onSharedModelChanged = (
sender: ExampleDoc,
changes: ExampleDocChange
): void => {
this._sharedModelChanged.emit(changes);
};
/**
* Callback to listen for changes on the sharedModel. This callback listens
* to changes on the different clients sharing the document and propagates
* them to the DocumentWidget.
*/
private _onClientChanged = () => {
const clients = this.sharedModel.awareness.getStates();
this._clientChanged.emit(clients);
};
private _dirty = false;
private _readOnly = false;
private _isDisposed = false;
private _contentChanged = new Signal<this, void>(this);
private _stateChanged = new Signal<this, IChangedArgs<any>>(this);
private _clientChanged = new Signal<this, Map<number, any>>(this);
private _sharedModelChanged = new Signal<this, ExampleDocChange>(this);
}
/**
* Type representing the changes on the sharedModel.
*
* NOTE: Yjs automatically syncs the documents of the different clients
* and triggers an event to notify that the content changed. You can
* listen to this changes and propagate them to the widget so you don't
* need to update all the data in the widget, you can only update the data
* that changed.
*
* This type represents the different changes that may happen and ready to use
* for the widget.
*/
export type ExampleDocChange = {
contextChange?: MapChange;
contentChange?: string;
positionChange?: Position;
};
/**
* SharedModel, stores and shares the content between clients.
*/
export class ExampleDoc extends YDocument<ExampleDocChange> {
constructor() {
super();
// Creating a new shared object and listen to its changes
this._content = this.ydoc.getMap('content');
this._content.observe(this._contentObserver);
}
/**
* Dispose of the resources.
*/
dispose(): void {
this._content.unobserve(this._contentObserver);
}
/**
* Static method to create instances on the sharedModel
*
* @returns The sharedModel instance
*/
public static create(): ExampleDoc {
return new ExampleDoc();
}
/**
* Returns an the requested object.
*
* @param key The key of the object.
* @returns The content
*/
public getContent(key: string): any {
return this._content.get(key);
}
/**
* Adds new data.
*
* @param key The key of the object.
* @param value New object.
*/
public setContent(key: string, value: any): void {
this._content.set(key, value);
}
/**
* Handle a change.
*
* @param event Model event
*/
private _contentObserver = (event: Y.YMapEvent<any>): void => {
const changes: ExampleDocChange = {};
// Checks which object changed and propagates them.
if (event.keysChanged.has('position')) {
changes.positionChange = this._content.get('position');
}
if (event.keysChanged.has('content')) {
changes.contentChange = this._content.get('content');
}
this._changed.emit(changes);
};
private _content: Y.Map<any>;
} | the_stack |
import Point from '../point/Point';
import Circle from '../circle/Circle';
import Line from '../line/Line';
import { Vector2Like } from '../types';
/**
* A triangle is a plane created by connecting three points.
* The first two arguments specify the first point, the middle two arguments
* specify the second point, and the last two arguments specify the third point.
*/
declare class Triangle {
/**
*
* @param x1 `x` coordinate of the first point. Default 0.
* @param y1 `y` coordinate of the first point. Default 0.
* @param x2 `x` coordinate of the second point. Default 0.
* @param y2 `y` coordinate of the second point. Default 0.
* @param x3 `x` coordinate of the third point. Default 0.
* @param y3 `y` coordinate of the third point. Default 0.
*/
constructor(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number);
/**
* Returns the area of a Triangle.
* @param triangle The Triangle to use.
*/
static Area(triangle: Triangle): number;
/**
* Builds an equilateral triangle. In the equilateral triangle, all the sides are the same length (congruent) and all the angles are the same size (congruent).
* The x/y specifies the top-middle of the triangle (x1/y1) and length is the length of each side.
* @param x x coordinate of the top point of the triangle.
* @param y y coordinate of the top point of the triangle.
* @param length Length of each side of the triangle.
*/
static BuildEquilateral(x: number, y: number, length: number): Triangle;
/**
* Takes an array of vertex coordinates, and optionally an array of hole indices, then returns an array
* of Triangle instances, where the given vertices have been decomposed into a series of triangles.
* @param data A flat array of vertex coordinates like [x0,y0, x1,y1, x2,y2, ...]
* @param holes An array of hole indices if any (e.g. [5, 8] for a 12-vertex input would mean one hole with vertices 5–7 and another with 8–11). Default null.
* @param scaleX Horizontal scale factor to multiply the resulting points by. Default 1.
* @param scaleY Vertical scale factor to multiply the resulting points by. Default 1.
* @param out An array to store the resulting Triangle instances in. If not provided, a new array is created.
*/
static BuildFromPolygon<O extends Triangle[]>(data: any[], holes?: any[], scaleX?: number, scaleY?: number, out?: O): O;
/**
* Builds a right triangle, i.e. one which has a 90-degree angle and two acute angles.
* @param x The X coordinate of the right angle, which will also be the first X coordinate of the constructed Triangle.
* @param y The Y coordinate of the right angle, which will also be the first Y coordinate of the constructed Triangle.
* @param width The length of the side which is to the left or to the right of the right angle.
* @param height The length of the side which is above or below the right angle.
*/
static BuildRight(x: number, y: number, width: number, height: number): Triangle;
/**
* Positions the Triangle so that it is centered on the given coordinates.
* @param triangle The triangle to be positioned.
* @param x The horizontal coordinate to center on.
* @param y The vertical coordinate to center on.
* @param centerFunc The function used to center the triangle. Defaults to Centroid centering.
*/
static CenterOn<O extends Triangle>(triangle: O, x: number, y: number, centerFunc?: CenterFunction): O;
/**
* Calculates the position of a Triangle's centroid, which is also its center of mass (center of gravity).
*
* The centroid is the point in a Triangle at which its three medians (the lines drawn from the vertices to the bisectors of the opposite sides) meet. It divides each one in a 2:1 ratio.
* @param triangle The Triangle to use.
* @param out An object to store the coordinates in.
*/
static Centroid<O extends Point>(triangle: Triangle, out?: O): O;
/**
* Computes the circumcentre of a triangle. The circumcentre is the centre of
* the circumcircle, the smallest circle which encloses the triangle. It is also
* the common intersection point of the perpendicular bisectors of the sides of
* the triangle, and is the only point which has equal distance to all three
* vertices of the triangle.
* @param triangle The Triangle to get the circumcenter of.
* @param out The Vector2 object to store the position in. If not given, a new Vector2 instance is created.
*/
static CircumCenter(triangle: Triangle, out?: Vector2Like): Vector2Like;
/**
* Finds the circumscribed circle (circumcircle) of a Triangle object. The circumcircle is the circle which touches all of the triangle's vertices.
* @param triangle The Triangle to use as input.
* @param out An optional Circle to store the result in.
*/
static CircumCircle(triangle: Triangle, out?: Circle): Circle;
/**
* Clones a Triangle object.
* @param source The Triangle to clone.
*/
static Clone(source: Triangle): Triangle;
/**
* Checks if a point (as a pair of coordinates) is inside a Triangle's bounds.
* @param triangle The Triangle to check.
* @param x The X coordinate of the point to check.
* @param y The Y coordinate of the point to check.
*/
static Contains(triangle: Triangle, x: number, y: number): boolean;
/**
* Filters an array of point-like objects to only those contained within a triangle.
* If `returnFirst` is true, will return an array containing only the first point in the provided array that is within the triangle (or an empty array if there are no such points).
* @param triangle The triangle that the points are being checked in.
* @param points An array of point-like objects (objects that have an `x` and `y` property)
* @param returnFirst If `true`, return an array containing only the first point found that is within the triangle. Default false.
* @param out If provided, the points that are within the triangle will be appended to this array instead of being added to a new array. If `returnFirst` is true, only the first point found within the triangle will be appended. This array will also be returned by this function.
*/
static ContainsArray(triangle: Triangle, points: Point[], returnFirst?: boolean, out?: any[]): Point[];
/**
* Tests if a triangle contains a point.
* @param triangle The triangle.
* @param point The point to test, or any point-like object with public `x` and `y` properties.
*/
static ContainsPoint(triangle: Triangle, point: Vector2Like): boolean;
/**
* Copy the values of one Triangle to a destination Triangle.
* @param source The source Triangle to copy the values from.
* @param dest The destination Triangle to copy the values to.
*/
static CopyFrom<O extends Triangle>(source: Triangle, dest: O): O;
/**
* Decomposes a Triangle into an array of its points.
* @param triangle The Triangle to decompose.
* @param out An array to store the points into.
*/
static Decompose(triangle: Triangle, out?: any[]): any[];
/**
* Returns true if two triangles have the same coordinates.
* @param triangle The first triangle to check.
* @param toCompare The second triangle to check.
*/
static Equals(triangle: Triangle, toCompare: Triangle): boolean;
/**
* Returns a Point from around the perimeter of a Triangle.
* @param triangle The Triangle to get the point on its perimeter from.
* @param position The position along the perimeter of the triangle. A value between 0 and 1.
* @param out An option Point, or Point-like object to store the value in. If not given a new Point will be created.
*/
static GetPoint<O extends Point>(triangle: Triangle, position: number, out?: O): O;
/**
* Returns an array of evenly spaced points on the perimeter of a Triangle.
* @param triangle The Triangle to get the points from.
* @param quantity The number of evenly spaced points to return. Set to 0 to return an arbitrary number of points based on the `stepRate`.
* @param stepRate If `quantity` is 0, the distance between each returned point.
* @param out An array to which the points should be appended.
*/
static GetPoints<O extends Point>(triangle: Triangle, quantity: number, stepRate: number, out?: O): O;
/**
* Calculates the position of the incenter of a Triangle object. This is the point where its three angle bisectors meet and it's also the center of the incircle, which is the circle inscribed in the triangle.
* @param triangle The Triangle to find the incenter of.
* @param out An optional Point in which to store the coordinates.
*/
static InCenter<O extends Point>(triangle: Triangle, out?: O): O;
/**
* Moves each point (vertex) of a Triangle by a given offset, thus moving the entire Triangle by that offset.
* @param triangle The Triangle to move.
* @param x The horizontal offset (distance) by which to move each point. Can be positive or negative.
* @param y The vertical offset (distance) by which to move each point. Can be positive or negative.
*/
static Offset<O extends Triangle>(triangle: O, x: number, y: number): O;
/**
* Gets the length of the perimeter of the given triangle.
* Calculated by adding together the length of each of the three sides.
* @param triangle The Triangle to get the length from.
*/
static Perimeter(triangle: Triangle): number;
/**
* Returns a random Point from within the area of the given Triangle.
* @param triangle The Triangle to get a random point from.
* @param out The Point object to store the position in. If not given, a new Point instance is created.
*/
static Random<O extends Point>(triangle: Triangle, out?: O): O;
/**
* Rotates a Triangle about its incenter, which is the point at which its three angle bisectors meet.
* @param triangle The Triangle to rotate.
* @param angle The angle by which to rotate the Triangle, in radians.
*/
static Rotate<O extends Triangle>(triangle: O, angle: number): O;
/**
* Rotates a Triangle at a certain angle about a given Point or object with public `x` and `y` properties.
* @param triangle The Triangle to rotate.
* @param point The Point to rotate the Triangle about.
* @param angle The angle by which to rotate the Triangle, in radians.
*/
static RotateAroundPoint<O extends Triangle>(triangle: O, point: Point, angle: number): O;
/**
* Rotates an entire Triangle at a given angle about a specific point.
* @param triangle The Triangle to rotate.
* @param x The X coordinate of the point to rotate the Triangle about.
* @param y The Y coordinate of the point to rotate the Triangle about.
* @param angle The angle by which to rotate the Triangle, in radians.
*/
static RotateAroundXY<O extends Triangle>(triangle: O, x: number, y: number, angle: number): O;
/**
* The geometry constant type of this object: `GEOM_CONST.TRIANGLE`.
* Used for fast type comparisons.
*/
readonly type: number;
/**
* `x` coordinate of the first point.
*/
x1: number;
/**
* `y` coordinate of the first point.
*/
y1: number;
/**
* `x` coordinate of the second point.
*/
x2: number;
/**
* `y` coordinate of the second point.
*/
y2: number;
/**
* `x` coordinate of the third point.
*/
x3: number;
/**
* `y` coordinate of the third point.
*/
y3: number;
/**
* Checks whether a given points lies within the triangle.
* @param x The x coordinate of the point to check.
* @param y The y coordinate of the point to check.
*/
contains(x: number, y: number): boolean;
/**
* Returns a specific point on the triangle.
* @param position Position as float within `0` and `1`. `0` equals the first point.
* @param output Optional Point, or point-like object, that the calculated point will be written to.
*/
getPoint<O extends Point>(position: number, output?: O): O;
/**
* Calculates a list of evenly distributed points on the triangle. It is either possible to pass an amount of points to be generated (`quantity`) or the distance between two points (`stepRate`).
* @param quantity Number of points to be generated. Can be falsey when `stepRate` should be used. All points have the same distance along the triangle.
* @param stepRate Distance between two points. Will only be used when `quantity` is falsey.
* @param output Optional Array for writing the calculated points into. Otherwise a new array will be created.
*/
getPoints<O extends Point[]>(quantity: number, stepRate?: number, output?: O): O;
/**
* Returns a random point along the triangle.
* @param point Optional `Point` that should be modified. Otherwise a new one will be created.
*/
getRandomPoint<O extends Point>(point?: O): O;
/**
* Sets all three points of the triangle. Leaving out any coordinate sets it to be `0`.
* @param x1 `x` coordinate of the first point. Default 0.
* @param y1 `y` coordinate of the first point. Default 0.
* @param x2 `x` coordinate of the second point. Default 0.
* @param y2 `y` coordinate of the second point. Default 0.
* @param x3 `x` coordinate of the third point. Default 0.
* @param y3 `y` coordinate of the third point. Default 0.
*/
setTo(x1?: number, y1?: number, x2?: number, y2?: number, x3?: number, y3?: number): this;
/**
* Returns a Line object that corresponds to Line A of this Triangle.
* @param line A Line object to set the results in. If `undefined` a new Line will be created.
*/
getLineA(line?: Line): Line;
/**
* Returns a Line object that corresponds to Line B of this Triangle.
* @param line A Line object to set the results in. If `undefined` a new Line will be created.
*/
getLineB(line?: Line): Line;
/**
* Returns a Line object that corresponds to Line C of this Triangle.
* @param line A Line object to set the results in. If `undefined` a new Line will be created.
*/
getLineC(line?: Line): Line;
/**
* Left most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly.
*/
left: number;
/**
* Right most X coordinate of the triangle. Setting it moves the triangle on the X axis accordingly.
*/
right: number;
/**
* Top most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly.
*/
top: number;
/**
* Bottom most Y coordinate of the triangle. Setting it moves the triangle on the Y axis accordingly.
*/
bottom: number;
}
export default Triangle; | the_stack |
// clang-format off
import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js';
import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import { ClearBrowsingDataBrowserProxyImpl, ClearBrowsingDataResult,InstalledApp, SettingsCheckboxElement, SettingsClearBrowsingDataDialogElement, SettingsHistoryDeletionDialogElement, SettingsPasswordsDeletionDialogElement} from 'chrome://settings/lazy_load.js';
import {CrButtonElement, loadTimeData, StatusAction, SyncBrowserProxyImpl} from 'chrome://settings/settings.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, isVisible, whenAttributeIs} from 'chrome://webui-test/test_util.js';
import {TestClearBrowsingDataBrowserProxy} from './test_clear_browsing_data_browser_proxy.js';
import {TestSyncBrowserProxy} from './test_sync_browser_proxy.js';
// <if expr="not chromeos and not lacros">
import {Router, routes} from 'chrome://settings/settings.js';
import {isChildVisible} from 'chrome://webui-test/test_util.js';
// </if>
// clang-format on
function getClearBrowsingDataPrefs() {
return {
browser: {
clear_data: {
browsing_history: {
key: 'browser.clear_data.browsing_history',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
browsing_history_basic: {
key: 'browser.clear_data.browsing_history_basic',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
cache: {
key: 'browser.clear_data.cache',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
cache_basic: {
key: 'browser.clear_data.cache_basic',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
cookies: {
key: 'browser.clear_data.cookies',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
cookies_basic: {
key: 'browser.clear_data.cookies_basic',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
download_history: {
key: 'browser.clear_data.download_history',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
hosted_apps_data: {
key: 'browser.clear_data.hosted_apps_data',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
form_data: {
key: 'browser.clear_data.form_data',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
passwords: {
key: 'browser.clear_data.passwords',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
site_settings: {
key: 'browser.clear_data.site_settings',
type: chrome.settingsPrivate.PrefType.BOOLEAN,
value: false,
},
time_period: {
key: 'browser.clear_data.time_period',
type: chrome.settingsPrivate.PrefType.NUMBER,
value: 0,
},
time_period_basic: {
key: 'browser.clear_data.time_period_basic',
type: chrome.settingsPrivate.PrefType.NUMBER,
value: 0,
},
},
last_clear_browsing_data_tab: {
key: 'browser.last_clear_browsing_data_tab',
type: chrome.settingsPrivate.PrefType.NUMBER,
value: 0,
},
}
};
}
suite('ClearBrowsingDataDesktop', function() {
let testBrowserProxy: TestClearBrowsingDataBrowserProxy;
let testSyncBrowserProxy: TestSyncBrowserProxy;
let element: SettingsClearBrowsingDataDialogElement;
setup(function() {
testBrowserProxy = new TestClearBrowsingDataBrowserProxy();
ClearBrowsingDataBrowserProxyImpl.setInstance(testBrowserProxy);
testSyncBrowserProxy = new TestSyncBrowserProxy();
SyncBrowserProxyImpl.setInstance(testSyncBrowserProxy);
document.body.innerHTML = '';
element = document.createElement('settings-clear-browsing-data-dialog');
element.set('prefs', getClearBrowsingDataPrefs());
document.body.appendChild(element);
return testBrowserProxy.whenCalled('initialize').then(() => {
assertTrue(element.$.clearBrowsingDataDialog.open);
});
});
teardown(function() {
element.remove();
});
test('ClearBrowsingDataSyncAccountInfoDesktop', function() {
// Not syncing: the footer is hidden.
webUIListenerCallback('sync-status-changed', {
signedIn: false,
hasError: false,
});
flush();
assertFalse(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
// The footer is never shown on Lacros.
// <if expr="not chromeos and not lacros">
// Syncing: the footer is shown, with the normal sync info.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: false,
});
flush();
assertTrue(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
assertTrue(isChildVisible(element, '#sync-info'));
assertFalse(isChildVisible(element, '#sync-paused-info'));
assertFalse(isChildVisible(element, '#sync-passphrase-error-info'));
assertFalse(isChildVisible(element, '#sync-other-error-info'));
// Sync is paused.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.REAUTHENTICATE,
});
flush();
assertFalse(isChildVisible(element, '#sync-info'));
assertTrue(isChildVisible(element, '#sync-paused-info'));
assertFalse(isChildVisible(element, '#sync-passphrase-error-info'));
assertFalse(isChildVisible(element, '#sync-other-error-info'));
// Sync passphrase error.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.ENTER_PASSPHRASE,
});
flush();
assertFalse(isChildVisible(element, '#sync-info'));
assertFalse(isChildVisible(element, '#sync-paused-info'));
assertTrue(isChildVisible(element, '#sync-passphrase-error-info'));
assertFalse(isChildVisible(element, '#sync-other-error-info'));
// Other sync error.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.NO_ACTION,
});
flush();
assertFalse(isChildVisible(element, '#sync-info'));
assertFalse(isChildVisible(element, '#sync-paused-info'));
assertFalse(isChildVisible(element, '#sync-passphrase-error-info'));
assertTrue(isChildVisible(element, '#sync-other-error-info'));
// </if>
});
// The footer is never shown on Lacros.
// <if expr="not chromeos and not lacros">
test('ClearBrowsingDataPauseSyncDesktop', function() {
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: false,
});
flush();
assertTrue(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
const syncInfo = element.shadowRoot!.querySelector('#sync-info');
assertTrue(isVisible(syncInfo));
const signoutLink = syncInfo!.querySelector<HTMLElement>('a[href]');
assertTrue(!!signoutLink);
assertEquals(0, testSyncBrowserProxy.getCallCount('pauseSync'));
signoutLink!.click();
assertEquals(1, testSyncBrowserProxy.getCallCount('pauseSync'));
});
test('ClearBrowsingDataStartSignInDesktop', function() {
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.REAUTHENTICATE,
});
flush();
assertTrue(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
const syncInfo = element.shadowRoot!.querySelector('#sync-paused-info');
assertTrue(isVisible(syncInfo));
const signinLink = syncInfo!.querySelector<HTMLElement>('a[href]');
assertTrue(!!signinLink);
assertEquals(0, testSyncBrowserProxy.getCallCount('startSignIn'));
signinLink!.click();
assertEquals(1, testSyncBrowserProxy.getCallCount('startSignIn'));
});
test('ClearBrowsingDataHandlePassphraseErrorDesktop', function() {
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.ENTER_PASSPHRASE,
});
flush();
assertTrue(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
const syncInfo =
element.shadowRoot!.querySelector('#sync-passphrase-error-info');
assertTrue(isVisible(syncInfo));
const passphraseLink = syncInfo!.querySelector<HTMLElement>('a[href]');
assertTrue(!!passphraseLink);
passphraseLink!.click();
assertEquals(routes.SYNC, Router.getInstance().getCurrentRoute());
});
// </if>
test('ClearBrowsingDataSearchLabelVisibility', function() {
for (const signedIn of [false, true]) {
for (const isNonGoogleDse of [false, true]) {
webUIListenerCallback('update-sync-state', {
signedIn: signedIn,
isNonGoogleDse: isNonGoogleDse,
nonGoogleSearchHistoryString: 'Some test string',
});
flush();
// Test Google search history label visibility and string.
assertEquals(
signedIn,
isVisible(
element.shadowRoot!.querySelector('#googleSearchHistoryLabel')),
'googleSearchHistoryLabel visibility');
if (signedIn) {
assertEquals(
isNonGoogleDse ?
element.i18nAdvanced('clearGoogleSearchHistoryNonGoogleDse') :
element.i18nAdvanced('clearGoogleSearchHistoryGoogleDse'),
element.shadowRoot!
.querySelector<HTMLElement>(
'#googleSearchHistoryLabel')!.innerHTML,
'googleSearchHistoryLabel text');
}
// Test non-Google search history label visibility and string.
assertEquals(
isNonGoogleDse,
isVisible(element.shadowRoot!.querySelector(
'#nonGoogleSearchHistoryLabel')),
'nonGoogleSearchHistoryLabel visibility');
if (isNonGoogleDse) {
assertEquals(
'Some test string',
element.shadowRoot!
.querySelector<HTMLElement>(
'#nonGoogleSearchHistoryLabel')!.innerText,
'nonGoogleSearchHistoryLabel text');
}
}
}
});
});
suite('ClearBrowsingDataAllPlatforms', function() {
let testBrowserProxy: TestClearBrowsingDataBrowserProxy;
let element: SettingsClearBrowsingDataDialogElement;
setup(function() {
testBrowserProxy = new TestClearBrowsingDataBrowserProxy();
ClearBrowsingDataBrowserProxyImpl.setInstance(testBrowserProxy);
document.body.innerHTML = '';
element = document.createElement('settings-clear-browsing-data-dialog');
element.set('prefs', getClearBrowsingDataPrefs());
document.body.appendChild(element);
return testBrowserProxy.whenCalled('initialize');
});
teardown(function() {
element.remove();
});
test('ClearBrowsingDataTap', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
assertFalse(element.$.installedAppsDialog.open);
const cancelButton =
element.shadowRoot!.querySelector<CrButtonElement>('.cancel-button');
assertTrue(!!cancelButton);
const actionButton =
element.shadowRoot!.querySelector<CrButtonElement>('.action-button');
assertTrue(!!actionButton);
const spinner = element.shadowRoot!.querySelector('paper-spinner-lite');
assertTrue(!!spinner);
// Select a datatype for deletion to enable the clear button.
assertTrue(!!element.$.cookiesCheckboxBasic);
element.$.cookiesCheckboxBasic.$.checkbox.click();
assertFalse(cancelButton!.disabled);
assertFalse(actionButton!.disabled);
assertFalse(spinner!.active);
const promiseResolver = new PromiseResolver<ClearBrowsingDataResult>();
testBrowserProxy.setClearBrowsingDataPromise(promiseResolver.promise);
actionButton!.click();
return testBrowserProxy.whenCalled('clearBrowsingData')
.then(function(args) {
const dataTypes = args[0];
const installedApps = args[2];
assertEquals(1, dataTypes.length);
assertEquals('browser.clear_data.cookies_basic', dataTypes[0]);
assertTrue(element.$.clearBrowsingDataDialog.open);
assertTrue(cancelButton!.disabled);
assertTrue(actionButton!.disabled);
assertTrue(spinner!.active);
assertTrue(installedApps.length === 0);
// Simulate signal from browser indicating that clearing has
// completed.
webUIListenerCallback('browsing-data-removing', false);
promiseResolver.resolve(
{showHistoryNotice: false, showPasswordsNotice: false});
// Yields to the message loop to allow the callback chain of the
// Promise that was just resolved to execute before the
// assertions.
})
.then(function() {
assertFalse(element.$.clearBrowsingDataDialog.open);
assertFalse(cancelButton!.disabled);
assertFalse(actionButton!.disabled);
assertFalse(spinner!.active);
assertFalse(!!element.shadowRoot!.querySelector('#historyNotice'));
assertFalse(!!element.shadowRoot!.querySelector('#passwordsNotice'));
// Check that the dialog didn't switch to installed apps.
assertFalse(element.$.installedAppsDialog.open);
});
});
test('ClearBrowsingDataClearButton', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
const actionButton =
element.shadowRoot!.querySelector<CrButtonElement>('.action-button');
assertTrue(!!actionButton);
assertTrue(!!element.$.cookiesCheckboxBasic);
// Initially the button is disabled because all checkboxes are off.
assertTrue(actionButton!.disabled);
// The button gets enabled if any checkbox is selected.
element.$.cookiesCheckboxBasic.$.checkbox.click();
assertTrue(element.$.cookiesCheckboxBasic.checked);
assertFalse(actionButton!.disabled);
// Switching to advanced disables the button.
element.shadowRoot!.querySelector('cr-tabs')!.selected = 1;
assertTrue(actionButton!.disabled);
// Switching back enables it again.
element.shadowRoot!.querySelector('cr-tabs')!.selected = 0;
assertFalse(actionButton!.disabled);
});
test('showHistoryDeletionDialog', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
const actionButton =
element.shadowRoot!.querySelector<CrButtonElement>('.action-button');
assertTrue(!!actionButton);
// Select a datatype for deletion to enable the clear button.
assertTrue(!!element.$.cookiesCheckboxBasic);
element.$.cookiesCheckboxBasic.$.checkbox.click();
assertFalse(actionButton!.disabled);
const promiseResolver = new PromiseResolver<ClearBrowsingDataResult>();
testBrowserProxy.setClearBrowsingDataPromise(promiseResolver.promise);
actionButton!.click();
return testBrowserProxy.whenCalled('clearBrowsingData')
.then(function() {
// Passing showHistoryNotice = true should trigger the notice about
// other forms of browsing history to open, and the dialog to stay
// open.
promiseResolver.resolve(
{showHistoryNotice: true, showPasswordsNotice: false});
// Yields to the message loop to allow the callback chain of the
// Promise that was just resolved to execute before the
// assertions.
})
.then(function() {
flush();
const notice =
element.shadowRoot!
.querySelector<SettingsHistoryDeletionDialogElement>(
'#historyNotice');
assertTrue(!!notice);
const noticeActionButton =
notice!.shadowRoot!.querySelector<CrButtonElement>(
'.action-button');
assertTrue(!!noticeActionButton);
// The notice should have replaced the main dialog.
assertFalse(element.$.clearBrowsingDataDialog.open);
assertTrue(notice!.$.dialog.open);
const whenNoticeClosed = eventToPromise('close', notice!);
// Tapping the action button will close the notice.
noticeActionButton!.click();
return whenNoticeClosed;
})
.then(function() {
const notice = element.shadowRoot!.querySelector('#historyNotice');
assertFalse(!!notice);
assertFalse(element.$.clearBrowsingDataDialog.open);
});
});
test('showPasswordsDeletionDialog', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
const actionButton =
element.shadowRoot!.querySelector<CrButtonElement>('.action-button');
assertTrue(!!actionButton);
// Select a datatype for deletion to enable the clear button.
const cookieCheckbox = element.$.cookiesCheckboxBasic;
assertTrue(!!cookieCheckbox);
cookieCheckbox.$.checkbox.click();
assertFalse(actionButton!.disabled);
const promiseResolver = new PromiseResolver<ClearBrowsingDataResult>();
testBrowserProxy.setClearBrowsingDataPromise(promiseResolver.promise);
actionButton!.click();
return testBrowserProxy.whenCalled('clearBrowsingData')
.then(function() {
// Passing showPasswordsNotice = true should trigger the notice about
// incomplete password deletions to open, and the dialog to stay open.
promiseResolver.resolve(
{showHistoryNotice: false, showPasswordsNotice: true});
// Yields to the message loop to allow the callback chain of the
// Promise that was just resolved to execute before the
// assertions.
})
.then(function() {
flush();
const notice =
element.shadowRoot!
.querySelector<SettingsPasswordsDeletionDialogElement>(
'#passwordsNotice');
assertTrue(!!notice);
const noticeActionButton =
notice!.shadowRoot!.querySelector<CrButtonElement>(
'.action-button');
assertTrue(!!noticeActionButton);
// The notice should have replaced the main dialog.
assertFalse(element.$.clearBrowsingDataDialog.open);
assertTrue(notice!.$.dialog.open);
const whenNoticeClosed = eventToPromise('close', notice!);
// Tapping the action button will close the notice.
noticeActionButton!.click();
return whenNoticeClosed;
})
.then(function() {
const notice = element.shadowRoot!.querySelector('#passwordsNotice');
assertFalse(!!notice);
assertFalse(element.$.clearBrowsingDataDialog.open);
});
});
test('showBothHistoryAndPasswordsDeletionDialog', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
const actionButton =
element.shadowRoot!.querySelector<CrButtonElement>('.action-button');
assertTrue(!!actionButton);
// Select a datatype for deletion to enable the clear button.
const cookieCheckbox = element.$.cookiesCheckboxBasic;
assertTrue(!!cookieCheckbox);
cookieCheckbox.$.checkbox.click();
assertFalse(actionButton!.disabled);
const promiseResolver = new PromiseResolver<ClearBrowsingDataResult>();
testBrowserProxy.setClearBrowsingDataPromise(promiseResolver.promise);
actionButton!.click();
return testBrowserProxy.whenCalled('clearBrowsingData')
.then(function() {
// Passing showHistoryNotice = true and showPasswordsNotice = true
// should first trigger the notice about other forms of browsing
// history to open, then once that is acknowledged, the notice about
// incomplete password deletions should open. The main CBD dialog
// should stay open during that whole time.
promiseResolver.resolve(
{showHistoryNotice: true, showPasswordsNotice: true});
// Yields to the message loop to allow the callback chain of the
// Promise that was just resolved to execute before the
// assertions.
})
.then(function() {
flush();
const notice =
element.shadowRoot!
.querySelector<SettingsHistoryDeletionDialogElement>(
'#historyNotice');
assertTrue(!!notice);
const noticeActionButton =
notice!.shadowRoot!.querySelector<CrButtonElement>(
'.action-button');
assertTrue(!!noticeActionButton);
// The notice should have replaced the main dialog.
assertFalse(element.$.clearBrowsingDataDialog.open);
assertTrue(notice!.$.dialog.open);
const whenNoticeClosed = eventToPromise('close', notice!);
// Tapping the action button will close the history notice, and
// display the passwords notice instead.
noticeActionButton!.click();
return whenNoticeClosed;
})
.then(function() {
// The passwords notice should have replaced the history notice.
const historyNotice =
element.shadowRoot!.querySelector('#historyNotice');
assertFalse(!!historyNotice);
const passwordsNotice =
element.shadowRoot!.querySelector('#passwordsNotice');
assertTrue(!!passwordsNotice);
})
.then(function() {
flush();
const notice =
element.shadowRoot!
.querySelector<SettingsPasswordsDeletionDialogElement>(
'#passwordsNotice');
assertTrue(!!notice);
const noticeActionButton =
notice!.shadowRoot!.querySelector<CrButtonElement>(
'.action-button');
assertTrue(!!noticeActionButton);
assertFalse(element.$.clearBrowsingDataDialog.open);
assertTrue(notice!.$.dialog.open);
const whenNoticeClosed = eventToPromise('close', notice!);
// Tapping the action button will close the notice.
noticeActionButton!.click();
return whenNoticeClosed;
})
.then(function() {
const notice = element.shadowRoot!.querySelector('#passwordsNotice');
assertFalse(!!notice);
assertFalse(element.$.clearBrowsingDataDialog.open);
});
});
test('Counters', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
const checkbox = element.shadowRoot!.querySelector<SettingsCheckboxElement>(
'#cacheCheckboxBasic')!;
assertEquals('browser.clear_data.cache_basic', checkbox.pref!.key);
// Simulate a browsing data counter result for history. This checkbox's
// sublabel should be updated.
webUIListenerCallback('update-counter-text', checkbox.pref!.key, 'result');
assertEquals('result', checkbox.subLabel);
});
test('history rows are hidden for supervised users', function() {
assertFalse(loadTimeData.getBoolean('isChildAccount'));
assertFalse(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#browsingCheckbox')!.hidden);
assertFalse(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#browsingCheckboxBasic')!.hidden);
assertFalse(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#downloadCheckbox')!.hidden);
element.remove();
testBrowserProxy.reset();
loadTimeData.overrideValues({isChildAccount: true});
element = document.createElement('settings-clear-browsing-data-dialog');
document.body.appendChild(element);
flush();
return testBrowserProxy.whenCalled('initialize').then(function() {
assertTrue(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#browsingCheckbox')!.hidden);
assertTrue(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#browsingCheckboxBasic')!.hidden);
assertTrue(element.shadowRoot!
.querySelector<SettingsCheckboxElement>(
'#downloadCheckbox')!.hidden);
});
});
// <if expr="chromeos_ash or chromeos_lacros">
// On ChromeOS the footer is never shown.
test('ClearBrowsingDataSyncAccountInfo', function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
// Not syncing.
webUIListenerCallback('sync-status-changed', {
signedIn: false,
hasError: false,
});
flush();
assertFalse(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
// Syncing.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: false,
});
flush();
assertFalse(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
// Sync passphrase error.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.ENTER_PASSPHRASE,
});
flush();
assertFalse(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
// Other sync error.
webUIListenerCallback('sync-status-changed', {
signedIn: true,
hasError: true,
statusAction: StatusAction.NO_ACTION,
});
flush();
assertFalse(!!element.shadowRoot!.querySelector(
'#clearBrowsingDataDialog [slot=footer]'));
});
// </if>
});
suite('InstalledApps', function() {
let testBrowserProxy: TestClearBrowsingDataBrowserProxy;
let element: SettingsClearBrowsingDataDialogElement;
const installedApps: InstalledApp[] = [
{
registerableDomain: 'google.com',
reasonBitfield: 0,
exampleOrigin: '',
isChecked: true,
storageSize: 0,
hasNotifications: false,
appName: '',
},
{
registerableDomain: 'yahoo.com',
reasonBitfield: 0,
exampleOrigin: '',
isChecked: true,
storageSize: 0,
hasNotifications: false,
appName: '',
},
];
setup(() => {
loadTimeData.overrideValues({installedAppsInCbd: true});
testBrowserProxy = new TestClearBrowsingDataBrowserProxy();
testBrowserProxy.setInstalledApps(installedApps);
ClearBrowsingDataBrowserProxyImpl.setInstance(testBrowserProxy);
document.body.innerHTML = '';
element = document.createElement('settings-clear-browsing-data-dialog');
element.set('prefs', getClearBrowsingDataPrefs());
document.body.appendChild(element);
return testBrowserProxy.whenCalled('initialize');
});
teardown(() => {
element.remove();
});
test('getInstalledApps', async function() {
assertTrue(element.$.clearBrowsingDataDialog.open);
assertFalse(element.$.installedAppsDialog.open);
// Select cookie checkbox.
element.$.cookiesCheckboxBasic.$.checkbox.click();
assertTrue(element.$.cookiesCheckboxBasic.checked);
// Clear browsing data.
element.$.clearBrowsingDataConfirm.click();
assertTrue(element.$.clearBrowsingDataDialog.open);
await testBrowserProxy.whenCalled('getInstalledApps');
await whenAttributeIs(element.$.installedAppsDialog, 'open', '');
const firstInstalledApp =
element.shadowRoot!.querySelector('installed-app-checkbox');
assertTrue(!!firstInstalledApp);
assertEquals(
'google.com', firstInstalledApp!.installedApp.registerableDomain);
assertTrue(firstInstalledApp!.installedApp.isChecked);
// Choose to keep storage for google.com.
firstInstalledApp!.shadowRoot!.querySelector('cr-checkbox')!.click();
assertFalse(firstInstalledApp!.installedApp.isChecked);
// Confirm deletion.
element.$.installedAppsConfirm.click();
const [dataTypes, _timePeriod, apps] =
await testBrowserProxy.whenCalled('clearBrowsingData');
assertEquals(1, dataTypes.length);
assertEquals('browser.clear_data.cookies_basic', dataTypes[0]);
assertEquals(2, apps.length);
assertEquals('google.com', apps[0].registerableDomain);
assertFalse(apps[0].isChecked);
assertEquals('yahoo.com', apps[1].registerableDomain);
assertTrue(apps[1].isChecked);
});
}); | the_stack |
declare module "react-multi-date-picker" {
import React, { HTMLAttributes } from "react";
import DateObject, { Calendar, Locale } from "react-date-object";
export type Value =
| Date
| string
| number
| DateObject
| Date[]
| string[]
| number[]
| DateObject[]
| null;
export type FunctionalPlugin = { type: string; fn: Function };
export type Plugin = React.ReactElement | FunctionalPlugin;
export interface CalendarProps {
ref?: React.MutableRefObject<any>;
/**
* @types Date | string | number | DateObject
* @types Date[] | string[] | number[] | DateObject[]
* @example
* <Calendar value={new Date()} />
* <DatePicker value={[new Date(), new Date(2020, 2, 12)]} />
*/
value?: Value;
/**
* default calendar is gregorian.
*
* if you want to use other calendars instead of gregorian,
* you must import it from "react-date-object"
*
* Availble calendars:
*
* - gregorian
* - persian
* - arabic
* - indian
*
* @example
* import persian from "react-date-object/calendars/persian"
* <Calendar calendar={persian} />
*
* import indian from "react-date-object/calendars/indian"
* <DatePicker calendar={indian} />
*/
calendar?: Calendar;
/**
* default locale is gregorian_en.
*
* if you want to use other locales instead of gregorian_en,
* you must import it from "react-date-object"
*
* Availble locales:
*
* - gregorian_en
* - gregorian_fa
* - gregorian_ar
* - gregorian_hi
* - persian_en
* - persian_fa
* - persian_ar
* - persian_hi
* - arabic_en
* - arabic_fa
* - arabic_ar
* - arabic_hi
* - indian_en
* - indian_fa
* - indian_ar
* - indian_hi
*
* @example
* import gregorian_fa from "react-date-object/locales/gregorian_fa"
* <Calendar locale={gregorian_fa} />
*
* import gregorian_ar from "react-date-object/locales/gregorian_ar"
* <DatePicker locale={gregorian_ar} />
*/
locale?: Locale;
/**
* @type string
* @default "YYYY/MM/DD"
* @see https://shahabyazdi.github.io/react-multi-date-picker/format-tokens/
* @example
* <Calendar format="MM/DD/YYYY hh:mm:ss a" />
*
* <DatePicker format="MM-DD-YYYY HH:mm:ss" />
*/
format?: string;
onlyMonthPicker?: boolean;
onlyYearPicker?: boolean;
/**
* @example
* <Calendar
* value={[new Date(2020,10,10), new Date(2020,10,14)]}
* range
* />
*
* <DatePicker range />
*/
range?: boolean;
/**
* @example
* <Calendar
* value={[new Date(2020,10,10), new Date(2020,10,14)]}
* multiple
* />
*
* <DatePicker multiple />
*/
multiple?: boolean;
/**
* Calendar wrapper className
*/
className?: string;
/**
* @see https://shahabyazdi.github.io/react-multi-date-picker/locales/
* @example
* <Calendar
* weekDays={[
* "SU",
* "MO",
* "TU",
* "WE",
* "TH",
* "FR",
* "SA"
* ]}
* />
*/
weekDays?: string[] | Array<string[]>;
/**
* @see https://shahabyazdi.github.io/react-multi-date-picker/locales/
* @example
* <Calendar
* months={[
* "jan",
* "feb",
* "mar",
* "apr",
* "may",
* "jun",
* "jul",
* "aug",
* "sep",
* "oct",
* "nov",
* "dec"
* ]}
* />
*/
months?: string[] | Array<string[]>;
/**
* @example
* <Calendar
* onChange={dateObject=>{
* console.log(dateObject.format())
* }}
* />
*
* <DatePicker
* onChange={dateObject=>{
* console.log(JSON.stringify(dateObject))
* }}
* />
*/
onChange?(selectedDates: DateObject | DateObject[] | null): void;
showOtherDays?: boolean;
/**
* the date you set in datepicker as value must be equal or bigger than min date.
*
* otherwise datepicker recognise it as `invalid date` and doesn't format it.
*
* @example
* <DatePicker
* value="2020/12/05"
* minDate="2020/12/05"
* />
*/
minDate?: Date | string | number | DateObject;
/**
* the date you set in datepicker as value must be equal or smaller than max date.
*
* otherwise datepicker recognise it as `invalid date` and doesn't format it.
*
* @example
* <DatePicker
* value="2020/12/01"
* maxDate="2020/12/06"
* />
*/
maxDate?: Date | string | number | DateObject;
/**
* You can customize your calendar days
* with the mapDays Prop and create different properties
* for each of them by returning the Props you want.
* @see https://shahabyazdi.github.io/react-multi-date-picker/map-days/
* @example
* <DatePicker
* mapDays={() => {
* return {
* style: {
* backgroundColor: "brown",
* color: "white"
* }
* }
* }}
* />
*/
mapDays?(object: {
date: DateObject;
selectedDate: DateObject | DateObject[];
currentMonth: object;
isSameDate(arg1: DateObject, arg2: DateObject): boolean;
}): HTMLAttributes<HTMLSpanElement> | void;
disableMonthPicker?: boolean;
disableYearPicker?: boolean;
/**
* @example
* <DatePicker
* format="Date:YYYY/MM/DD, Time:HH:mm:ss"
* formattingIgnoreList={["Date", "Time"]}
* />
*/
formattingIgnoreList?: string[];
/**
* Calendar z-index
* @default 100
*/
zIndex?: number;
/**
* Availble Positions:
* - top
* - bottom
* - left
* - right
*
* @example
*
* <DatePicker
* plugins={[
* <ImportedPlugin position="right" />
* ]}
* />
*/
plugins?: (Plugin | Plugin[])[];
/**
* In Multiple mode, use this Prop to sort the selected dates.
*
* @example
*
* <DatePicker multiple sort />
*/
sort?: boolean;
numberOfMonths?: number;
currentDate?: DateObject;
children?: React.ReactNode;
digits?: string[];
/**
* You can set the buttons prop to false to disable the previous & next buttons.
*
* @example
* <Calendar buttons={false} />
*/
buttons?: boolean;
/**
* You can render your favorite element instead of the previous & next buttons.
*
* @example
* <Calendar renderButton={<CustomButton />} />
*/
renderButton?: React.ReactElement | Function;
/**
* Use this property to change the start day of the week.
*
* Only numbers between 0 and 6 are valid
*
* @example
*
* <Calendar weekStartDayIndex={2} />
*/
weekStartDayIndex?: number;
disableDayPicker?: boolean;
onPropsChange?(props: object): void;
onMonthChange?(date: DateObject): void;
onYearChange?(date: DateObject): void;
onFocusedDateChange?(
focusedDate: DateObject | undefined,
clickedDate: DateObject | undefined
): void;
readOnly?: boolean;
disabled?: boolean;
hideMonth?: boolean;
hideYear?: boolean;
hideWeekDays?: boolean;
shadow?: boolean;
fullYear?: boolean;
displayWeekNumbers?: boolean;
weekNumber?: string;
weekPicker?: boolean;
}
export interface DatePickerProps {
arrow?: boolean | React.ReactElement;
arrowClassName?: string;
arrowStyle?: React.CSSProperties;
/**
* Input name.
* This feature does not work if you render custom input.
*/
name?: string;
id?: string;
title?: string;
required?: boolean;
/**
* Input placeholder.
* This feature does not work if you render custom input.
*/
placeholder?: string;
/**
* Input style.
* This feature does not work if you render custom input.
*/
style?: React.CSSProperties;
/**
* This feature does not work if you render custom input.
*
* You can also use this prop for button and icon type.
*
* Default class names:
*
* - input : `rmdp-input`
*
* - button : `rmdp-button`
*
* Note that when you enter a new className, the default className is automatically `removed`.
*/
inputClass?: string;
/**
* This feature does not work if you render custom input.
*/
disabled?: boolean;
/**
* @example
* <DatePicker
* type="custom"
* render={<CustomComponent/>}
* />
*/
render?: React.ReactElement | Function;
/**
* This feature only affects on `input` in `single` mode
*
* Input modes:
*
* - text
* - numeric
* - decimal
* - none `useful for disabling virtual keyboard`
*
* @default "text"
*/
inputMode?: string;
scrollSensitive?: boolean;
hideOnScroll?: boolean;
/**
* DatePicker container style.
*/
containerStyle?: React.CSSProperties;
/**
* DatePicker container className.
*/
containerClassName?: string;
/**
* Availble positions:
*
* - top or top-center
* - bottom or bottom-center
* - left or left-center
* - right or right-center
* - top-start or top-left
* - bottom-start or bottom-left
* - left-start or left-top
* - right-start or right-top
* - top-end or top-right
* - bottom-end or bottom-right
* - left-end or left-bottom
* - right-end or right-bottom
*
* @see https://shahabyazdi.github.io/react-multi-date-picker/positions/
* @example
*
* <DatePicker
* calendarPosition="bottom-start"
* />
*/
calendarPosition?: string;
animations?: Function[];
/**
* This feature only affects on `input` in `single` mode
*/
editable?: boolean;
/**
* Set it to false if you want to see selected date(s)
* that are not in range of min and max dates in calendar.
* @default true
*/
onlyShowInRangeDates?: boolean;
/**
* Return `false` in case you don't want to open Calendar
*/
onOpen?(): void | boolean;
/**
* Return `false` in case you don't want to close Calendar
*/
onClose?(): void | boolean;
fixMainPosition?: boolean;
fixRelativePosition?: boolean;
offsetY?: number;
offsetX?: number;
onPositionChange?(data: {
popper: {
top: number;
bottom: number;
left: number;
right: number;
height: number;
width: number;
};
element: {
top: number;
bottom: number;
left: number;
right: number;
height: number;
width: number;
};
arrow: {
top: number;
bottom: number;
left: number;
right: number;
height: number;
width: number;
direction: string;
};
position: string;
scroll: {
scrollLeft: number;
scrollTop: number;
};
}): void;
mobileLabels?: { OK: string; CANCEL: string };
portal?: boolean;
portalTarget?: HTMLElement;
}
export { DateObject };
export function Calendar(props: CalendarProps): React.ReactElement;
export function getAllDatesInRange(
range: DateObject[],
toDate?: boolean
): DateObject[] | Date[];
export function toDateObject(date: Date, calendar?: Calendar): DateObject;
export default function DatePicker(
props: CalendarProps & DatePickerProps
): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/date_panel" {
import React, { HTMLAttributes } from "react";
import DateObject from "react-date-object";
interface DatePanelProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
eachDaysInRange?: boolean;
sort?: string;
style?: React.CSSProperties;
className?: string;
onClickDate?(date: DateObject | undefined): void;
removeButton?: boolean;
header?: string;
markFocused?: boolean;
focusedClassName?: string;
formatFunction?(object: {
date: DateObject | undefined;
format: string;
index: number;
}): React.ReactNode;
}
export default function DatePanel(props: DatePanelProps): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/date_picker_header" {
import React, { HTMLAttributes } from "react";
import type { Calendar, Locale } from "react-date-object";
interface DatePickerHeaderProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
size?: string;
calendar?: Calendar;
locale?: Locale;
className?: string;
}
export default function DatePickerHeader(
props: DatePickerHeaderProps
): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/colors" {
import { HTMLAttributes } from "react";
import type { Plugin } from "react-multi-date-picker";
interface ColorsProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
colors?: string[];
defaultColor?: string;
className?: string;
}
export default function colors(object?: ColorsProps): Plugin[];
}
declare module "react-multi-date-picker/plugins/settings" {
import React, { HTMLAttributes } from "react";
interface SettingsProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
calendars?: string[];
locales?: string[];
modes?: string[];
others?: string[];
defaultActive?: string;
disabledList?: string[];
defaultFormat?: {
single?: string;
onlyYearPicker?: string;
onlyMonthPicker?: string;
};
className?: string;
names?: {
gregorian: string;
persian: string;
arabic: string;
indian: string;
en: string;
fa: string;
ar: string;
hi: string;
single: string;
multiple: string;
range: string;
disable: string;
onlyMonthPicker: string;
onlyYearPicker: string;
};
titles?: {
calendar: string;
locale: string;
mode: string;
otherPickers: string;
gregorian: string;
persian: string;
arabic: string;
indian: string;
en: string;
fa: string;
ar: string;
hi: string;
single: string;
multiple: string;
range: string;
disable: string;
onlyMonthPicker: string;
onlyYearPicker: string;
};
}
export default function Settings(props: SettingsProps): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/toolbar" {
import React, { HTMLAttributes } from "react";
interface ToolbarProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
className?: string;
sort?: string[];
names?: { today: string; deselect: string; close: string };
}
export default function Toolbar(props: ToolbarProps): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/highlight_weekends" {
export default function highlightWeekends(weekends?: number[]): {
type: string;
fn: Function;
};
}
declare module "react-multi-date-picker/plugins/time_picker" {
import React, { HTMLAttributes } from "react";
interface TimePickerProps
extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
position?: string;
disabled?: boolean;
hideSeconds?: boolean;
/**
* If the calendar is in multiple or range mode,
* and the time picker position is right or left,
* a select with the default format (YYYY/MM/DD)
* will be added to the time picker.
* So, you can change the format of the select with this prop.
*/
format?: string;
}
export default function TimePicker(
props: TimePickerProps
): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/analog_time_picker" {
import React from "react";
interface TimePickerProps {
position?: string;
disabled?: boolean;
hideSeconds?: boolean;
/**
* If the calendar is in multiple or range mode,
* and the time picker position is right or left,
* a select with the default format (YYYY/MM/DD)
* will be added to the time picker.
* So, you can change the format of the select with this prop.
*/
format?: string;
}
export default function AnalogTimePicker(
props: TimePickerProps
): React.ReactElement;
}
declare module "react-multi-date-picker/plugins/range_picker_footer" {
import React from "react";
interface FooterProps {
position?: string;
disabled?: boolean;
format?: string;
names?: {
selectedDates: string;
from: string;
to: string;
selectDate: string;
close: string;
separator: string;
};
}
export default function Footer(props: FooterProps): React.ReactElement;
}
declare module "react-multi-date-picker/components/button" {
import React, { HTMLAttributes } from "react";
export default function Buttons(
props: HTMLAttributes<HTMLButtonElement>
): React.ReactElement;
}
declare module "react-multi-date-picker/components/input_icon" {
import React, { HTMLAttributes } from "react";
export default function InputIcon(
props: HTMLAttributes<HTMLInputElement>
): React.ReactElement;
}
declare module "react-multi-date-picker/components/icon" {
import React, { SVGAttributes } from "react";
export default function Icon(
props: SVGAttributes<SVGElement>
): React.ReactElement;
} | the_stack |
import Component from "@egjs/component";
import { AnimationManager } from "./AnimationManager";
import { EventManager } from "./EventManager";
import { InterruptManager } from "./InterruptManager";
import { AxisManager, AxisOption, Axis } from "./AxisManager";
import { InputObserver } from "./InputObserver";
import {
TRANSFORM,
DIRECTION_NONE, DIRECTION_LEFT, DIRECTION_RIGHT,
DIRECTION_UP, DIRECTION_DOWN, DIRECTION_HORIZONTAL, DIRECTION_VERTICAL, DIRECTION_ALL
} from "./const";
import { IInputType } from "./inputType/InputType";
import { AxesEvents, ObjectInterface } from "./types";
export interface AxesOption {
easing?: (x: number) => number;
maximumDuration?: number;
minimumDuration?: number;
deceleration?: number;
interruptable?: boolean;
round?: number;
}
/**
* @typedef {Object} AxisOption The Axis information. The key of the axis specifies the name to use as the logical virtual coordinate system.
* @ko 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.
* @property {Number[]} [range] The coordinate of range <ko>좌표 범위</ko>
* @property {Number} [range.0=0] The coordinate of the minimum <ko>최소 좌표</ko>
* @property {Number} [range.1=0] The coordinate of the maximum <ko>최대 좌표</ko>
* @property {Number[]} [bounce] The size of bouncing area. The coordinates can exceed the coordinate area as much as the bouncing area based on user action. If the coordinates does not exceed the bouncing area when an element is dragged, the coordinates where bouncing effects are applied are retuned back into the coordinate area<ko>바운스 영역의 크기. 사용자의 동작에 따라 좌표가 좌표 영역을 넘어 바운스 영역의 크기만큼 더 이동할 수 있다. 사용자가 끌어다 놓는 동작을 했을 때 좌표가 바운스 영역에 있으면, 바운스 효과가 적용된 좌표가 다시 좌표 영역 안으로 들어온다</ko>
* @property {Number} [bounce.0=0] The size of coordinate of the minimum area <ko>최소 좌표 바운스 영역의 크기</ko>
* @property {Number} [bounce.1=0] The size of coordinate of the maximum area <ko>최대 좌표 바운스 영역의 크기</ko>
* @property {Boolean[]} [circular] Indicates whether a circular element is available. If it is set to "true" and an element is dragged outside the coordinate area, the element will appear on the other side.<ko>순환 여부. 'true'로 설정한 방향의 좌표 영역 밖으로 엘리먼트가 이동하면 반대 방향에서 엘리먼트가 나타난다</ko>
* @property {Boolean} [circular.0=false] Indicates whether to circulate to the coordinate of the minimum <ko>최소 좌표 방향의 순환 여부</ko>
* @property {Boolean} [circular.1=false] Indicates whether to circulate to the coordinate of the maximum <ko>최대 좌표 방향의 순환 여부</ko>
**/
/**
* @typedef {Object} AxesOption The option object of the eg.Axes module
* @ko eg.Axes 모듈의 옵션 객체
* @property {Function} [easing=easing.easeOutCubic] The easing function to apply to an animation <ko>애니메이션에 적용할 easing 함수</ko>
* @property {Number} [maximumDuration=Infinity] Maximum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최대 좌표 이동 시간</ko>
* @property {Number} [minimumDuration=0] Minimum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최소 좌표 이동 시간</ko>
* @property {Number} [deceleration=0.0006] Deceleration of the animation where acceleration is manually enabled by user. A higher value indicates shorter running time. <ko>사용자의 동작으로 가속도가 적용된 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다</ko>
* @property {Boolean} [interruptable=true] Indicates whether an animation is interruptible.<br>- true: It can be paused or stopped by user action or the API.<br>- false: It cannot be paused or stopped by user action or the API while it is running.<ko>진행 중인 애니메이션 중지 가능 여부.<br>- true: 사용자의 동작이나 API로 애니메이션을 중지할 수 있다.<br>- false: 애니메이션이 진행 중일 때는 사용자의 동작이나 API가 적용되지 않는다</ko>
* @property {Number} [round = null] Rounding unit. For example, 0.1 rounds to 0.1 decimal point(6.1234 => 6.1), 5 rounds to 5 (93 => 95) <br>[Details](https://github.com/naver/egjs-axes/wiki/round-option)<ko>반올림 단위. 예를 들어 0.1 은 소숫점 0.1 까지 반올림(6.1234 => 6.1), 5 는 5 단위로 반올림(93 => 95).<br>[상세내용](https://github.com/naver/egjs-axes/wiki/round-option)</ko>
**/
/**
* @class eg.Axes
* @classdesc A module used to change the information of user action entered by various input devices such as touch screen or mouse into the logical virtual coordinates. You can easily create a UI that responds to user actions.
* @ko 터치 입력 장치나 마우스와 같은 다양한 입력 장치를 통해 전달 받은 사용자의 동작을 논리적인 가상 좌표로 변경하는 모듈이다. 사용자 동작에 반응하는 UI를 손쉽게 만들수 있다.
* @extends eg.Component
*
* @param {Object.<string, AxisOption>} axis Axis information managed by eg.Axes. The key of the axis specifies the name to use as the logical virtual coordinate system. <ko>eg.Axes가 관리하는 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.</ko>
* @param {AxesOption} [options] The option object of the eg.Axes module<ko>eg.Axes 모듈의 옵션 객체</ko>
* @param {Object.<string, number>} [startPos] The coordinates to be moved when creating an instance. not triggering change event.<ko>인스턴스 생성시 이동할 좌표, change 이벤트는 발생하지 않음.</ko>
*
* @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.3+ (except 3.x)"}
* @example
*
* // 1. Initialize eg.Axes
* const axes = new eg.Axes({
* something1: {
* range: [0, 150],
* bounce: 50
* },
* something2: {
* range: [0, 200],
* bounce: 100
* },
* somethingN: {
* range: [1, 10],
* }
* }, {
* deceleration : 0.0024
* });
*
* // 2. attach event handler
* axes.on({
* "hold" : function(evt) {
* },
* "release" : function(evt) {
* },
* "animationStart" : function(evt) {
* },
* "animationEnd" : function(evt) {
* },
* "change" : function(evt) {
* }
* });
*
* // 3. Initialize inputTypes
* const panInputArea = new eg.Axes.PanInput("#area", {
* scale: [0.5, 1]
* });
* const panInputHmove = new eg.Axes.PanInput("#hmove");
* const panInputVmove = new eg.Axes.PanInput("#vmove");
* const pinchInputArea = new eg.Axes.PinchInput("#area", {
* scale: 1.5
* });
*
* // 4. Connect eg.Axes and InputTypes
* // [PanInput] When the mouse or touchscreen is down and moved.
* // Connect the 'something2' axis to the mouse or touchscreen x position and
* // connect the 'somethingN' axis to the mouse or touchscreen y position.
* axes.connect(["something2", "somethingN"], panInputArea); // or axes.connect("something2 somethingN", panInputArea);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position.
* axes.connect(["something1"], panInputHmove); // or axes.connect("something1", panInputHmove);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position.
* axes.connect(["", "something2"], panInputVmove); // or axes.connect(" something2", panInputVmove);
*
* // [PinchInput] Connect 'something2' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out).
* axes.connect("something2", pinchInputArea);
*/
export default class Axes extends Component<AxesEvents> {
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @type {String}
* @example
* eg.Axes.VERSION; // ex) 3.3.3
* @memberof eg.Axes
*/
static VERSION = "#__VERSION__#";
// for tree shaking
static PanInput;
static PinchInput;
static WheelInput;
static MoveKeyInput;
static RotatePanInput;
/**
* @name eg.Axes.TRANSFORM
* @desc Returns the transform attribute with CSS vendor prefixes.
* @ko CSS vendor prefixes를 붙인 transform 속성을 반환한다.
*
* @constant
* @type {String}
* @example
* eg.Axes.TRANSFORM; // "transform" or "webkitTransform"
*/
static TRANSFORM = TRANSFORM;
/**
* @name eg.Axes.DIRECTION_NONE
* @constant
* @type {Number}
*/
static DIRECTION_NONE = DIRECTION_NONE;
/**
* @name eg.Axes.DIRECTION_LEFT
* @constant
* @type {Number}
*/
static DIRECTION_LEFT = DIRECTION_LEFT;
/**
* @name eg.Axes.DIRECTION_RIGHT
* @constant
* @type {Number}
*/
static DIRECTION_RIGHT = DIRECTION_RIGHT;
/**
* @name eg.Axes.DIRECTION_UP
* @constant
* @type {Number}
*/
static DIRECTION_UP = DIRECTION_UP;
/**
* @name eg.Axes.DIRECTION_DOWN
* @constant
* @type {Number}
*/
static DIRECTION_DOWN = DIRECTION_DOWN;
/**
* @name eg.Axes.DIRECTION_HORIZONTAL
* @constant
* @type {Number}
*/
static DIRECTION_HORIZONTAL = DIRECTION_HORIZONTAL;
/**
* @name eg.Axes.DIRECTION_VERTICAL
* @constant
* @type {Number}
*/
static DIRECTION_VERTICAL = DIRECTION_VERTICAL;
/**
* @name eg.Axes.DIRECTION_ALL
* @constant
* @type {Number}
*/
public static DIRECTION_ALL = DIRECTION_ALL;
public options: AxesOption;
public em: EventManager;
public axm: AxisManager;
public itm: InterruptManager;
public am: AnimationManager;
public io: InputObserver;
private _inputs: IInputType[] = [];
constructor(public axis: ObjectInterface<AxisOption> = {}, options: AxesOption = {}, startPos?: Axis) {
super();
this.options = {
...{
easing: function easeOutCubic(x) {
return 1 - Math.pow(1 - x, 3);
},
interruptable: true,
maximumDuration: Infinity,
minimumDuration: 0,
deceleration: 0.0006,
round: null,
}, ...options,
};
this.itm = new InterruptManager(this.options);
this.axm = new AxisManager(this.axis, this.options);
this.em = new EventManager(this);
this.am = new AnimationManager(this);
this.io = new InputObserver(this);
this.em.setAnimationManager(this.am);
startPos && this.em.triggerChange(startPos);
}
/**
* Connect the axis of eg.Axes to the inputType.
* @ko eg.Axes의 축과 inputType을 연결한다
* @method eg.Axes#connect
* @param {(String[]|String)} axes The name of the axis to associate with inputType <ko>inputType과 연결할 축의 이름</ko>
* @param {Object} inputType The inputType instance to associate with the axis of eg.Axes <ko>eg.Axes의 축과 연결할 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* axes.connect("x", new eg.Axes.PanInput("#area1"))
* .connect("x xOther", new eg.Axes.PanInput("#area2"))
* .connect(" xOther", new eg.Axes.PanInput("#area3"))
* .connect(["x"], new eg.Axes.PanInput("#area4"))
* .connect(["xOther", "x"], new eg.Axes.PanInput("#area5"))
* .connect(["", "xOther"], new eg.Axes.PanInput("#area6"));
*/
connect(axes: string[] | string, inputType: IInputType) {
let mapped;
if (typeof axes === "string") {
mapped = axes.split(" ");
} else {
mapped = axes.concat();
}
// check same instance
if (~this._inputs.indexOf(inputType)) {
this.disconnect(inputType);
}
// check same element in hammer type for share
if ("hammer" in inputType) {
const targets = this._inputs.filter(v => v.hammer && v.element === inputType.element);
if (targets.length) {
inputType.hammer = targets[0].hammer;
}
}
inputType.mapAxes(mapped);
inputType.connect(this.io);
this._inputs.push(inputType);
return this;
}
/**
* Disconnect the axis of eg.Axes from the inputType.
* @ko eg.Axes의 축과 inputType의 연결을 끊는다.
* @method eg.Axes#disconnect
* @param {Object} [inputType] An inputType instance associated with the axis of eg.Axes <ko>eg.Axes의 축과 연결한 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* const input1 = new eg.Axes.PanInput("#area1");
* const input2 = new eg.Axes.PanInput("#area2");
* const input3 = new eg.Axes.PanInput("#area3");
*
* axes.connect("x", input1);
* .connect("x xOther", input2)
* .connect(["xOther", "x"], input3);
*
* axes.disconnect(input1); // disconnects input1
* axes.disconnect(); // disconnects all of them
*/
disconnect(inputType?: IInputType) {
if (inputType) {
const index = this._inputs.indexOf(inputType);
if (index >= 0) {
this._inputs[index].disconnect();
this._inputs.splice(index, 1);
}
} else {
this._inputs.forEach(v => v.disconnect());
this._inputs = [];
}
return this;
}
/**
* Returns the current position of the coordinates.
* @ko 좌표의 현재 위치를 반환한다
* @method eg.Axes#get
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Object.<string, number>} Axis coordinate information <ko>축 좌표 정보</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.get(); // {"x": 0, "xOther": -100, "zoom": 50}
* axes.get(["x", "zoom"]); // {"x": 0, "zoom": 50}
*/
get(axes?: string[]) {
return this.axm.get(axes);
}
/**
* Moves an axis to specific coordinates.
* @ko 좌표를 이동한다.
* @method eg.Axes#setTo
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setTo({"x": 30, "zoom": 60});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setTo({"x": 100, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": 60, "zoom": 60}
*/
setTo(pos: Axis, duration = 0) {
this.am.setTo(pos, duration);
return this;
}
/**
* Moves an axis from the current coordinates to specific coordinates.
* @ko 현재 좌표를 기준으로 좌표를 이동한다.
* @method eg.Axes#setBy
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setBy({"x": 30, "zoom": 10});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setBy({"x": 70, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": -40, "zoom": 60}
*/
setBy(pos: Axis, duration = 0) {
this.am.setBy(pos, duration);
return this;
}
/**
* Returns whether there is a coordinate in the bounce area of the target axis.
* @ko 대상 축 중 bounce영역에 좌표가 존재하는지를 반환한다
* @method eg.Axes#isBounceArea
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Boolen} Whether the bounce area exists. <ko>bounce 영역 존재 여부</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.isBounceArea(["x"]);
* axes.isBounceArea(["x", "zoom"]);
* axes.isBounceArea();
*/
isBounceArea(axes?: string[]) {
return this.axm.isOutside(axes);
}
/**
* Destroys properties, and events used in a module and disconnect all connections to inputTypes.
* @ko 모듈에 사용한 속성, 이벤트를 해제한다. 모든 inputType과의 연결을 끊는다.
* @method eg.Axes#destroy
*/
destroy() {
this.disconnect();
this.em.destroy();
}
} | the_stack |
export as namespace AmazonCognitoIdentity;
// Stubs the XDomainRequest built-in from older IE browsers, does not follow the project's interface naming convention
export interface XDomainRequest {
readonly responseText: string;
timeout: number;
onprogress: () => void;
ontimeout: () => void;
onerror: () => void;
onload: () => void;
open(method: string, url: string): void;
send(data: string): void;
abort(): void;
}
export interface CognitoSessionData {
/**
* The session's Id token.
*/
IdToken?: CognitoIdToken;
/**
* The session's refresh token.
*/
RefreshToken?: CognitoRefreshToken;
/**
* The session's access token.
*/
AccessToken?: CognitoAccessToken;
/**
* The session's token scopes.
*/
TokenScopes?: CognitoTokenScopes;
/**
* The session's state.
*/
State?: string;
}
export interface CognitoAuthOptions {
/**
* Required: User pool application client id.
*/
ClientId: string;
/**
* Required: The application/user-pools Cognito web hostname,this is set at the Cognito console.
*/
AppWebDomain: string;
/**
* Optional: The token scopes
*/
TokenScopesArray?: ReadonlyArray<string>;
/**
* Required: Required: The redirect Uri, which will be launched after authentication as signed in.
*/
RedirectUriSignIn: string;
/**
* Required: The redirect Uri, which will be launched when signed out.
*/
RedirectUriSignOut: string;
/**
* Optional: Pre-selected identity provider (this allows to automatically trigger social provider authentication flow).
*/
IdentityProvider?: string;
/**
* Optional: UserPoolId for the configured cognito userPool.
*/
UserPoolId?: string;
/**
* Optional: boolean flag indicating if the data collection is enabled to support cognito advanced security features. By default, this flag is set to true.
*/
AdvancedSecurityDataCollectionFlag?: boolean;
}
export interface CognitoAuthUserHandler {
onSuccess: (authSession: CognitoAuthSession) => void;
onFailure: (err: any) => void;
}
export interface CognitoConstants {
DOMAIN_SCHEME: string;
DOMAIN_PATH_SIGNIN: string;
DOMAIN_PATH_TOKEN: string;
DOMAIN_PATH_SIGNOUT: string;
DOMAIN_QUERY_PARAM_REDIRECT_URI: string;
DOMAIN_QUERY_PARAM_SIGNOUT_URI: string;
DOMAIN_QUERY_PARAM_RESPONSE_TYPE: string;
DOMAIN_QUERY_PARAM_IDENTITY_PROVIDER: string;
DOMAIN_QUERY_PARAM_USERCONTEXTDATA: string;
CLIENT_ID: string;
STATE: string;
SCOPE: string;
TOKEN: string;
CODE: string;
POST: string;
PARAMETERERROR: string;
SCOPETYPEERROR: string;
QUESTIONMARK: string;
POUNDSIGN: string;
COLONDOUBLESLASH: string;
SLASH: string;
AMPERSAND: string;
EQUALSIGN: string;
SPACE: string;
CONTENTTYPE: string;
CONTENTTYPEVALUE: string;
AUTHORIZATIONCODE: string;
IDTOKEN: string;
ACCESSTOKEN: string;
REFRESHTOKEN: string;
ERROR: string;
ERROR_DESCRIPTION: string;
STRINGTYPE: string;
STATELENGTH: number;
STATEORIGINSTRING: string;
WITHCREDENTIALS: string;
UNDEFINED: string;
SELF: string;
HOSTNAMEREGEX: RegExp;
QUERYPARAMETERREGEX1: RegExp;
QUERYPARAMETERREGEX2: RegExp;
HEADER: { 'Content-Type': string };
}
export class CognitoIdToken {
/**
* Constructs a new CognitoIdToken object
* @param IdToken The JWT Id token
*/
constructor(IdToken: string);
/**
* @returns the record's token.
*/
getJwtToken(): string;
/**
* Sets new value for id token.
* @param idToken The JWT Id token
*/
setJwtToken(idToken: string): void;
/**
* @returns the token's expiration (exp member).
*/
getExpiration(): number;
/**
* @returns the token's payload.
*/
decodePayload(): object;
}
export class CognitoRefreshToken {
/**
* Constructs a new CognitoRefreshToken object
* @param RefreshToken The JWT refresh token.
*/
constructor(RefreshToken: string);
/**
* @returns the record's token.
*/
getToken(): string;
/**
* Sets new value for refresh token.
* @param refreshToken The JWT refresh token.
*/
setToken(refreshToken: string): void;
}
export class CognitoAccessToken {
/**
* Constructs a new CognitoAccessToken object
* @param AccessToken The JWT access token.
*/
constructor(AccessToken: string);
/**
* @returns the record's token.
*/
getJwtToken(): string;
/**
* Sets new value for access token.
* @param accessToken The JWT access token.
*/
setJwtToken(accessToken: string): void;
/**
* @returns the token's expiration (exp member).
*/
getExpiration(): number;
/**
* @returns the username from payload.
*/
getUsername(): string;
/**
* @returns the token's payload.
*/
decodePayload(): object;
}
export class CognitoTokenScopes {
/**
* Constructs a new CognitoTokenScopes object
* @param TokenScopesArray The token scopes
*/
constructor(TokenScopesArray: ReadonlyArray<string>);
/**
* @returns the token scopes.
*/
getScopes(): string[];
/**
* Sets new value for token scopes.
* @param tokenScopes The token scopes
*/
setTokenScopes(tokenScopes: ReadonlyArray<string>): void;
}
export class CognitoAuthSession {
/**
* Constructs a new CognitoUserSession object
* @param sessionData The session's tokens, scopes, and state.
*/
constructor(sessionData: CognitoSessionData);
/**
* @returns the session's Id token
*/
getIdToken(): CognitoIdToken;
/**
* Set a new Id token
* @param IdToken The session's Id token.
*/
setIdToken(IdToken: CognitoIdToken): void;
/**
* @returns the session's refresh token
*/
getRefreshToken(): CognitoRefreshToken;
/**
* Set a new Refresh token
* @param RefreshToken The session's refresh token.
*/
setRefreshToken(RefreshToken: CognitoRefreshToken): void;
/**
* @returns the session's access token
*/
getAccessToken(): CognitoAccessToken;
/**
* Set a new Access token
* @param AccessToken The session's access token.
*/
setAccessToken(AccessToken: CognitoAccessToken): void;
/**
* @returns the session's token scopes
*/
getTokenScopes(): CognitoTokenScopes;
/**
* Set new token scopes
* @param tokenScopes The session's token scopes.
*/
setTokenScopes(tokenScopes: CognitoTokenScopes): void;
/**
* @returns the session's state
*/
getState(): string;
/**
* Set new state
* @param state The session's state.
*/
setState(State: string): void;
/**
* Checks to see if the session is still valid based on session expiry information found
* in Access and Id Tokens and the current time
* @returns if the session is still valid
*/
isValid(): boolean;
}
export class CognitoAuth {
/**
* Called on success or error.
*/
userhandler: CognitoAuthUserHandler;
/**
* Constructs a new CognitoAuth object
* @param options Creation options
*/
constructor(options: CognitoAuthOptions);
/**
* @returns the constants
*/
getCognitoConstants(): CognitoConstants;
/**
* @returns the client id
*/
getClientId(): string;
/**
* @returns the app web domain
*/
getAppWebDomain(): string;
/**
* method for getting the current user of the application from the local storage
*
* @returns the user retrieved from storage
*/
getCurrentUser(): string;
/**
* method for setting the current user's name
* @param Username the user's name
*/
setUser(Username: string): void;
/**
* sets response type to 'code'
*/
useCodeGrantFlow(): void;
/**
* sets response type to 'token'
*/
useImplicitFlow(): void;
/**
* @returns the current session for this user
*/
getSignInUserSession(): CognitoAuthSession;
/**
* @returns the user's username
*/
getUsername(): string;
/**
* @param Username the user's username
*/
setUsername(Username: string): void;
/**
* @returns the user's state
*/
getState(): string;
/**
* @param State the user's state
*/
setState(State: string): void;
/**
* This is used to get a session, either from the session object or from the local storage, or by using a refresh token
* @param RedirectUriSignIn Required: The redirect Uri, which will be launched after authentication.
* @param TokenScopesArray Required: The token scopes, it is an array of strings specifying all scopes for the tokens.
*/
getSession(): void;
/**
* Parse the http request response and proceed according to different response types.
* @param httpRequestResponse the http request response
*/
parseCognitoWebResponse(httpRequestResponse: string): void;
/**
* Get the query parameter map and proceed according to code response type.
* @param Query parameter map
*/
getCodeQueryParameter(map: ReadonlyMap<string, string>): void;
/**
* Get the query parameter map and proceed according to token response type.
* @param Query parameter map
*/
getTokenQueryParameter(map: ReadonlyMap<string, string>): void;
/**
* Get cached tokens and scopes and return a new session using all the cached data.
* @returns the auth session
*/
getCachedSession(): CognitoAuthSession;
/**
* This is used to get last signed in user from local storage
* @returns the last user name
*/
getLastUser(): string;
/**
* This is used to save the session tokens and scopes to local storage.
*/
cacheTokensScopes(): void;
/**
* Compare two sets if they are identical.
* @param set1 one set
* @param set2 the other set
* @returns boolean value is true if two sets are identical
*/
compareSets(set1: ReadonlySet<any>, set2: ReadonlySet<any>): boolean;
/**
* Get the hostname from url.
* @param url the url string
* @returns hostname string
*/
getHostName(url: string): string;
/**
* Get http query parameters and return them as a map.
* @param url the url string
* @param splitMark query parameters split mark (prefix)
* @returns map
*/
getQueryParameters(url: string, splitMark: string): Map<string, string>;
/**
* helper function to generate a random string
* @param length the length of string
* @param chars a original string
* @returns a random value.
*/
generateRandomString(length: number, chars: string): string;
/**
* This is used to clear the session tokens and scopes from local storage
*/
clearCachedTokensScopes(): void;
/**
* This is used to build a user session from tokens retrieved in the authentication result
* @param refreshToken Successful auth response from server.
*/
refreshSession(refreshToken: string): void;
/**
* Make the http POST request.
* @param header header JSON object
* @param body body JSON object
* @param url string
* @param onSuccess callback
* @param onFailure callback
*/
makePOSTRequest(header: object, body: object, url: string,
onSuccess: (responseText: string) => void,
onFailure: (responseText: string) => void): void;
/**
* Create the XHR object
* @param method which method to call
* @param url the url string
* @returns xhr
*/
createCORSRequest(method: string, url: string): XMLHttpRequest | XDomainRequest;
/**
* The http POST request onFailure callback.
* @param err the error object
*/
onFailure(err: any): void;
/**
* The http POST request onSuccess callback when refreshing tokens.
* @param jsonData tokens
*/
onSuccessRefreshToken(jsonData: string): void;
/**
* The http POST request onSuccess callback when exchanging code for tokens.
* @param jsonData tokens
*/
onSuccessExchangeForToken(jsonData: string): void;
/**
* Launch Cognito Auth UI page.
* @param URL the url to launch
*/
launchUri(URL: string): void;
/**
* @returns scopes string
*/
getSpaceSeperatedScopeString(): string;
/**
* Create the FQDN(fully qualified domain name) for authorization endpoint.
* @returns url
*/
getFQDNSignIn(): string;
/**
* Sign out the user.
*/
signOut(): void;
/**
* Create the FQDN(fully qualified domain name) for signout endpoint.
* @returns url
*/
getFQDNSignOut(): string;
/**
* This method returns the encoded data string used for cognito advanced security feature.
* This would be generated only when developer has included the JS used for collecting the
* data on their client. Please refer to documentation to know more about using AdvancedSecurity
* features
*/
getUserContextData(): string;
/**
* Helper method to let the user know if they have either a valid cached session
* or a valid authenticated session from the app integration callback.
* @returns userSignedIn
*/
isUserSignedIn(): boolean;
}
export class DateHelper {
/**
* @returns The current time in "ddd MMM D HH:mm:ss UTC YYYY" format.
*/
getNowString(): string;
}
export class StorageHelper {
/**
* This is used to get a storage object
* @returns the storage
*/
constructor();
/**
* This is used to return the storage
* @returns the storage
*/
getStorage(): Storage;
} | the_stack |
"use strict";
import {
MessageRoom,
Game,
Server,
User,
Utils,
Colors,
Stopwatch,
} from "../../core/core";
import {
Alignment,
Roles,
Role,
GameEndConditions,
priorities,
getRoleColor,
Passives,
WinConditions,
getRoleBackgroundColor,
} from "../classic/roles";
import { ClassicPlayer } from "./classicPlayer";
//import { DEBUGMODE } from "../../app";
import { Phrase } from "../../core/user";
enum Phase {
day = "day",
night = "night",
}
enum Trial {
ended = "ended",
nominate = "nominate",
verdict = "verdict",
}
export enum FinalVote {
guilty = "guilty",
abstain = "abstain",
innocent = "innocent",
}
let fs = require("fs");
let roleLists: { defaultLists: Array<Array<string>> } = JSON.parse(
fs.readFileSync("games/classic/list.json", "utf-8"),
);
let globalMinimumPlayerCount = 4;
//four player games are for debugging only
//if (DEBUGMODE) {
//globalMinimumPlayerCount = 4;
//}
export class Classic extends Game {
private phase: string = Phase.day;
//what stage the trial is in
private trial: string = Trial.ended;
private dayClock: Stopwatch = new Stopwatch();
private daychat: MessageRoom = new MessageRoom();
public mafiachat: MessageRoom = new MessageRoom();
//the interval which counts votes to get the nomination
private tallyInterval: any;
private trialClock: Stopwatch = new Stopwatch();
private readonly maxTrialsPerDay: number = 3;
private trialsThisDay: number = 0;
//days after which there is a stalemate if no deaths
private readonly maxDaysWithoutDeath: number = 3;
private daysWithoutDeath: number = 0;
private deadChat: MessageRoom = new MessageRoom();
public players: Array<ClassicPlayer> = [];
//these are the messages that town crier, thanos etc. send
public announcements: Array<Array<Phrase>> = [];
public generalDiscussionDuration = 2 * 60000;
constructor(server: Server, name: string, uid: string) {
super(
server,
globalMinimumPlayerCount,
15,
"Classic",
name,
uid,
"OpenWerewolf-Classic",
"James Craster",
"Apache-2.0",
);
super.addMessageRoom(this.daychat);
super.addMessageRoom(this.mafiachat);
super.addMessageRoom(this.deadChat);
}
private playersCanVote() {
this.players
.filter(player => player.alive)
.forEach(player => player.user.canVote());
}
private playersCannotVote() {
for (let player of this.players) {
player.user.cannotVote();
}
}
private dayUnmute() {
this.players
.filter(player => player.alive)
.forEach(player => this.daychat.unmute(player.user));
}
//called if the game has gone on too many days without a kill
private stalemate() {
this.daychat.broadcast(
"Three days have passed without a death.",
undefined,
Colors.yellow,
);
this.daychat.broadcast(
"The game has ended in a stalemate.",
undefined,
Colors.yellow,
);
for (let player of this.players) {
player.user.headerSend([
{
text: "The game has ended in a stalemate.",
color: Colors.brightYellow,
},
]);
player.user.headerSend([
{
text: "*** YOU LOSE! ***",
color: Colors.brightRed,
},
]);
}
this.end();
}
/*
* Function that checks if town or mafia have won, and announces their victory.
* Also announces the victory of any other winning faction.
* Returns true if any faction has won, false otherwise.
*/
private winCondition(): boolean {
let townWin = GameEndConditions.townWin(this);
let mafiaWin = GameEndConditions.mafiaWin(this);
if (townWin) {
this.daychat.broadcast("The town have won!", undefined, Colors.green);
this.headerBroadcast([
{ text: "The town have won!", color: Colors.brightGreen },
]);
} else if (mafiaWin) {
this.daychat.broadcast("The mafia have won!", undefined, Colors.red);
this.headerBroadcast([
{ text: "The mafia have won!", color: Colors.brightRed },
]);
}
if (townWin || mafiaWin) {
//announce other factions that have won (that aren't town or mafia)
for (let player of this.players) {
if (
player.winCondition(player, this) &&
player.alignment != Alignment.mafia &&
player.alignment != Alignment.town
) {
if (player.role.color != undefined) {
this.headerBroadcast([
{
text: "The " + player.roleName + " has won!",
color: getRoleColor(player.role),
},
]);
}
}
}
//congratulate winners
for (let player of this.players) {
if (player.winCondition(player, this)) {
player.user.headerSend([
{
text: "*** YOU WIN! ***",
color: Colors.brightGreen,
},
]);
player.user.send([
{ text: "*** YOU WIN! ***", color: Colors.brightGreen },
]);
} else {
player.user.headerSend([
{
text: "*** YOU LOSE! ***",
color: Colors.brightRed,
},
]);
player.user.send([
{ text: "*** YOU LOSE! ***", color: Colors.brightRed },
]);
}
}
//list all winners in the chat
let winners = "";
let count = 0;
for (let player of this.players) {
if (player.winCondition(player, this)) {
if (count == 0) {
winners += player.user.username;
} else {
winners += `, ${player.user.username}`;
}
count++;
}
}
this.broadcast(`Winners: ${winners}`, Colors.brightGreen);
this.end();
}
return townWin || mafiaWin;
}
public start() {
this.beforeStart();
this.broadcastPlayerList();
//map the rolename strings from List.json into role classes
let roleList: Array<Role> = roleLists.defaultLists[
this.users.length - globalMinimumPlayerCount
].map(stringElem => {
return priorities.find(elem => elem.roleName == stringElem) as Role;
});
this.broadcastRoleList(roleList.map(elem => elem.roleName));
let randomDeck = Utils.shuffle(roleList);
this.daychat.muteAll();
//hand out roles
for (let i = 0; i < randomDeck.length; i++) {
this.players.push(new ClassicPlayer(this.users[i], randomDeck[i]));
}
this.players
.filter(elem => elem.alignment == Alignment.mafia)
.forEach(player => {
this.mafiachat.addUser(player.user);
this.mafiachat.mute(player.user);
});
for (let player of this.players) {
//tell the player what their role is
this.sendRole(player);
}
//print the list of roles in the left panel
for (let player of this.players) {
for (let role of roleList.sort(
(a, b) => priorities.indexOf(a) - priorities.indexOf(b),
)) {
player.user.leftSend(role.roleName, getRoleColor(role));
}
}
for (let player of this.players) {
if (player.role.passives.indexOf(Passives.speakWithDead) != -1) {
player.user.send("You have the power to speak with the dead at night.");
this.deadChat.addUser(player.user);
}
}
this.players
.filter(player => player.role.winCondition == WinConditions.lynchTarget)
.forEach(player => {
player.assignLynchTarget(Utils.chooseCombination(this.players, 1)[0]);
player.user.send(
`Your target is ${
player.winLynchTarget!.user.username
} : if they are lynched, you win!`,
);
});
this.setAllTime(5000, 0);
setTimeout(this.night.bind(this), 5000);
}
private sendRole(player: ClassicPlayer) {
player.user.send(
`You are a ${player.role.roleName}`,
undefined,
getRoleBackgroundColor(player.role),
);
player.user.headerSend([
{ text: "You are a ", color: Colors.white },
{ text: player.role.roleName, color: getRoleColor(player.role) },
]);
player.user.emit(
"ownInfoSend",
player.user.username,
player.role.roleName,
getRoleColor(player.role),
);
player.user.emit("role", player.role.roleName, getRoleColor(player.role));
}
private night() {
this.cancelVoteSelection();
this.playersCanVote();
//reset the gallows' animation if they have been used
for (let player of this.players) {
player.user.resetGallows();
}
this.broadcast("Night has fallen.", undefined, Colors.nightBlue);
this.headerBroadcast([
{ text: "Night has fallen", color: Colors.nightBlue },
]);
this.phase = Phase.night;
//Let the mafia communicate with one another
this.mafiachat.unmuteAll();
//if there is no godfather
if (
!this.players.find(elem => elem.role == Roles.godfather && elem.alive)
) {
//promote mafioso to godfather if one exists
if (
!safeCall(
this.players.find(elem => elem.role == Roles.mafioso && elem.alive),
mafioso => {
mafioso.upgradeToGodfather();
this.sendRole(mafioso);
},
)
) {
//there is no mafioso, so promote one of the other mafia
safeCall(
this.players.find(
player => player.alignment == Alignment.mafia && player.alive,
),
mafiaMember => {
mafiaMember.upgradeToGodfather();
this.sendRole(mafiaMember);
},
);
}
}
this.mafiachat.broadcast(
"This is the mafia chat, you can talk to other mafia now in secret.",
);
//tell the mafia who the other mafia are
this.mafiachat.broadcast("The mafia are:");
this.players
.filter(player => player.alignment == Alignment.mafia)
.map(player => player.user.username + " : " + player.role.roleName)
.forEach(elem => this.mafiachat.broadcast(elem));
this.daychat.broadcast("Click on someone to perform your action on them.");
this.setAllTime(60000, 10000);
setTimeout(() => {
Classic.nightResolution(this);
let deaths: number = 0;
//Notify the dead that they have died
for (let player of this.players) {
if (player.diedThisNight) {
player.user.send("You have been killed!", undefined, Colors.red);
deaths++;
}
}
//Reset each player after the night
for (let player of this.players) {
player.resetAfterNight();
}
this.mafiachat.muteAll();
this.cancelVoteSelection();
this.phase = Phase.day;
this.daychat.broadcast("Dawn has broken.", undefined, Colors.yellow);
this.headerBroadcast([
{ text: "Dawn has broken", color: Colors.brightYellow },
]);
this.daychat.unmuteAll();
for (let player of this.players) {
if (!player.alive) {
this.daychat.mute(player.user);
}
}
//Notify the living that the dead have died
this.daychat.broadcast("The deaths:");
if (deaths == 0) {
this.daychat.broadcast("Nobody died.");
} else {
for (let player of this.players) {
if (player.diedThisNight) {
this.daychat.broadcast(player.user.username + " has died.");
this.daychat.mute(player.user);
}
}
}
for (let player of this.players) {
player.diedThisNight = false;
}
this.playersCannotVote();
this.day();
}, 6000);
}
public hang(target: ClassicPlayer) {
target.hang();
this.kill(target);
target.diedThisNight = false;
}
public revive(target: ClassicPlayer) {
target.revive();
this.deadChat.removeUser(target.user);
this.announcements.push([
{
text: `${target.user.username} has been revived`,
color: Colors.standardWhite,
},
]);
}
public kill(target: ClassicPlayer) {
//let the other players know the target has died
this.markAsDead(target.user.username);
target.kill();
if (!this.deadChat.getMemberById(target.user.id)) {
this.deadChat.addUser(target.user);
}
this.daysWithoutDeath = 0;
}
public static nightResolution(game: Classic) {
//sort players based off of the const priorities list
let nightPlayerArray = game.players.sort(
(a, b) => priorities.indexOf(a.role) - priorities.indexOf(b.role),
);
//perform each player's ability in turn
for (let actingPlayer of nightPlayerArray) {
for (let ability of actingPlayer.abilities) {
let targetPlayer = game.getPlayer(actingPlayer.target);
if (targetPlayer) {
//check player can perform ability
if (ability.uses != 0) {
if (!actingPlayer.roleBlocked) {
//check condition of ability is satisfied
if (ability.ability.condition(targetPlayer, game, actingPlayer)) {
ability.ability.action(targetPlayer, game, actingPlayer);
if (ability.uses) {
ability.uses--;
}
}
} else {
actingPlayer.user.send("You were roleblocked!", Colors.brightRed);
}
} else {
actingPlayer.user.send(
"You couldn't perform your ability; out of uses!",
Colors.brightRed,
);
}
}
}
}
}
private day() {
if (!this.winCondition()) {
if (this.daysWithoutDeath == 1) {
this.daychat.broadcast(
"No one died yesterday. If no one dies in the next two days the game will end in a stalemate.",
);
}
if (this.daysWithoutDeath == 2) {
this.daychat.broadcast(
"No one has died for two days. If no one dies by tomorrow morning the game will end in a stalemate.",
);
}
//If no one has died in three days, end the game in a stalemate.
if (this.daysWithoutDeath >= this.maxDaysWithoutDeath) {
this.stalemate();
}
this.daysWithoutDeath++;
this.trialsThisDay = 0;
this.trialClock.restart();
this.trialClock.stop();
//read out all of the announcements
for (let announcement of this.announcements) {
this.headerBroadcast(announcement);
}
setTimeout(() => {
this.daychat.broadcast(
"2 minutes of general discussion until the trials begin. Discuss who to nominate.",
);
//make time to wait shorter if in debug mode
if (false) {
this.setAllTime(20000, 20000);
setTimeout(this.trialVote.bind(this), 20000);
} else {
this.setAllTime(this.generalDiscussionDuration, 20000);
setTimeout(this.trialVote.bind(this), this.generalDiscussionDuration);
}
}, 10000);
}
}
private trialVote() {
if (this.trialsThisDay >= this.maxTrialsPerDay) {
this.daychat.broadcast(
"The town is out of trials - you only get 3 trials a day! Night begins.",
);
this.endDay();
return;
}
this.dayUnmute();
this.cancelVoteSelection();
this.trialClock.start();
this.daychat.broadcast(
"The trial has begun! The player with a majority of votes will be put on trial.",
);
this.daychat.broadcast(
"Max 60 seconds in total. If the target is acquitted you can vote for a new one. At most 3 trials a day.",
);
this.daychat.broadcast("Click on somebody to nominate them.");
this.playersCanVote();
this.setAllTime(Math.max(0, 60000 - this.trialClock.time), 20000);
this.trial = Trial.nominate;
this.dayClock.restart();
this.dayClock.start();
this.tallyInterval = setInterval(this.tallyVotes.bind(this), 1000);
}
private tallyVotes() {
let defendant = 0;
let aliveCount = this.players.filter(player => player.alive).length;
let beginTrial = false;
for (let possibleDefendant of this.players) {
let count = this.players.map(elem => (elem.vote == possibleDefendant.user.id ? 1 : 0)).reduce<number>((acc, val) => acc + val, 0);
if (count >= Math.floor(aliveCount / 2) + 1) {
beginTrial = true;
defendant = this.players.indexOf(possibleDefendant);
break;
}
}
if (beginTrial) {
this.trialClock.stop();
clearInterval(this.tallyInterval);
this.defenseSpeech(defendant);
}
if (this.trialClock.time > 60000) {
this.daychat.broadcast("Time's up! Night will now begin.");
this.endDay();
}
}
private defenseSpeech(defendant: number) {
this.cancelVoteSelection();
this.playersCannotVote();
this.trial = Trial.ended;
this.daychat.broadcast(
this.players[defendant].user.username + " is on trial.",
);
this.daychat.broadcast("The accused can defend themselves for 30 seconds.");
this.daychat.muteAll();
this.daychat.unmute(this.players[defendant].user);
if (false) {
this.setAllTime(5000, 5000);
setTimeout(this.finalVote.bind(this), 5 * 1000, defendant);
} else {
this.setAllTime(30000, 5000);
setTimeout(this.finalVote.bind(this), 30 * 1000, defendant);
}
}
private finalVote(defendant: number) {
this.trial = Trial.verdict;
this.dayUnmute();
this.daychat.broadcast(
"30 seconds to vote: click on guilty or innocent, or do nothing to abstain.",
);
this.headerBroadcast([
{ text: "Vote to decide ", color: Colors.white },
{
text: this.players[defendant].user.username,
color: this.players[defendant].user.color,
},
{ text: "'s fate", color: Colors.white },
]);
setTimeout(() => {
for (let i = 0; i < this.players.length; i++) {
//block the defendant from voting in their own trial
if (i != defendant && this.players[i].alive) {
this.players[i].user.emit("finalVerdict");
}
}
}, 3500);
this.setAllTime(30000, 5000);
setTimeout(this.verdict.bind(this), 30 * 1000, defendant);
}
private verdict(defendant: number) {
this.players.forEach(player => player.user.emit("endVerdict"));
this.daychat.muteAll();
this.trialsThisDay++;
let innocentCount = 0;
let guiltyCount = 0;
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].finalVote == FinalVote.guilty) {
this.daychat.broadcast([
{ text: this.players[i].user.username + " voted " },
{ text: "guilty", color: Colors.brightRed },
]);
guiltyCount++;
} else if (this.players[i].finalVote == FinalVote.innocent) {
this.daychat.broadcast([
{ text: this.players[i].user.username + " voted " },
{ text: "innocent", color: Colors.brightGreen },
]);
innocentCount++;
} else if (this.players[i].alive && i != defendant) {
this.daychat.broadcast([
{ text: this.players[i].user.username + " chose to " },
{ text: "abstain", color: Colors.brightYellow },
]);
}
}
if (guiltyCount > innocentCount) {
this.hang(this.players[defendant]);
this.daychat.broadcast(
this.players[defendant].user.username + " has died.",
);
//play the hanging animation for every player
for (let player of this.players) {
player.user.hang([this.players[defendant].user.username]);
}
this.daychat.broadcast(
"The dead player has 30 seconds for a death speech.",
);
this.setAllTime(30000, 0);
setTimeout(this.endDay.bind(this), 30 * 1000);
} else {
this.daychat.broadcast(
this.players[defendant].user.username + " has been acquitted",
);
if (this.trialClock.time < 60000) {
//reset trial values and call trial vote
this.trial = Trial.ended;
for (let player of this.players) {
player.resetAfterTrial();
}
this.trialVote();
} else {
this.daychat.broadcast("Time's up! Night will now begin.");
this.setAllTime(10000, 0);
setTimeout(this.endDay.bind(this), 10 * 1000);
}
}
}
private endDay() {
this.trialClock.restart();
this.trialClock.stop();
for (let player of this.players) {
player.resetAfterTrial();
}
this.daychat.muteAll();
this.trial = Trial.ended;
clearInterval(this.tallyInterval);
if (!this.winCondition()) {
this.night();
}
}
public disconnect(user: User) {
let player = this.getPlayer(user.id);
if (player instanceof ClassicPlayer) {
this.kill(player);
this.broadcast(player.user.username + " has died.");
}
}
public end() {
//read out all the roles
this.players
.map(player => {
return [
{
text: `${player.user.username} was the `,
color: Colors.standardWhite,
},
{ text: player.role.roleName, color: getRoleColor(player.role) },
];
})
.forEach(elem => this.daychat.broadcast(elem));
//reset initial conditions
this.phase = Phase.day;
this.trial = Trial.ended;
this.dayClock = new Stopwatch();
this.afterEnd();
}
public receive(user: User, msg: string) {
let player = this.getPlayer(user.id);
this.endChat.receive(user, [
{ text: user.username, color: user.color },
{ text: ": " + msg },
]);
if (this.inPlay && player instanceof ClassicPlayer) {
//let medium etc. talk in dead chat at night
if (
player.alive &&
this.phase == Phase.night &&
player.role.passives.indexOf(Passives.speakWithDead) != -1
) {
this.deadChat.receive(player.user, [
{
text: "Hidden",
color: Colors.standardWhite,
italic: false,
},
{ text: ": " + msg, color: Colors.grey, italic: true },
]);
}
if (player.alive) {
//if the message is an in-game command, like voting
if (msg[0] == "/") {
if (Utils.isCommand(msg, "/vote") && this.phase == Phase.night) {
let username = Utils.commandArguments(msg)[0];
let exists = false;
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].user.username == username) {
exists = true;
player.user.send(
"Your choice of '" + username + "' has been received.",
);
if (player.alignment == Alignment.mafia) {
this.mafiachat.broadcast(
`${player.user.username} has chosen to target ${
this.players[i].user.username
}.`,
);
}
player.target = this.players[i].user.id;
if (!this.players[i].alive) {
player.user.send(
"That player is dead - unless you are retributionist, you should pick someone else.",
);
}
}
}
if (!exists) {
player.user.send(
"There's no player called '" + username + "'. Try again.",
);
}
} else if (
Utils.isCommand(msg, "/unvote") &&
this.phase == Phase.night
) {
if (player.target != "") {
player.user.send(
`Your choice of "${
this.getPlayer(player.target)!.user.username
}" has been cancelled.`,
);
if (player.alignment == Alignment.mafia) {
this.mafiachat.broadcast(
`${player.user.username} cancelled their choice.`,
);
}
player.target = "";
}
} else if (
Utils.isCommand(msg, "/vote") &&
this.trial == Trial.nominate
) {
let username = Utils.commandArguments(msg)[0];
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].user.username == username) {
if (this.players[i].alive) {
player.voteFor(this.players[i].user);
this.daychat.broadcast(
player.user.username + " voted for '" + username + "'.",
);
} else {
player.user.send(
"That player is dead, you cannot vote for them.",
);
}
}
}
} else if (
Utils.isCommand(msg, "/unvote") &&
this.trial == Trial.nominate
) {
if (player.vote != "") {
let voteTarget = this.getPlayer(player.vote);
if (voteTarget) {
player.user.send(
"Your vote for " +
voteTarget.user.username +
" has been cancelled.",
);
this.daychat.broadcast(
player.user.username +
" cancelled their vote for " +
voteTarget.user.username,
);
player.clearVote();
}
} else {
player.user.send(
"You cannot cancel your vote as you haven't vote for anyone.",
);
}
} else if (
Utils.isCommand(msg, "/guilty") &&
this.trial == Trial.verdict
) {
player.finalVote = FinalVote.guilty;
player.user.send("You have voted guilty.");
} else if (
(Utils.isCommand(msg, "/innocent") ||
Utils.isCommand(msg, "/inno")) &&
this.trial == Trial.verdict
) {
player.finalVote = FinalVote.innocent;
player.user.send("You have voted innocent.");
}
} else {
//send message to day/mafiachat
this.daychat.receive(player.user, [
{ text: player.user.username, color: player.user.color },
{ text: ": " + msg },
]);
if (player.alignment == Alignment.mafia) {
this.mafiachat.receive(user, [
{ text: player.user.username, color: player.user.color },
{ text: ": " + msg },
]);
}
}
} else {
//player is dead, route their message to dead chat
this.deadChat.receive(player.user, [
{
text: player.user.username,
color: player.user.color,
italic: true,
},
{ text: ": " + msg, color: Colors.grey, italic: true },
]);
}
} else {
//if the sender isn't a user, route their message to day chat as default
this.daychat.receive(user, [
{ text: user.username, color: user.color },
{ text: ": " + msg },
]);
}
}
public makeHost(user: User) {
user.makeHost(
priorities.map(elem => {
return {
roleName: elem.roleName,
color: getRoleColor(elem),
};
}),
);
}
public addUser(user: User) {
//if there is no host, make them the host
if (!this.users.find(elem => elem.isHost)) {
this.makeHost(user);
}
this.daychat.addUser(user);
super.addUser(user);
}
public getPlayer(id: string) {
return this.players.find(player => player.user.id == id);
}
public resendData(user: User) {
let player = this.getPlayer(user.id);
if (player) {
player.user.emit(
"ownInfoSend",
player.user.username,
player.role.roleName,
getRoleColor(player.role),
);
setTimeout(() => {
for (let p of this.players.filter(elem => !elem.alive)) {
(player as ClassicPlayer).user.markAsDead(p.user.username);
}
}, 500);
}
//if the user is the host, on reload they are still the host
if (user.isHost) {
this.makeHost(user);
}
}
public customAdminReceive(user: User, msg: string): void {
if (!this.inPlay) {
//enter list of roles as a single word of first initials
if (Utils.isCommand(msg, "!roles")) {
let roleWord = Utils.commandArguments(msg)[0];
roleLists.defaultLists[
roleWord.length - this.minPlayerCount
] = this.parseRoleWord(roleWord);
}
//show the rolelist for a given number of people
if (Utils.isCommand(msg, "!show")) {
let number = parseInt(Utils.commandArguments(msg)[0]);
user.send(Utils.arrayToCommaSeparated(roleLists.defaultLists[number]));
}
} else {
//set general discussion length, in seconds
if (Utils.isCommand(msg, "!daytime")) {
if (
Utils.commandArguments(msg).length > 0 &&
parseInt(Utils.commandArguments(msg)[0])
) {
this.generalDiscussionDuration =
parseInt(Utils.commandArguments(msg)[0]) * 1000;
}
}
}
}
private parseRoleWord(word: string) {
let out = [];
for (let letter of word) {
switch (letter) {
case "t":
out.push(Roles.townie.roleName);
break;
case "v":
out.push(Roles.vigilante.roleName);
break;
case "s":
out.push(Roles.sherrif.roleName);
break;
case "g":
out.push(Roles.godfather.roleName);
break;
case "m":
out.push(Roles.mafioso.roleName);
break;
case "e":
out.push(Roles.escort.roleName);
break;
case "j":
out.push(Roles.jester.roleName);
break;
case "f":
out.push(Roles.fruitVendor.roleName);
break;
case "d":
out.push(Roles.doctor.roleName);
break;
case "u":
out.push(Roles.medium.roleName);
break;
case "x":
out.push(Roles.executioner.roleName);
break;
case "v":
out.push(Roles.survivor.roleName);
break;
case "c":
out.push(Roles.consort.roleName);
break;
case "a":
out.push(Roles.mafiaVanilla.roleName);
}
}
return out;
}
}
function safeCall<T>(arg: T | undefined, func: (x: T) => any) {
if (arg) {
func(arg);
return true;
} else {
return false;
}
} | the_stack |
import "core-js/stable/array/from";
import "core-js/stable/array/fill";
import "core-js/stable/array/iterator";
import "core-js/stable/promise";
import "core-js/stable/reflect";
import "es6-map/implement";
//import "core-js/stable/symbol";
import "whatwg-fetch";
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version, DisplayMode } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { SPComponentLoader } from '@microsoft/sp-loader';
import { IPropertyPaneConfiguration, PropertyPaneButton, PropertyPaneButtonType, PropertyPaneCheckbox, PropertyPaneLabel, PropertyPaneLink, PropertyPaneTextField, PropertyPaneToggle, PropertyPaneChoiceGroup, IPropertyPaneGroup } from "@microsoft/sp-property-pane";
import { PropertyFieldSwatchColorPicker, PropertyFieldSwatchColorPickerStyle } from '@pnp/spfx-property-controls/lib/PropertyFieldSwatchColorPicker';
import { Logger, LogLevel, ConsoleListener } from "@pnp/logging";
import * as strings from 'hubLinksStrings';
import HubLinks from './components/HubLinks';
import { IHubLinksItem, HubLinksItem, HubLinksItemHeading, IHubLinksGroupItem, HubLinksGroupItem } from './components/IHubLinksItem';
import { HubLinksLayout } from './components/layouts/HubLinksLayout';
import { IHubLinksProps } from './components/HubLinks';
import { PropertyFieldCamlQueryFieldMapping, SPFieldType, SPFieldRequiredLevel, PropertyFieldCamlQueryOrderBy } from '../../propertyPane/propertyFieldCamlQueryFieldMapping/PropertyFieldCamlQueryFieldMapping';
import { PropertyPaneGroupSort } from '../../propertyPane/propertyFieldGroupSort/PropertyFieldGroupSort';
import { sp } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import QueryStringParser from "../../utilities/urlparser/queryStringParser";
import { WebPartLogger } from '../../utilities/webpartlogger/usagelogger';
const titleField = "Title";
const urlField = "URL";
const iconField = "Icon";
const groupingField = "GroupBy";
const descriptionField = "Description";
const openNewTabField = "NewTab";
export interface IHubLinksWebPartProps {
listQuery: string; //advancedCAMLQuery
data: string; //advancedCAMLData
title: string;
defaultExpand: boolean;
hubLinksItems: IHubLinksItem[];
usesListMode: boolean;
layoutMode: HubLinksLayout;
groups: string[]; //For Group Layout, list of groups identified with sort order
showDescription: boolean;
version: string;
tileColor: string;
tileColorProp: string;
tileBorderColor: string;
tileBorderColorProp: string;
tileBackgroundColor: string;
tileBackgroundColorProp: string;
}
export default class HubLinksWebPart extends BaseClientSideWebPart<IHubLinksWebPartProps> {
private LOG_SOURCE = "HubLinksWebPart";
private _webpart: any;
private _activeIndex: number = -1;
private _itemPropertyPane: boolean = false;
constructor() {
super();
}
public async onInit(): Promise<void> {
//Initialize PnPLogger
Logger.subscribe(new ConsoleListener());
Logger.activeLogLevel = LogLevel.Info;
try {
//Initialize PnPJs
let ie11Mode: boolean = (!!window.MSInputMethodContext && !!document["documentMode"]);
sp.setup({ ie11: ie11Mode, spfxContext: this.context });
SPComponentLoader.loadCss('https://use.fontawesome.com/releases/v5.14.0/css/all.css');
const urls: string[] = [];
if (this.properties.data) {
this.properties.hubLinksItems.forEach(element => {
if (element.URL)
urls.push(element.URL);
});
}
//Change theme colors of web part to expected values
if (!this.properties.tileColorProp) this.properties.tileColorProp = "primaryText";
if (!this.properties.tileColor) this.properties.tileColor = window["__themeState__"]["theme"][this.properties.tileColorProp];
else if (this.properties.tileColor !== window["__themeState__"]["theme"][this.properties.tileColorProp]) this.properties.tileColor = window["__themeState__"]["theme"][this.properties.tileColorProp];
if (!this.properties.tileBorderColorProp) this.properties.tileBorderColorProp = "themePrimary";
if (!this.properties.tileBorderColor) this.properties.tileBorderColor = window["__themeState__"]["theme"][this.properties.tileBorderColorProp];
else if (this.properties.tileBorderColor !== window["__themeState__"]["theme"][this.properties.tileBorderColorProp]) this.properties.tileBorderColor = window["__themeState__"]["theme"][this.properties.tileBorderColorProp];
if (!this.properties.tileBackgroundColorProp) this.properties.tileBackgroundColorProp = "white";
if (!this.properties.tileBackgroundColor) this.properties.tileBackgroundColor = window["__themeState__"]["theme"][this.properties.tileBackgroundColorProp];
else if (this.properties.tileBackgroundColor !== window["__themeState__"]["theme"][this.properties.tileBackgroundColorProp]) this.properties.tileBackgroundColor = window["__themeState__"]["theme"][this.properties.tileBackgroundColorProp];
if (this.displayMode !== DisplayMode.Edit)
WebPartLogger.logUsage(this.context, urls);
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (onInit)`, LogLevel.Error);
}
}
public get webpart(): any {
return this._webpart;
}
public get activeIndex(): number {
return this._activeIndex;
}
public set activeIndex(v: number) {
this._activeIndex = v;
}
private _groupItems(items: IHubLinksItem[], groups?: string[]): IHubLinksGroupItem[] {
let retArray: Array<IHubLinksGroupItem> = [];
try {
let groupId: number = 1;
if (groups) {
//Group order defined
groups.forEach(grp => {
retArray.push(new HubLinksGroupItem(new HubLinksItemHeading(grp, groupId), []));
groupId++;
});
}
items.forEach((link, idx) => {
link.index = idx.toString();
const newLink: IHubLinksItem = JSON.parse(JSON.stringify(link));
var newGroup = true;
newLink[groupingField] = link[groupingField] ? link[groupingField] : "Ungrouped";
retArray.forEach(propLink => {
if (propLink.Heading.Title == newLink[groupingField]) {
propLink.Links.push(newLink);
newGroup = false;
}
});
if (newGroup) {
retArray.push(new HubLinksGroupItem(new HubLinksItemHeading(newLink[groupingField], groupId), [newLink]));
groupId++;
}
});
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (groupItems)`, LogLevel.Error);
}
return retArray;
}
public render(): void {
const self = this;
try {
this._checkUpdateProperties();
const element: React.ReactElement<IHubLinksProps> = React.createElement(
HubLinks,
{
defaultExpand: this.properties.defaultExpand,
links: [],
title: this.properties.title,
setTitle: (title: string) => {
self.properties.title = title;
},
isEdit: this.displayMode === DisplayMode.Edit,
textColor: this.properties.tileColorProp,
borderColor: this.properties.tileBorderColorProp,
backgroundColor: this.properties.tileBackgroundColorProp,
hubLinksItems: this.properties.hubLinksItems,
usesListMode: this.properties.usesListMode,
setUrl: (url: string, name: string) => {
if (this.activeIndex === -1) {
this.properties.hubLinksItems.push(new HubLinksItem(null, name, url, "", "", false, "")); //strings.TitlePlaceholder
this.activeIndex = this.properties.hubLinksItems.length - 1;
}
var isDoc = false;
const docExtensions = ["pdf", "xls", "xlsx", "doc", "docx", "ppt", "pptx", "pptm", "dot"];
for (const ext of docExtensions) {
if (url.indexOf(ext, url.length - ext.length) !== -1)
isDoc = true;
}
self.properties.hubLinksItems[this.activeIndex].URL = url + (isDoc ? "?web=1" : "");
self.properties.hubLinksItems[this.activeIndex].Title = name ? name : this.properties.hubLinksItems[this.activeIndex].Title;
if (!this.context.propertyPane.isRenderedByWebPart())
this.context.propertyPane.open();
self.context.propertyPane.refresh();
},
editItem: (index: number) => {
if (index === -1) {
this.properties.hubLinksItems.push(new HubLinksItem(null, "")); //strings.TitlePlaceholder
index = this.properties.hubLinksItems.length - 1;
}
this.activeIndex = index;
this.context.propertyPane.open();
},
deleteItem: (index: number) => {
this.properties.hubLinksItems.splice(index, 1);
this.render();
},
rearrangeItems: (newOrder: [number]) => {
const newArr = new Array<HubLinksItem>();
const currArr = this.properties.hubLinksItems;
for (const num of newOrder)
newArr.push(this.properties.hubLinksItems[num]);
this.properties.hubLinksItems.length = 0;
for (const val of newArr)
this.properties.hubLinksItems.push(val);
},
setGroup: (index: string, group: string) => {
for (var i = 0; i < this.properties.hubLinksItems.length; i++) {
if (this.properties.hubLinksItems[i].index == index)
this.properties.hubLinksItems[i].GroupBy = group;
}
},
resetActiveIndex: () => {
this.activeIndex = -1;
},
advancedCamlData: this.properties.data,
context: this.context,
layoutMode: this.properties.layoutMode,
showDescription: this.properties.showDescription
}
);
if (this.properties.usesListMode) {
const propData = this.properties.data ? JSON.parse(this.properties.data) : { fieldMappings: [], selectedList: {} };
if (propData.selectedList.id) {
sp.web.lists.getById(propData.selectedList.id).getItemsByCAMLQuery({ ViewXml: QueryStringParser.ReplaceQueryStringParameters(this.properties.listQuery) }).then((response: any[]) => {
response.forEach(value => {
const item: any = {};
propData.fieldMappings.forEach(mapping => {
switch (mapping.type) {
case SPFieldType.URL:
item[mapping.name] = value[mapping.mappedTo] ? value[mapping.mappedTo]["Url"] : null;
item[mapping.name + "_text"] = value[mapping.mappedTo] ? value[mapping.mappedTo]["Description"] : null;
break;
default:
item[mapping.name] = value[mapping.mappedTo];
break;
}
});
if (item[urlField] !== null) {
//If has GroupBy field, then make sure it exists on groups property
if (item.GroupBy && this.properties.groups.indexOf(item.GroupBy) < 0) {
//Group not in list, add
this.properties.groups.push(item.GroupBy);
}
element.props.links.push(new HubLinksItem(null, item[urlField + "_text"] === item[urlField] ? item.Title : item[urlField + "_text"], item.URL, item.Description, item.Icon, item.NewTab, item.GroupBy));
}
});
if (this.properties.layoutMode == HubLinksLayout.GroupedListLayout) {
//If group layout, then reform the links into a grouped format
element.props.links = this._groupItems(element.props.links, this.properties.groups);
//Refresh property pane if visible
this.context.propertyPane.refresh();
}
this._webpart = ReactDom.render(element, this.domElement);
}).catch((error) => { });
}
}
else {
//If group layout, then reform the links into a grouped format
if (this.properties.layoutMode == HubLinksLayout.GroupedListLayout) {
element.props.hubLinksItems = this._groupItems(this.properties.hubLinksItems, this.properties.groups);
}
this._webpart = ReactDom.render(element, this.domElement);
}
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (groupItems)`, LogLevel.Error);
return null;
}
}
private _checkUpdateProperties(): void {
try {
if (this.properties.version != this.dataVersion.toString()) {
const dataObj = this.properties.data ? JSON.parse(this.properties.data) :
{
filter: [],
max: 0,
selectedList: {},
sort: {},
fieldMappings: [],
data: {}
};
let groupEnabled: boolean;
if (dataObj.fieldMappings && dataObj.fieldMappings.length > 0) {
groupEnabled = dataObj.fieldMappings.filter((item) => { return item.name === "Group By"; })[0].enabled;
}
dataObj.fieldMappings = [
{ name: urlField, type: SPFieldType.URL, enabled: true, requiredLevel: SPFieldRequiredLevel.Required, mappedTo: dataObj.fieldMappings.filter((item) => { return item.name === "URL"; })[0].mappedTo },
{ name: iconField, type: SPFieldType.Text, enabled: true, requiredLevel: SPFieldRequiredLevel.Required, mappedTo: dataObj.fieldMappings.filter((item) => { return item.name === "Font Awesome Icon"; })[0].mappedTo },
{ name: groupingField, type: SPFieldType.Text, enabled: true, requiredLevel: SPFieldRequiredLevel.Required, mappedTo: dataObj.fieldMappings.filter((item) => { return item.name === "Group By"; })[0].mappedTo },
{ name: descriptionField, type: SPFieldType.Text, enabled: true, requiredLevel: SPFieldRequiredLevel.Required },
{ name: titleField, type: SPFieldType.Text, enabled: true, requiredLevel: SPFieldRequiredLevel.Required, mappedTo: "Title" },
];
this.properties.layoutMode = groupEnabled ? HubLinksLayout.GroupedListLayout : HubLinksLayout.ListLayout;
this.properties.usesListMode = true;
this.properties.showDescription = false;
this.properties.groups = [];
this.properties.hubLinksItems = [];
this.properties.version = this.dataVersion.toString();
this.properties.data = JSON.stringify(dataObj);
}
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (checkUpdateProperties)`, LogLevel.Error);
}
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
public openLinkSelector(event) {
try {
let currentUrl: string = "";
if (this.activeIndex >= 0 && this.properties.hubLinksItems[this.activeIndex] && this.properties.hubLinksItems[this.activeIndex].URL) {
currentUrl = this.properties.hubLinksItems[this.activeIndex].URL;
}
//open the link picker, sending in the current url for reference
this.webpart.openLinkPicker(event, currentUrl);
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (openLinkSelector)`, LogLevel.Error);
}
}
public itemValidation(length: number, required: boolean, errorText: string, value: string): Promise<string> {
return new Promise<string>((resolve: (validationMessage: string) => void) => {
if (value.length > length) {
resolve(errorText);
}
else if (required && value.length < 1) {
resolve(strings.RequiredValueErrorText);
}
else {
resolve("");
}
});
}
private _updateGroupsProperty(): void {
let groups: string[] = [];
try {
for (let i = 0; i < this.properties.hubLinksItems.length; i++) {
let groupName: string = (this.properties.hubLinksItems[i].GroupBy?.length > 0) ? this.properties.hubLinksItems[i].GroupBy : "Ungrouped";
let found: boolean = groups.indexOf(groupName) > -1;
if (!found)
groups.push(groupName);
}
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (_updateGroupsProperty) -- Error processing property field changes.`, LogLevel.Error);
}
this.properties.groups = groups;
}
protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void {
try {
const pathIdx = propertyPath.indexOf('.');
if (propertyPath.substring(pathIdx + 1) === "usesListMode" || propertyPath.substring(pathIdx + 1) == "listQuery") {
//Reset grouping
this.properties.groups = [];
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
} else if (propertyPath.substring(pathIdx + 1) === "GroupBy") {
if (oldValue != newValue) {
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
this._updateGroupsProperty();
}
} else if (propertyPath === "tileColor") {
this.properties.tileColorProp = this.getThemeProperty(newValue);
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
} else if (propertyPath === "tileBorderColor") {
this.properties.tileBorderColorProp = this.getThemeProperty(newValue);
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
} else if (propertyPath === "tileBackgroundColor") {
this.properties.tileBackgroundColorProp = this.getThemeProperty(newValue);
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
} else {
//super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
}
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (onPropertyPaneFieldChanged)`, LogLevel.Error);
}
}
public getThemeProperty(color: string) {
const themePrimary = "themePrimary";
const themePrimaryColor = window["__themeState__"]["theme"][themePrimary];
const themeSecondary = "themeSecondary";
const themeSecondaryColor = window["__themeState__"]["theme"][themeSecondary];
const themeTertiary = "themeTertiary";
const themeTertiaryColor = window["__themeState__"]["theme"][themeTertiary];
const primaryText = "primaryText";
const primaryTextColor = window["__themeState__"]["theme"][primaryText];
const white = "white";
const whiteColor = window["__themeState__"]["theme"][white];
const black = "black";
const blackColor = window["__themeState__"]["theme"][black];
switch (color) {
case themePrimaryColor: return themePrimary;
case themeSecondaryColor: return themeSecondary;
case themeTertiaryColor: return themeTertiary;
case primaryTextColor: return primaryText;
case whiteColor: return white;
case blackColor: return black;
default: return black;
}
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
if (this.context.propertyPane.isRenderedByWebPart()) return this.getEditItemPropertyPane();
return this.getBasicPropertyPane();
}
public getBasicPropertyPane(): IPropertyPaneConfiguration {
//Define base configuration
const config: IPropertyPaneConfiguration = {
pages: [
{
header: {
description: ''
},
groups: [
{
groupName: strings.LayoutLabel,
isCollapsed: false,
groupFields: [
PropertyPaneChoiceGroup("layoutMode", {
label: "",
options: [
{
checked: this.properties.layoutMode === HubLinksLayout.RoundIconItemLayout,
key: HubLinksLayout.RoundIconItemLayout,
iconProps: { officeFabricIconFontName: "BulletedList2" },
text: strings.ItemLayoutLabel
},
{
checked: this.properties.layoutMode === HubLinksLayout.ListLayout,
key: HubLinksLayout.ListLayout,
iconProps: { officeFabricIconFontName: "List" },
text: strings.ListLayoutLabel
},
{
checked: this.properties.layoutMode === HubLinksLayout.GroupedListLayout,
key: HubLinksLayout.GroupedListLayout,
iconProps: { officeFabricIconFontName: "GroupedList" },
text: strings.GroupedListLayoutLabel
},
{
checked: this.properties.layoutMode === HubLinksLayout.GroupedListLayout,
key: HubLinksLayout.TileLayout,
iconProps: { officeFabricIconFontName: "GroupedList" },
text: strings.IconTopLayoutLabel
},
{
checked: this.properties.layoutMode === HubLinksLayout.GroupedListLayout,
key: HubLinksLayout.SquareIconItemLayout,
iconProps: { officeFabricIconFontName: "GroupedList" },
text: strings.IconLeftLayoutLabel
}
]
})
]
}
],
displayGroupsAsAccordion: true
}]
};
try {
//Add alternate configurations based on layout
switch (this.properties.layoutMode) {
case HubLinksLayout.GroupedListLayout:
//Add show description
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneToggle('showDescription', {
label: strings.ShowDescriptionLabel,
onText: strings.OnLabel,
offText: strings.OffLabel
})
);
//Add groups expanded by default
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneToggle('defaultExpand', {
label: strings.ExpandDefaultLabel,
onText: strings.OnLabel,
offText: strings.OffLabel
})
);
//Add Group Sort
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneGroupSort('groups', {
label: strings.GroupSortLabel,
initialValue: this.properties.groups,
render: this.render.bind(this),
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
disabled: false,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'webpartGroupSort'
})
);
break;
case HubLinksLayout.RoundIconItemLayout:
break;
case HubLinksLayout.SquareIconItemLayout:
case HubLinksLayout.TileLayout:
const colors = [
{ label: strings.ThemePrimaryColor, color: window["__themeState__"]["theme"]["themePrimary"] },
{ label: strings.ThemeSecondaryColor, color: window["__themeState__"]["theme"]["themeSecondary"] },
{ label: strings.ThemePrimaryColor, color: window["__themeState__"]["theme"]["themeTertiary"] },
//primaryText no longer consistent
//{label: strings.ThemePrimaryText, color: window["__themeState__"]["theme"]["primaryText"]},
{ label: strings.ThemePrimaryText, color: window["__themeState__"]["theme"]["bodyText"] },
{ label: strings.WhiteColor, color: window["__themeState__"]["theme"]["white"] },
{ label: strings.BlackColor, color: window["__themeState__"]["theme"]["black"] },
];
config.pages[0].groups[0]["groupFields"].push(
PropertyFieldSwatchColorPicker('tileColor', {
label: strings.TileFontColorLabel,
selectedColor: this.properties.tileColor,
colors: colors,
style: PropertyFieldSwatchColorPickerStyle.Full,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
key: 'tileColorFieldId'
})
);
config.pages[0].groups[0]["groupFields"].push(
PropertyFieldSwatchColorPicker('tileBackgroundColor', {
label: strings.TileBackgroundColorLabel,
selectedColor: this.properties.tileBackgroundColor,
colors: colors,
style: PropertyFieldSwatchColorPickerStyle.Full,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
key: 'tileBackgroundColorFieldId'
})
);
config.pages[0].groups[0]["groupFields"].push(
PropertyFieldSwatchColorPicker('tileBorderColor', {
label: strings.TileBorderColorLabel,
selectedColor: this.properties.tileBorderColor,
colors: colors,
style: PropertyFieldSwatchColorPickerStyle.Full,
onPropertyChange: this.onPropertyPaneFieldChanged,
properties: this.properties,
key: 'tileBorderColorFieldId'
})
);
break;
default:
//Add show description
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneToggle('showDescription', {
label: strings.ShowDescriptionLabel,
onText: strings.OnLabel,
offText: strings.OffLabel
})
);
break;
}
//Add usesListMode
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneToggle('usesListMode', {
label: strings.AdvancedEnableListModeLabel,
onText: strings.OnLabel,
offText: strings.OffLabel
})
);
config.pages[0].groups[0]["groupFields"].push(
PropertyPaneLabel('listModeInfo', {
text: strings.AdvancedEnableListModeInfo
})
);
//If usesListMode, the add advanced list mode group
if (this.properties.usesListMode) {
//Build fieldMapping array.
const fieldMappings: Array<any> = [
{ name: urlField, type: SPFieldType.URL, requiredLevel: SPFieldRequiredLevel.Required },
{ name: iconField, type: SPFieldType.Text, requiredLevel: SPFieldRequiredLevel.Required },
{ name: groupingField, type: SPFieldType.Text, requiredLevel: SPFieldRequiredLevel.Required },
{ name: titleField, type: SPFieldType.Text, requiredLevel: SPFieldRequiredLevel.Required },
{ name: openNewTabField, type: SPFieldType.Boolean, requiredLevel: SPFieldRequiredLevel.Required }
];
//If showDescription then add mapping for description field.
if (this.properties.layoutMode === HubLinksLayout.RoundIconItemLayout || this.properties.showDescription) {
fieldMappings.push({ name: descriptionField, type: SPFieldType.Text, requiredLevel: SPFieldRequiredLevel.Required });
}
config.pages[0].groups.push(
{
groupName: strings.AdvancedListModeGroupLabel,
isCollapsed: !this.properties.usesListMode,
groupFields: [
PropertyFieldCamlQueryFieldMapping('listQuery', {
label: strings.ListQueryGroupName,
dataPropertyPath: "data",
query: this.properties.listQuery,
fieldMappings: fieldMappings,
createFields: [
'<Field Type="Text" DisplayName="LinkCategory" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Web Part Columns" ID="{0dfb4045-98b8-4bad-ac61-d9c42f67d262}" SourceID="{a5df0f41-264b-4bf8-a651-222fcdf5d32d}" StaticName="LinkCategory" Name="LinkCategory" Version="5" />',
'<Field ID="{c29e077d-f466-4d8e-8bbe-72b66c5f205c}" Name="URL" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="URL" Group="Base Columns" Type="URL" DisplayName="URL" Required="TRUE"/>',
'<Field Type="Text" DisplayName="FontAwesomeIcon" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Web Part Columns" ID="{6df0c002-e0f6-4801-aa83-b7a5bb80f0f4}" SourceID="{a5df0f41-264b-4bf8-a651-222fcdf5d32d}" StaticName="FontAwesomeIcon" Name="FontAwesomeIcon" Version="5" />',
'<Field Type="Number" DisplayName="SortOrder" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" Group="Web Part Columns" ID="{7a911a9e-dbe1-4a87-bd40-c042db929a80}" SourceID="{a5df0f41-264b-4bf8-a651-222fcdf5d32d}" StaticName="SortOrder" Name="SortOrder" Version="5" />',
'<Field Type="Text" DisplayName="Description" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" MaxLength="255" Group="Web Part Columns" ID="{7350f220-d480-4dd8-89a5-1fafd4cd7d23}" SourceID="{a5df0f41-264b-4bf8-a651-222fcdf5d32d}" StaticName="Description" Name="Description" Version="5" />',
'<Field Type="Boolean" DisplayName="OpenLinkinNewTab" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE" Group="Web Part Columns" ID="{4bf7c60f-0737-49c9-894c-6a31af134242}" SourceID="{4bf7c60f-0737-49c9-894c-6a31af134242}" StaticName="OpenLinkInNewTab" Name="OpenLinkInNewTab" Version="5" />'
],
createTitleRequired: false,
includeHidden: false,
orderBy: PropertyFieldCamlQueryOrderBy.Title,
showOrderBy: true,
showFilters: true,
showMax: false,
showCreate: true,
render: this.render.bind(this),
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
context: this.context,
properties: this.properties,
disabled: false,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'spListQueryFieldId'
})
]
}
);
}
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (getBasicPropertyPane)`, LogLevel.Error);
}
return config;
}
public getEditItemPropertyPane(): IPropertyPaneConfiguration {
let retVal: IPropertyPaneConfiguration = {
pages: [
{
header: {
description: ""
},
displayGroupsAsAccordion: true,
groups: []
}
]
};
try {
let group0: IPropertyPaneGroup = {
groupName: strings.EditItemGeneralLabel,
groupFields: []
};
const titleLength: number = (80 - ((this.properties.hubLinksItems[this.activeIndex]?.Title) ? this.properties.hubLinksItems[this.activeIndex].Title.length : 0));
group0.groupFields.push(PropertyPaneTextField(`hubLinksItems[${this.activeIndex}].Title`, {
label: strings.EditItemGeneralTitleLabel,
description: `${strings.EditItemGeneralTitlePreCountLabel} ${titleLength} ${strings.EditItemGeneralTitlePostCountLabel}`,
//onGetErrorMessage: this.itemValidation.bind(this, 80, true, strings.EditItemGeneralTitleErrorText)
}));
const descriptionLength: number = (130 - ((this.properties.hubLinksItems[this.activeIndex]?.Description) ? this.properties.hubLinksItems[this.activeIndex].Description.length : 0));
group0.groupFields.push(PropertyPaneTextField(`hubLinksItems[${this.activeIndex}].Description`, {
label: strings.EditItemGeneralDescriptionLabel,
description: `${strings.EditItemGeneralDescriptionPreCountLabel} ${descriptionLength} ${strings.EditItemGeneralDescriptionPostCountLabel}`,
onGetErrorMessage: this.itemValidation.bind(this, 130, (this.properties.layoutMode === HubLinksLayout.RoundIconItemLayout || this.properties.showDescription), strings.EditItemGeneralDescriptionErrorText)
}));
const groupByLength: number = (80 - ((this.properties.hubLinksItems[this.activeIndex]?.GroupBy) ? this.properties.hubLinksItems[this.activeIndex].GroupBy.length : 0));
group0.groupFields.push(PropertyPaneTextField(`hubLinksItems[${this.activeIndex}].GroupBy`, {
label: strings.EditItemGeneralGroupByLabel,
description: `${strings.EditItemGeneralGroupByPreCountLabel} ${groupByLength} ${strings.EditItemGeneralGroupByPostCountLabel}`,
onGetErrorMessage: this.itemValidation.bind(this, 80, (this.properties.layoutMode === HubLinksLayout.GroupedListLayout), strings.EditItemGeneralGroupByErrorText)
}));
group0.groupFields = group0.groupFields.concat([
PropertyPaneLabel("itemLinkLabel", {
text: strings.EditItemGeneralSelectLinkLabel
}),
PropertyPaneLink(`hubLinksItems[${this.activeIndex}].URL`, {
target: "_blank",
href: this.properties.hubLinksItems[this.activeIndex]?.URL,
text: this.properties.hubLinksItems[this.activeIndex]?.URL
}),
PropertyPaneButton("itemChangeLink", {
text: strings.EditItemGeneralSelectLinkButtonText,
buttonType: PropertyPaneButtonType.Primary,
onClick: this.openLinkSelector.bind(this)
}),
PropertyPaneCheckbox(`hubLinksItems[${this.activeIndex}].NewTab`, {
text: strings.EditItemGeneralOpenTabLabel
})
]);
retVal.pages[0].groups.push(group0);
let group1: IPropertyPaneGroup = {
groupName: strings.EditItemIconLabel,
groupFields: [
PropertyPaneTextField("hubLinksItems[" + this.activeIndex + "].Icon", {
label: strings.EditItemIconEntryLabel,
placeholder: strings.EditItemIconEntryPlaceholder,
onGetErrorMessage: this.itemValidation.bind(this, 255, (this.properties.layoutMode === HubLinksLayout.RoundIconItemLayout), "")
}),
PropertyPaneLink('iconShortcut', {
text: strings.EditItemIconEntryLinkText,
href: "https://fontawesome.com/icons?d=gallery&m=free",
target: "_blank"
})
]
};
retVal.pages[0].groups.push(group1);
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (getEditItemPropertyPane)`, LogLevel.Error);
}
return retVal;
}
protected onPropertyPaneConfigurationComplete(): void {
let hubLinksItems: IHubLinksItem[] = [];
try {
for (let i = 0; i < this.properties.hubLinksItems.length; i++) {
if (this.properties.hubLinksItems[i].Title?.length > 0)
hubLinksItems.push(this.properties.hubLinksItems[i]);
}
//Update groups and render
this._updateGroupsProperty();
this.properties.hubLinksItems = hubLinksItems;
this.render();
} catch (err) {
Logger.write(`${err} - ${this.LOG_SOURCE} (onPropertyPaneConfigurationComplete)`, LogLevel.Error);
}
}
} | the_stack |
import * as path from 'path';
import { ResourcePart } from '@aws-cdk/assert-internal';
import '@aws-cdk/assert-internal/jest';
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import * as ssm from '@aws-cdk/aws-ssm';
import * as core from '@aws-cdk/core';
import * as constructs from 'constructs';
import * as inc from '../lib';
import * as futils from '../lib/file-utils';
/* eslint-disable quote-props */
/* eslint-disable quotes */
describe('CDK Include', () => {
let stack: core.Stack;
beforeEach(() => {
stack = new core.Stack();
});
test('can ingest a template with only an empty S3 Bucket, and output it unchanged', () => {
includeTestTemplate(stack, 'only-empty-bucket.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('only-empty-bucket.json'),
);
});
test('throws an exception if asked for resource with a logical ID not present in the template', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-empty-bucket.json');
expect(() => {
cfnTemplate.getResource('LogicalIdThatDoesNotExist');
}).toThrow(/Resource with logical ID 'LogicalIdThatDoesNotExist' was not found in the template/);
});
test('can ingest a template with only an empty S3 Bucket, and change its property', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-empty-bucket.json');
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
cfnBucket.bucketName = 'my-bucket-name';
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "my-bucket-name",
},
},
},
});
});
test('can ingest a template with only an S3 Bucket with complex properties, and output it unchanged', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-bucket-complex-props.json');
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
expect((cfnBucket.corsConfiguration as any).corsRules).toHaveLength(1);
expect(stack).toMatchTemplate(
loadTestFileToJsObject('only-bucket-complex-props.json'),
);
});
test('allows referring to a bucket defined in the template in your CDK code', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-empty-bucket.json');
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
const role = new iam.Role(stack, 'Role', {
assumedBy: new iam.AnyPrincipal(),
});
role.addToPolicy(new iam.PolicyStatement({
actions: ['s3:*'],
resources: [cfnBucket.attrArn],
}));
expect(stack).toHaveResourceLike('AWS::IAM::Policy', {
"PolicyDocument": {
"Statement": [
{
"Action": "s3:*",
"Resource": {
"Fn::GetAtt": [
"Bucket",
"Arn",
],
},
},
],
},
});
});
test('can ingest a template with a Bucket Ref-erencing a KMS Key, and output it unchanged', () => {
includeTestTemplate(stack, 'bucket-with-encryption-key.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('bucket-with-encryption-key.json'),
);
});
test('accepts strings for properties with type number', () => {
includeTestTemplate(stack, 'string-for-number.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('string-for-number.json'),
);
});
test('accepts numbers for properties with type string', () => {
includeTestTemplate(stack, 'number-for-string.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('number-for-string.json'),
);
});
test('accepts booleans for properties with type string', () => {
includeTestTemplate(stack, 'boolean-for-string.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('boolean-for-string.json'),
);
});
test('correctly changes the logical IDs, including references, if imported with preserveLogicalIds=false', () => {
const cfnTemplate = includeTestTemplate(stack, 'bucket-with-encryption-key.json', {
preserveLogicalIds: false,
});
// even though the logical IDs in the resulting template are different than in the input template,
// the L1s can still be retrieved using their original logical IDs from the template file,
// and any modifications to them will be reflected in the resulting template
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
cfnBucket.bucketName = 'my-bucket-name';
expect(stack).toMatchTemplate({
"Resources": {
"MyScopeKey7673692F": {
"Type": "AWS::KMS::Key",
"Properties": {
"KeyPolicy": {
"Statement": [
{
"Action": [
"kms:*",
],
"Effect": "Allow",
"Principal": {
"AWS": {
"Fn::Join": ["", [
"arn:",
{ "Ref": "AWS::Partition" },
":iam::",
{ "Ref": "AWS::AccountId" },
":root",
]],
},
},
"Resource": "*",
},
],
"Version": "2012-10-17",
},
},
"DeletionPolicy": "Delete",
"UpdateReplacePolicy": "Delete",
},
"MyScopeBucket02C1313B": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "my-bucket-name",
"BucketEncryption": {
"ServerSideEncryptionConfiguration": [
{
"ServerSideEncryptionByDefault": {
"KMSMasterKeyID": {
"Fn::GetAtt": [
"MyScopeKey7673692F",
"Arn",
],
},
"SSEAlgorithm": "aws:kms",
},
},
],
},
},
"Metadata": {
"Object1": "Location1",
"KeyRef": { "Ref": "MyScopeKey7673692F" },
"KeyArn": { "Fn::GetAtt": ["MyScopeKey7673692F", "Arn"] },
},
"DeletionPolicy": "Retain",
"UpdateReplacePolicy": "Retain",
},
},
});
});
test('can ingest a template with an Fn::If expression for simple values, and output it unchanged', () => {
includeTestTemplate(stack, 'if-simple-property.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('if-simple-property.json'),
);
});
test('can ingest a template with an Fn::If expression for complex values, and output it unchanged', () => {
includeTestTemplate(stack, 'if-complex-property.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('if-complex-property.json'),
);
});
test('can ingest a UserData script, and output it unchanged', () => {
includeTestTemplate(stack, 'user-data.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('user-data.json'),
);
});
test('can correctly ingest a resource with a property of type: Map of Lists of primitive types', () => {
const cfnTemplate = includeTestTemplate(stack, 'ssm-association.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('ssm-association.json'),
);
const association = cfnTemplate.getResource('Association') as ssm.CfnAssociation;
expect(Object.keys(association.parameters as any)).toHaveLength(2);
});
test('can ingest a template with intrinsic functions and conditions, and output it unchanged', () => {
includeTestTemplate(stack, 'functions-and-conditions.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('functions-and-conditions.json'),
);
});
test('can ingest a JSON template with string-form Fn::GetAtt, and output it unchanged', () => {
includeTestTemplate(stack, 'get-att-string-form.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('get-att-string-form.json'),
);
});
test('can ingest a template with Fn::Sub in string form with escaped and unescaped references and output it unchanged', () => {
includeTestTemplate(stack, 'fn-sub-string.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-string.json'),
);
});
test('can parse the string argument Fn::Sub with escaped references that contain whitespace', () => {
includeTestTemplate(stack, 'fn-sub-escaping.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-escaping.json'),
);
});
test('can ingest a template with Fn::Sub in map form and output it unchanged', () => {
includeTestTemplate(stack, 'fn-sub-map-dotted-attributes.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-map-dotted-attributes.json'),
);
});
test('preserves an empty map passed to Fn::Sub', () => {
includeTestTemplate(stack, 'fn-sub-map-empty.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-map-empty.json'),
);
});
test('can ingest a template with Fn::Sub shadowing a logical ID from the template and output it unchanged', () => {
includeTestTemplate(stack, 'fn-sub-shadow.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-shadow.json'),
);
});
test('can ingest a template with Fn::Sub attribute expression shadowing a logical ID from the template, and output it unchanged', () => {
includeTestTemplate(stack, 'fn-sub-shadow-attribute.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-shadow-attribute.json'),
);
});
test('can modify resources used in Fn::Sub in map form references and see the changes in the template', () => {
const cfnTemplate = includeTestTemplate(stack, 'fn-sub-shadow.json');
cfnTemplate.getResource('AnotherBucket').overrideLogicalId('NewBucket');
expect(stack).toHaveResourceLike('AWS::S3::Bucket', {
"BucketName": {
"Fn::Sub": [
"${AnotherBucket}",
{
"AnotherBucket": { "Ref": "NewBucket" },
},
],
},
});
});
test('can modify resources used in Fn::Sub in string form and see the changes in the template', () => {
const cfnTemplate = includeTestTemplate(stack, 'fn-sub-override.json');
cfnTemplate.getResource('Bucket').overrideLogicalId('NewBucket');
expect(stack).toHaveResourceLike('AWS::S3::Bucket', {
"BucketName": {
"Fn::Sub": "${NewBucket}-${!Bucket}-${NewBucket.DomainName}",
},
});
});
test('can ingest a template with Fn::Sub with brace edge cases and output it unchanged', () => {
includeTestTemplate(stack, 'fn-sub-brace-edges.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('fn-sub-brace-edges.json'),
);
});
test('when a parameter in an Fn::Sub expression is substituted with a deploy-time value, it adds a new key to the Fn::Sub map', () => {
const parameter = new core.CfnParameter(stack, 'AnotherParam');
includeTestTemplate(stack, 'fn-sub-parameters.json', {
parameters: {
'MyParam': `it's_a_${parameter.valueAsString}_concatenation`,
},
});
expect(stack).toMatchTemplate({
"Parameters": {
"AnotherParam": {
"Type": "String",
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Sub": [
"${MyParam}",
{
"MyParam": {
"Fn::Join": ["", [
"it's_a_",
{ "Ref": "AnotherParam" },
"_concatenation",
]],
},
},
],
},
},
},
},
});
});
test('can ingest a template with a Ref expression for an array value, and output it unchanged', () => {
includeTestTemplate(stack, 'ref-array-property.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('ref-array-property.json'),
);
});
test('renders non-Resources sections unchanged', () => {
includeTestTemplate(stack, 'only-empty-bucket-with-parameters.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('only-empty-bucket-with-parameters.json'),
);
});
test('resolves DependsOn with a single String value to the actual L1 class instance', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-depends-on.json');
const cfnBucket2 = cfnTemplate.getResource('Bucket2');
expect(cfnBucket2.node.dependencies).toHaveLength(1);
// we always render dependsOn as an array, even if it's a single string
expect(stack).toHaveResourceLike('AWS::S3::Bucket', {
"Properties": {
"BucketName": "bucket2",
},
"DependsOn": [
"Bucket1",
],
}, ResourcePart.CompleteDefinition);
});
test('resolves DependsOn with an array of String values to the actual L1 class instances', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-depends-on-array.json');
const cfnBucket2 = cfnTemplate.getResource('Bucket2');
expect(cfnBucket2.node.dependencies).toHaveLength(2);
expect(stack).toHaveResourceLike('AWS::S3::Bucket', {
"Properties": {
"BucketName": "bucket2",
},
"DependsOn": [
"Bucket0",
"Bucket1",
],
}, ResourcePart.CompleteDefinition);
});
test('correctly parses Conditions and the Condition resource attribute', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-condition.json');
const alwaysFalseCondition = cfnTemplate.getCondition('AlwaysFalseCond');
const cfnBucket = cfnTemplate.getResource('Bucket');
expect(cfnBucket.cfnOptions.condition).toBe(alwaysFalseCondition);
expect(stack).toMatchTemplate(
loadTestFileToJsObject('resource-attribute-condition.json'),
);
});
test('allows Conditions to reference Mappings', () => {
includeTestTemplate(stack, 'condition-using-mapping.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('condition-using-mapping.json'),
);
});
test('correctly change references to Conditions when renaming them', () => {
const cfnTemplate = includeTestTemplate(stack, 'condition-same-name-as-resource.json');
const alwaysFalse = cfnTemplate.getCondition('AlwaysFalse');
alwaysFalse.overrideLogicalId('TotallyFalse');
expect(stack).toMatchTemplate({
"Parameters": {
"Param": {
"Type": "String",
},
},
"Conditions": {
"AlwaysTrue": {
"Fn::Not": [{ "Condition": "TotallyFalse" }],
},
"TotallyFalse": {
"Fn::Equals": [{ "Ref": "Param" }, 2],
},
},
"Resources": {
"AlwaysTrue": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::If": ["TotallyFalse",
{ "Ref": "Param" },
{ "Ref": "AWS::NoValue" }],
},
},
},
},
});
});
test('correctly parses templates with parameters', () => {
const cfnTemplate = includeTestTemplate(stack, 'bucket-with-parameters.json');
const param = cfnTemplate.getParameter('BucketName');
new s3.CfnBucket(stack, 'NewBucket', {
bucketName: param.valueAsString,
});
const originalTemplate = loadTestFileToJsObject('bucket-with-parameters.json');
expect(stack).toMatchTemplate({
"Resources": {
...originalTemplate.Resources,
"NewBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Ref": "BucketName",
},
},
},
},
"Parameters": {
...originalTemplate.Parameters,
},
});
});
test('getParameter() throws an exception if asked for a Parameter with a name that is not present in the template', () => {
const cfnTemplate = includeTestTemplate(stack, 'bucket-with-parameters.json');
expect(() => {
cfnTemplate.getParameter('FakeBucketNameThatDoesNotExist');
}).toThrow(/Parameter with name 'FakeBucketNameThatDoesNotExist' was not found in the template/);
});
test('reflects changes to a retrieved CfnParameter object in the resulting template', () => {
const cfnTemplate = includeTestTemplate(stack, 'bucket-with-parameters.json');
const stringParam = cfnTemplate.getParameter('BucketName');
const numberParam = cfnTemplate.getParameter('CorsMaxAge');
stringParam.default = 'MyDefault';
stringParam.allowedPattern = '[0-9]*$';
stringParam.allowedValues = ['123123', '456789'];
stringParam.constraintDescription = 'MyNewConstraint';
stringParam.description = 'a string of numeric characters';
stringParam.maxLength = 6;
stringParam.minLength = 2;
numberParam.maxValue = 100;
numberParam.minValue = 4;
numberParam.noEcho = false;
numberParam.type = "NewType";
const originalTemplate = loadTestFileToJsObject('bucket-with-parameters.json');
expect(stack).toMatchTemplate({
"Resources": {
...originalTemplate.Resources,
},
"Parameters": {
...originalTemplate.Parameters,
"BucketName": {
...originalTemplate.Parameters.BucketName,
"Default": "MyDefault",
"AllowedPattern": "[0-9]*$",
"AllowedValues": ["123123", "456789"],
"ConstraintDescription": "MyNewConstraint",
"Description": "a string of numeric characters",
"MaxLength": 6,
"MinLength": 2,
},
"CorsMaxAge": {
...originalTemplate.Parameters.CorsMaxAge,
"MaxValue": 100,
"MinValue": 4,
"NoEcho": false,
"Type": "NewType",
},
},
});
});
test('reflects changes to a retrieved CfnCondition object in the resulting template', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-condition.json');
const alwaysFalseCondition = cfnTemplate.getCondition('AlwaysFalseCond');
alwaysFalseCondition.expression = core.Fn.conditionEquals(1, 2);
expect(stack).toMatchTemplate({
"Conditions": {
"AlwaysFalseCond": {
"Fn::Equals": [1, 2],
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Condition": "AlwaysFalseCond",
},
},
});
});
test('correctly handles the CreationPolicy resource attribute', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-creation-policy.json');
const cfnBucket = cfnTemplate.getResource('Bucket');
expect(cfnBucket.cfnOptions.creationPolicy).toBeDefined();
expect(stack).toMatchTemplate(
loadTestFileToJsObject('resource-attribute-creation-policy.json'),
);
});
test('correctly handles the UpdatePolicy resource attribute', () => {
const cfnTemplate = includeTestTemplate(stack, 'resource-attribute-update-policy.json');
const cfnBucket = cfnTemplate.getResource('Bucket');
expect(cfnBucket.cfnOptions.updatePolicy).toBeDefined();
expect(stack).toMatchTemplate(
loadTestFileToJsObject('resource-attribute-update-policy.json'),
);
});
test("correctly handles referencing the ingested template's resources across Stacks", () => {
// for cross-stack sharing to work, we need an App
const app = new core.App();
stack = new core.Stack(app, 'MyStack');
const cfnTemplate = includeTestTemplate(stack, 'only-empty-bucket.json');
const cfnBucket = cfnTemplate.getResource('Bucket') as s3.CfnBucket;
const otherStack = new core.Stack(app, 'OtherStack');
const role = new iam.Role(otherStack, 'Role', {
assumedBy: new iam.AnyPrincipal(),
});
role.addToPolicy(new iam.PolicyStatement({
actions: ['s3:*'],
resources: [cfnBucket.attrArn],
}));
expect(stack).toMatchTemplate({
...loadTestFileToJsObject('only-empty-bucket.json'),
"Outputs": {
"ExportsOutputFnGetAttBucketArn436138FE": {
"Value": {
"Fn::GetAtt": ["Bucket", "Arn"],
},
"Export": {
"Name": "MyStack:ExportsOutputFnGetAttBucketArn436138FE",
},
},
},
});
expect(otherStack).toHaveResourceLike('AWS::IAM::Policy', {
"PolicyDocument": {
"Statement": [
{
"Action": "s3:*",
"Resource": {
"Fn::ImportValue": "MyStack:ExportsOutputFnGetAttBucketArn436138FE",
},
},
],
},
});
});
test('correctly re-names references to resources in the template if their logical IDs have been changed', () => {
const cfnTemplate = includeTestTemplate(stack, 'bucket-with-encryption-key.json');
const cfnKey = cfnTemplate.getResource('Key');
cfnKey.overrideLogicalId('TotallyDifferentKey');
const originalTemplate = loadTestFileToJsObject('bucket-with-encryption-key.json');
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketEncryption": {
"ServerSideEncryptionConfiguration": [
{
"ServerSideEncryptionByDefault": {
"KMSMasterKeyID": {
"Fn::GetAtt": ["TotallyDifferentKey", "Arn"],
},
"SSEAlgorithm": "aws:kms",
},
},
],
},
},
"Metadata": {
"Object1": "Location1",
"KeyRef": { "Ref": "TotallyDifferentKey" },
"KeyArn": { "Fn::GetAtt": ["TotallyDifferentKey", "Arn"] },
},
"DeletionPolicy": "Retain",
"UpdateReplacePolicy": "Retain",
},
"TotallyDifferentKey": originalTemplate.Resources.Key,
},
});
});
test('can include a template with a custom resource that uses attributes', () => {
const cfnTemplate = includeTestTemplate(stack, 'custom-resource-with-attributes.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('custom-resource-with-attributes.json'),
);
const alwaysFalseCondition = cfnTemplate.getCondition('AlwaysFalseCond');
expect(cfnTemplate.getResource('CustomBucket').cfnOptions.condition).toBe(alwaysFalseCondition);
});
test("throws an exception when a custom resource uses a Condition attribute that doesn't exist in the template", () => {
expect(() => {
includeTestTemplate(stack, 'custom-resource-with-bad-condition.json');
}).toThrow(/Resource 'CustomResource' uses Condition 'AlwaysFalseCond' that doesn't exist/);
});
test('can ingest a template that contains outputs and modify them', () => {
const cfnTemplate = includeTestTemplate(stack, 'outputs-with-references.json');
const output = cfnTemplate.getOutput('Output1');
output.value = 'a mutated value';
output.description = undefined;
output.exportName = 'an export';
output.condition = new core.CfnCondition(stack, 'MyCondition', {
expression: core.Fn.conditionIf('AlwaysFalseCond', core.Aws.NO_VALUE, true),
});
const originalTemplate = loadTestFileToJsObject('outputs-with-references.json');
expect(stack).toMatchTemplate({
"Conditions": {
...originalTemplate.Conditions,
"MyCondition": {
"Fn::If": [
"AlwaysFalseCond",
{ "Ref": "AWS::NoValue" },
true,
],
},
},
"Parameters": {
...originalTemplate.Parameters,
},
"Resources": {
...originalTemplate.Resources,
},
"Outputs": {
"Output1": {
"Value": "a mutated value",
"Export": {
"Name": "an export",
},
"Condition": "MyCondition",
},
"OutputWithNoCondition": {
"Value": "some-value",
},
},
});
});
test('can ingest a template that contains outputs and get those outputs', () => {
const cfnTemplate = includeTestTemplate(stack, 'outputs-with-references.json');
const output = cfnTemplate.getOutput('Output1');
expect(output.condition).toBe(cfnTemplate.getCondition('AlwaysFalseCond'));
expect(output.description).toBeDefined();
expect(output.value).toBeDefined();
expect(output.exportName).toBeDefined();
expect(stack).toMatchTemplate(
loadTestFileToJsObject('outputs-with-references.json'),
);
});
test("throws an exception when attempting to retrieve an Output that doesn't exist", () => {
const cfnTemplate = includeTestTemplate(stack, 'outputs-with-references.json');
expect(() => {
cfnTemplate.getOutput('FakeOutput');
}).toThrow(/Output with logical ID 'FakeOutput' was not found in the template/);
});
test('can ingest a template that contains Mappings, and retrieve those Mappings', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-mapping-and-bucket.json');
const someMapping = cfnTemplate.getMapping('SomeMapping');
someMapping.setValue('region', 'key2', 'value2');
expect(stack).toMatchTemplate({
"Mappings": {
"SomeMapping": {
"region": {
"key1": "value1",
"key2": "value2",
},
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::FindInMap": [
"SomeMapping",
{ "Ref": "AWS::Region" },
"key1",
],
},
},
},
},
});
});
test("throws an exception when attempting to retrieve a Mapping that doesn't exist in the template", () => {
const cfnTemplate = includeTestTemplate(stack, 'only-mapping-and-bucket.json');
expect(() => {
cfnTemplate.getMapping('NonExistentMapping');
}).toThrow(/Mapping with name 'NonExistentMapping' was not found in the template/);
});
test('can ingest a template that uses Fn::FindInMap with the first argument being a dynamic reference', () => {
includeTestTemplate(stack, 'find-in-map-with-dynamic-mapping.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('find-in-map-with-dynamic-mapping.json'),
);
});
test('handles renaming Mapping references', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-mapping-and-bucket.json');
const someMapping = cfnTemplate.getMapping('SomeMapping');
someMapping.overrideLogicalId('DifferentMapping');
expect(stack).toMatchTemplate({
"Mappings": {
"DifferentMapping": {
"region": {
"key1": "value1",
},
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::FindInMap": [
"DifferentMapping",
{ "Ref": "AWS::Region" },
"key1",
],
},
},
},
},
});
});
test('can ingest a template that uses Fn::FindInMap for the value of a boolean property', () => {
includeTestTemplate(stack, 'find-in-map-for-boolean-property.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('find-in-map-for-boolean-property.json'),
);
});
test('can ingest a template that contains Rules, and allows retrieving those Rules', () => {
const cfnTemplate = includeTestTemplate(stack, 'only-parameters-and-rule.json');
const rule = cfnTemplate.getRule('TestVpcRule');
expect(rule).toBeDefined();
expect(stack).toMatchTemplate(
loadTestFileToJsObject('only-parameters-and-rule.json'),
);
});
test('fails when trying to replace Parameters referenced in Fn::ValueOf expressions with user-provided values', () => {
expect(() => {
includeTestTemplate(stack, 'only-parameters-and-rule.json', {
parameters: {
'Subnets': ['subnet-1234abcd'],
},
});
}).toThrow(/Cannot substitute parameter 'Subnets' used in Fn::ValueOf expression with attribute 'VpcId'/);
});
test("throws an exception when attempting to retrieve a Rule that doesn't exist in the template", () => {
const cfnTemplate = includeTestTemplate(stack, 'only-parameters-and-rule.json');
expect(() => {
cfnTemplate.getRule('DoesNotExist');
}).toThrow(/Rule with name 'DoesNotExist' was not found in the template/);
});
test('can ingest a template that contains Hooks, and allows retrieving those Hooks', () => {
const cfnTemplate = includeTestTemplate(stack, 'hook-code-deploy-blue-green-ecs.json');
const hook = cfnTemplate.getHook('EcsBlueGreenCodeDeployHook');
expect(hook).toBeDefined();
expect(stack).toMatchTemplate(
loadTestFileToJsObject('hook-code-deploy-blue-green-ecs.json'),
);
});
test("throws an exception when attempting to retrieve a Hook that doesn't exist in the template", () => {
const cfnTemplate = includeTestTemplate(stack, 'hook-code-deploy-blue-green-ecs.json');
expect(() => {
cfnTemplate.getHook('DoesNotExist');
}).toThrow(/Hook with logical ID 'DoesNotExist' was not found in the template/);
});
test('replaces references to parameters with the user-specified values in Resources, Conditions, Metadata, and Options sections', () => {
includeTestTemplate(stack, 'parameter-references.json', {
parameters: {
'MyParam': 'my-s3-bucket',
},
});
expect(stack).toMatchTemplate({
"Transform": {
"Name": "AWS::Include",
"Parameters": {
"Location": "my-s3-bucket",
},
},
"Metadata": {
"Field": {
"Fn::If": [
"AlwaysFalse",
"AWS::NoValue",
"my-s3-bucket",
],
},
},
"Conditions": {
"AlwaysFalse": {
"Fn::Equals": ["my-s3-bucket", "Invalid?BucketName"],
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Metadata": {
"Field": "my-s3-bucket",
},
"Properties": {
"BucketName": "my-s3-bucket",
},
},
},
"Outputs": {
"MyOutput": {
"Value": "my-s3-bucket",
},
},
});
});
test('replaces parameters with falsey values in Ref expressions', () => {
includeTestTemplate(stack, 'resource-attribute-creation-policy.json', {
parameters: {
'CountParameter': 0,
},
});
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"CreationPolicy": {
"AutoScalingCreationPolicy": {
"MinSuccessfulInstancesPercent": 50,
},
"ResourceSignal": {
"Count": 0,
"Timeout": "PT5H4M3S",
},
},
},
},
});
});
test('replaces parameters in Fn::Sub expressions', () => {
includeTestTemplate(stack, 'fn-sub-parameters.json', {
parameters: {
'MyParam': 'my-s3-bucket',
},
});
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Sub": "my-s3-bucket",
},
},
},
},
});
});
test('does not modify Fn::Sub variables shadowing a replaced parameter', () => {
includeTestTemplate(stack, 'fn-sub-shadow-parameter.json', {
parameters: {
'MyParam': 'MyValue',
},
});
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Sub": [
"${MyParam}",
{
"MyParam": "MyValue",
},
],
},
},
},
},
});
});
test('replaces parameters with falsey values in Fn::Sub expressions', () => {
includeTestTemplate(stack, 'fn-sub-parameters.json', {
parameters: {
'MyParam': '',
},
});
expect(stack).toMatchTemplate({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": { "Fn::Sub": "" },
},
},
},
});
});
test('throws an exception when parameters are passed a resource name', () => {
expect(() => {
includeTestTemplate(stack, 'bucket-with-parameters.json', {
parameters: {
'Bucket': 'noChange',
},
});
}).toThrow(/Parameter with logical ID 'Bucket' was not found in the template/);
});
test('throws an exception when provided a parameter to replace that is not in the template with parameters', () => {
expect(() => {
includeTestTemplate(stack, 'bucket-with-parameters.json', {
parameters: {
'FakeParameter': 'DoesNotExist',
},
});
}).toThrow(/Parameter with logical ID 'FakeParameter' was not found in the template/);
});
test('throws an exception when provided a parameter to replace in a template with no parameters', () => {
expect(() => {
includeTestTemplate(stack, 'only-empty-bucket.json', {
parameters: {
'FakeParameter': 'DoesNotExist',
},
});
}).toThrow(/Parameter with logical ID 'FakeParameter' was not found in the template/);
});
test('can ingest a template that contains properties not in the current CFN spec, and output it unchanged', () => {
includeTestTemplate(stack, 'properties-not-in-cfn-spec.json');
expect(stack).toMatchTemplate(
loadTestFileToJsObject('properties-not-in-cfn-spec.json'),
);
});
});
interface IncludeTestTemplateProps {
/** @default true */
readonly preserveLogicalIds?: boolean;
/** @default {} */
readonly parameters?: { [parameterName: string]: any }
}
function includeTestTemplate(scope: constructs.Construct, testTemplate: string, props: IncludeTestTemplateProps = {}): inc.CfnInclude {
return new inc.CfnInclude(scope, 'MyScope', {
templateFile: _testTemplateFilePath(testTemplate),
parameters: props.parameters,
preserveLogicalIds: props.preserveLogicalIds,
});
}
function loadTestFileToJsObject(testTemplate: string): any {
return futils.readJsonSync(_testTemplateFilePath(testTemplate));
}
function _testTemplateFilePath(testTemplate: string) {
return path.join(__dirname, 'test-templates', testTemplate);
} | the_stack |
import * as appscaling from '@aws-cdk/aws-applicationautoscaling';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as ec2 from '@aws-cdk/aws-ec2';
import * as elb from '@aws-cdk/aws-elasticloadbalancing';
import * as elbv2 from '@aws-cdk/aws-elasticloadbalancingv2';
import * as iam from '@aws-cdk/aws-iam';
import * as cloudmap from '@aws-cdk/aws-servicediscovery';
import { Annotations, Duration, IResolvable, IResource, Lazy, Resource, Stack, ArnFormat } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { LoadBalancerTargetOptions, NetworkMode, TaskDefinition } from '../base/task-definition';
import { ICluster, CapacityProviderStrategy, ExecuteCommandLogging, Cluster } from '../cluster';
import { ContainerDefinition, Protocol } from '../container-definition';
import { CfnService } from '../ecs.generated';
import { ScalableTaskCount } from './scalable-task-count';
/**
* The interface for a service.
*/
export interface IService extends IResource {
/**
* The Amazon Resource Name (ARN) of the service.
*
* @attribute
*/
readonly serviceArn: string;
/**
* The name of the service.
*
* @attribute
*/
readonly serviceName: string;
}
/**
* The deployment controller to use for the service.
*/
export interface DeploymentController {
/**
* The deployment controller type to use.
*
* @default DeploymentControllerType.ECS
*/
readonly type?: DeploymentControllerType;
}
/**
* The deployment circuit breaker to use for the service
*/
export interface DeploymentCircuitBreaker {
/**
* Whether to enable rollback on deployment failure
* @default false
*/
readonly rollback?: boolean;
}
export interface EcsTarget {
/**
* The name of the container.
*/
readonly containerName: string;
/**
* The port number of the container. Only applicable when using application/network load balancers.
*
* @default - Container port of the first added port mapping.
*/
readonly containerPort?: number;
/**
* The protocol used for the port mapping. Only applicable when using application load balancers.
*
* @default Protocol.TCP
*/
readonly protocol?: Protocol;
/**
* ID for a target group to be created.
*/
readonly newTargetGroupId: string;
/**
* Listener and properties for adding target group to the listener.
*/
readonly listener: ListenerConfig;
}
/**
* Interface for ECS load balancer target.
*/
export interface IEcsLoadBalancerTarget extends elbv2.IApplicationLoadBalancerTarget, elbv2.INetworkLoadBalancerTarget, elb.ILoadBalancerTarget {
}
/**
* The properties for the base Ec2Service or FargateService service.
*/
export interface BaseServiceOptions {
/**
* The name of the cluster that hosts the service.
*/
readonly cluster: ICluster;
/**
* The desired number of instantiations of the task definition to keep running on the service.
*
* @default - When creating the service, default is 1; when updating the service, default uses
* the current task number.
*/
readonly desiredCount?: number;
/**
* The name of the service.
*
* @default - CloudFormation-generated name.
*/
readonly serviceName?: string;
/**
* The maximum number of tasks, specified as a percentage of the Amazon ECS
* service's DesiredCount value, that can run in a service during a
* deployment.
*
* @default - 100 if daemon, otherwise 200
*/
readonly maxHealthyPercent?: number;
/**
* The minimum number of tasks, specified as a percentage of
* the Amazon ECS service's DesiredCount value, that must
* continue to run and remain healthy during a deployment.
*
* @default - 0 if daemon, otherwise 50
*/
readonly minHealthyPercent?: number;
/**
* The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy
* Elastic Load Balancing target health checks after a task has first started.
*
* @default - defaults to 60 seconds if at least one load balancer is in-use and it is not already set
*/
readonly healthCheckGracePeriod?: Duration;
/**
* The options for configuring an Amazon ECS service to use service discovery.
*
* @default - AWS Cloud Map service discovery is not enabled.
*/
readonly cloudMapOptions?: CloudMapOptions;
/**
* Specifies whether to propagate the tags from the task definition or the service to the tasks in the service
*
* Valid values are: PropagatedTagSource.SERVICE, PropagatedTagSource.TASK_DEFINITION or PropagatedTagSource.NONE
*
* @default PropagatedTagSource.NONE
*/
readonly propagateTags?: PropagatedTagSource;
/**
* Specifies whether to propagate the tags from the task definition or the service to the tasks in the service.
* Tags can only be propagated to the tasks within the service during service creation.
*
* @deprecated Use `propagateTags` instead.
* @default PropagatedTagSource.NONE
*/
readonly propagateTaskTagsFrom?: PropagatedTagSource;
/**
* Specifies whether to enable Amazon ECS managed tags for the tasks within the service. For more information, see
* [Tagging Your Amazon ECS Resources](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html)
*
* @default false
*/
readonly enableECSManagedTags?: boolean;
/**
* Specifies which deployment controller to use for the service. For more information, see
* [Amazon ECS Deployment Types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html)
*
* @default - Rolling update (ECS)
*/
readonly deploymentController?: DeploymentController;
/**
* Whether to enable the deployment circuit breaker. If this property is defined, circuit breaker will be implicitly
* enabled.
* @default - disabled
*/
readonly circuitBreaker?: DeploymentCircuitBreaker;
/**
* A list of Capacity Provider strategies used to place a service.
*
* @default - undefined
*
*/
readonly capacityProviderStrategies?: CapacityProviderStrategy[];
/**
* Whether to enable the ability to execute into a container
*
* @default - undefined
*/
readonly enableExecuteCommand?: boolean;
}
/**
* Complete base service properties that are required to be supplied by the implementation
* of the BaseService class.
*/
export interface BaseServiceProps extends BaseServiceOptions {
/**
* The launch type on which to run your service.
*
* LaunchType will be omitted if capacity provider strategies are specified on the service.
*
* @see - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-capacityproviderstrategy
*
* Valid values are: LaunchType.ECS or LaunchType.FARGATE or LaunchType.EXTERNAL
*/
readonly launchType: LaunchType;
}
/**
* Base class for configuring listener when registering targets.
*/
export abstract class ListenerConfig {
/**
* Create a config for adding target group to ALB listener.
*/
public static applicationListener(listener: elbv2.ApplicationListener, props?: elbv2.AddApplicationTargetsProps): ListenerConfig {
return new ApplicationListenerConfig(listener, props);
}
/**
* Create a config for adding target group to NLB listener.
*/
public static networkListener(listener: elbv2.NetworkListener, props?: elbv2.AddNetworkTargetsProps): ListenerConfig {
return new NetworkListenerConfig(listener, props);
}
/**
* Create and attach a target group to listener.
*/
public abstract addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService): void;
}
/**
* Class for configuring application load balancer listener when registering targets.
*/
class ApplicationListenerConfig extends ListenerConfig {
constructor(private readonly listener: elbv2.ApplicationListener, private readonly props?: elbv2.AddApplicationTargetsProps) {
super();
}
/**
* Create and attach a target group to listener.
*/
public addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService) {
const props = this.props || {};
const protocol = props.protocol;
const port = props.port ?? (protocol === elbv2.ApplicationProtocol.HTTPS ? 443 : 80);
this.listener.addTargets(id, {
... props,
targets: [
service.loadBalancerTarget({
...target,
}),
],
port,
});
}
}
/**
* Class for configuring network load balancer listener when registering targets.
*/
class NetworkListenerConfig extends ListenerConfig {
constructor(private readonly listener: elbv2.NetworkListener, private readonly props?: elbv2.AddNetworkTargetsProps) {
super();
}
/**
* Create and attach a target group to listener.
*/
public addTargets(id: string, target: LoadBalancerTargetOptions, service: BaseService) {
const port = this.props?.port ?? 80;
this.listener.addTargets(id, {
... this.props,
targets: [
service.loadBalancerTarget({
...target,
}),
],
port,
});
}
}
/**
* The interface for BaseService.
*/
export interface IBaseService extends IService {
/**
* The cluster that hosts the service.
*/
readonly cluster: ICluster;
}
/**
* The base class for Ec2Service and FargateService services.
*/
export abstract class BaseService extends Resource
implements IBaseService, elbv2.IApplicationLoadBalancerTarget, elbv2.INetworkLoadBalancerTarget, elb.ILoadBalancerTarget {
/**
* Import an existing ECS/Fargate Service using the service cluster format.
* The format is the "new" format "arn:aws:ecs:region:aws_account_id:service/cluster-name/service-name".
* @see https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids
*/
public static fromServiceArnWithCluster(scope: Construct, id: string, serviceArn: string): IBaseService {
const stack = Stack.of(scope);
const arn = stack.splitArn(serviceArn, ArnFormat.SLASH_RESOURCE_NAME);
const resourceName = arn.resourceName;
if (!resourceName) {
throw new Error('Missing resource Name from service ARN: ${serviceArn}');
}
const resourceNameParts = resourceName.split('/');
if (resourceNameParts.length !== 2) {
throw new Error(`resource name ${resourceName} from service ARN: ${serviceArn} is not using the ARN cluster format`);
}
const clusterName = resourceNameParts[0];
const serviceName = resourceNameParts[1];
const clusterArn = Stack.of(scope).formatArn({
partition: arn.partition,
region: arn.region,
account: arn.account,
service: 'ecs',
resource: 'cluster',
resourceName: clusterName,
});
const cluster = Cluster.fromClusterArn(scope, `${id}Cluster`, clusterArn);
class Import extends Resource implements IBaseService {
public readonly serviceArn = serviceArn;
public readonly serviceName = serviceName;
public readonly cluster = cluster;
}
return new Import(scope, id, {
environmentFromArn: serviceArn,
});
}
/**
* The security groups which manage the allowed network traffic for the service.
*/
public readonly connections: ec2.Connections = new ec2.Connections();
/**
* The Amazon Resource Name (ARN) of the service.
*/
public readonly serviceArn: string;
/**
* The name of the service.
*
* @attribute
*/
public readonly serviceName: string;
/**
* The task definition to use for tasks in the service.
*/
public readonly taskDefinition: TaskDefinition;
/**
* The cluster that hosts the service.
*/
public readonly cluster: ICluster;
/**
* The details of the AWS Cloud Map service.
*/
protected cloudmapService?: cloudmap.Service;
/**
* A list of Elastic Load Balancing load balancer objects, containing the load balancer name, the container
* name (as it appears in a container definition), and the container port to access from the load balancer.
*/
protected loadBalancers = new Array<CfnService.LoadBalancerProperty>();
/**
* A list of Elastic Load Balancing load balancer objects, containing the load balancer name, the container
* name (as it appears in a container definition), and the container port to access from the load balancer.
*/
protected networkConfiguration?: CfnService.NetworkConfigurationProperty;
/**
* The details of the service discovery registries to assign to this service.
* For more information, see Service Discovery.
*/
protected serviceRegistries = new Array<CfnService.ServiceRegistryProperty>();
private readonly resource: CfnService;
private scalableTaskCount?: ScalableTaskCount;
/**
* Constructs a new instance of the BaseService class.
*/
constructor(
scope: Construct,
id: string,
props: BaseServiceProps,
additionalProps: any,
taskDefinition: TaskDefinition) {
super(scope, id, {
physicalName: props.serviceName,
});
if (props.propagateTags && props.propagateTaskTagsFrom) {
throw new Error('You can only specify either propagateTags or propagateTaskTagsFrom. Alternatively, you can leave both blank');
}
this.taskDefinition = taskDefinition;
// launchType will set to undefined if using external DeploymentController or capacityProviderStrategies
const launchType = props.deploymentController?.type === DeploymentControllerType.EXTERNAL ||
props.capacityProviderStrategies !== undefined ?
undefined : props.launchType;
const propagateTagsFromSource = props.propagateTaskTagsFrom ?? props.propagateTags ?? PropagatedTagSource.NONE;
this.resource = new CfnService(this, 'Service', {
desiredCount: props.desiredCount,
serviceName: this.physicalName,
loadBalancers: Lazy.any({ produce: () => this.loadBalancers }, { omitEmptyArray: true }),
deploymentConfiguration: {
maximumPercent: props.maxHealthyPercent || 200,
minimumHealthyPercent: props.minHealthyPercent === undefined ? 50 : props.minHealthyPercent,
deploymentCircuitBreaker: props.circuitBreaker ? {
enable: true,
rollback: props.circuitBreaker.rollback ?? false,
} : undefined,
},
propagateTags: propagateTagsFromSource === PropagatedTagSource.NONE ? undefined : props.propagateTags,
enableEcsManagedTags: props.enableECSManagedTags ?? false,
deploymentController: props.circuitBreaker ? {
type: DeploymentControllerType.ECS,
} : props.deploymentController,
launchType: launchType,
enableExecuteCommand: props.enableExecuteCommand,
capacityProviderStrategy: props.capacityProviderStrategies,
healthCheckGracePeriodSeconds: this.evaluateHealthGracePeriod(props.healthCheckGracePeriod),
/* role: never specified, supplanted by Service Linked Role */
networkConfiguration: Lazy.any({ produce: () => this.networkConfiguration }, { omitEmptyArray: true }),
serviceRegistries: Lazy.any({ produce: () => this.serviceRegistries }, { omitEmptyArray: true }),
...additionalProps,
});
if (props.deploymentController?.type === DeploymentControllerType.EXTERNAL) {
Annotations.of(this).addWarning('taskDefinition and launchType are blanked out when using external deployment controller.');
}
this.serviceArn = this.getResourceArnAttribute(this.resource.ref, {
service: 'ecs',
resource: 'service',
resourceName: `${props.cluster.clusterName}/${this.physicalName}`,
});
this.serviceName = this.getResourceNameAttribute(this.resource.attrName);
this.cluster = props.cluster;
if (props.cloudMapOptions) {
this.enableCloudMap(props.cloudMapOptions);
}
if (props.enableExecuteCommand) {
this.enableExecuteCommand();
const logging = this.cluster.executeCommandConfiguration?.logging ?? ExecuteCommandLogging.DEFAULT;
if (this.cluster.executeCommandConfiguration?.kmsKey) {
this.enableExecuteCommandEncryption(logging);
}
if (logging !== ExecuteCommandLogging.NONE) {
this.executeCommandLogConfiguration();
}
}
this.node.defaultChild = this.resource;
}
/**
* The CloudMap service created for this service, if any.
*/
public get cloudMapService(): cloudmap.IService | undefined {
return this.cloudmapService;
}
private executeCommandLogConfiguration() {
const logConfiguration = this.cluster.executeCommandConfiguration?.logConfiguration;
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'logs:DescribeLogGroups',
],
resources: ['*'],
}));
const logGroupArn = logConfiguration?.cloudWatchLogGroup ? `arn:${this.stack.partition}:logs:${this.env.region}:${this.env.account}:log-group:${logConfiguration.cloudWatchLogGroup.logGroupName}:*` : '*';
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'logs:CreateLogStream',
'logs:DescribeLogStreams',
'logs:PutLogEvents',
],
resources: [logGroupArn],
}));
if (logConfiguration?.s3Bucket?.bucketName) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:GetBucketLocation',
],
resources: ['*'],
}));
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:PutObject',
],
resources: [`arn:${this.stack.partition}:s3:::${logConfiguration.s3Bucket.bucketName}/*`],
}));
if (logConfiguration.s3EncryptionEnabled) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
's3:GetEncryptionConfiguration',
],
resources: [`arn:${this.stack.partition}:s3:::${logConfiguration.s3Bucket.bucketName}`],
}));
}
}
}
private enableExecuteCommandEncryption(logging: ExecuteCommandLogging) {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'kms:Decrypt',
'kms:GenerateDataKey',
],
resources: [`${this.cluster.executeCommandConfiguration?.kmsKey?.keyArn}`],
}));
this.cluster.executeCommandConfiguration?.kmsKey?.addToResourcePolicy(new iam.PolicyStatement({
actions: [
'kms:*',
],
resources: ['*'],
principals: [new iam.ArnPrincipal(`arn:${this.stack.partition}:iam::${this.env.account}:root`)],
}));
if (logging === ExecuteCommandLogging.DEFAULT || this.cluster.executeCommandConfiguration?.logConfiguration?.cloudWatchEncryptionEnabled) {
this.cluster.executeCommandConfiguration?.kmsKey?.addToResourcePolicy(new iam.PolicyStatement({
actions: [
'kms:Encrypt*',
'kms:Decrypt*',
'kms:ReEncrypt*',
'kms:GenerateDataKey*',
'kms:Describe*',
],
resources: ['*'],
principals: [new iam.ServicePrincipal(`logs.${this.env.region}.amazonaws.com`)],
conditions: {
ArnLike: { 'kms:EncryptionContext:aws:logs:arn': `arn:${this.stack.partition}:logs:${this.env.region}:${this.env.account}:*` },
},
}));
}
}
/**
* This method is called to attach this service to an Application Load Balancer.
*
* Don't call this function directly. Instead, call `listener.addTargets()`
* to add this service to a load balancer.
*/
public attachToApplicationTargetGroup(targetGroup: elbv2.IApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
return this.defaultLoadBalancerTarget.attachToApplicationTargetGroup(targetGroup);
}
/**
* Registers the service as a target of a Classic Load Balancer (CLB).
*
* Don't call this. Call `loadBalancer.addTarget()` instead.
*/
public attachToClassicLB(loadBalancer: elb.LoadBalancer): void {
return this.defaultLoadBalancerTarget.attachToClassicLB(loadBalancer);
}
/**
* Return a load balancing target for a specific container and port.
*
* Use this function to create a load balancer target if you want to load balance to
* another container than the first essential container or the first mapped port on
* the container.
*
* Use the return value of this function where you would normally use a load balancer
* target, instead of the `Service` object itself.
*
* @example
*
* declare const listener: elbv2.ApplicationListener;
* declare const service: ecs.BaseService;
* listener.addTargets('ECS', {
* port: 80,
* targets: [service.loadBalancerTarget({
* containerName: 'MyContainer',
* containerPort: 1234,
* })],
* });
*/
public loadBalancerTarget(options: LoadBalancerTargetOptions): IEcsLoadBalancerTarget {
const self = this;
const target = this.taskDefinition._validateTarget(options);
const connections = self.connections;
return {
attachToApplicationTargetGroup(targetGroup: elbv2.ApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
targetGroup.registerConnectable(self, self.taskDefinition._portRangeFromPortMapping(target.portMapping));
return self.attachToELBv2(targetGroup, target.containerName, target.portMapping.containerPort);
},
attachToNetworkTargetGroup(targetGroup: elbv2.NetworkTargetGroup): elbv2.LoadBalancerTargetProps {
return self.attachToELBv2(targetGroup, target.containerName, target.portMapping.containerPort);
},
connections,
attachToClassicLB(loadBalancer: elb.LoadBalancer): void {
return self.attachToELB(loadBalancer, target.containerName, target.portMapping.containerPort);
},
};
}
/**
* Use this function to create all load balancer targets to be registered in this service, add them to
* target groups, and attach target groups to listeners accordingly.
*
* Alternatively, you can use `listener.addTargets()` to create targets and add them to target groups.
*
* @example
*
* declare const listener: elbv2.ApplicationListener;
* declare const service: ecs.BaseService;
* service.registerLoadBalancerTargets(
* {
* containerName: 'web',
* containerPort: 80,
* newTargetGroupId: 'ECS',
* listener: ecs.ListenerConfig.applicationListener(listener, {
* protocol: elbv2.ApplicationProtocol.HTTPS
* }),
* },
* )
*/
public registerLoadBalancerTargets(...targets: EcsTarget[]) {
for (const target of targets) {
target.listener.addTargets(target.newTargetGroupId, {
containerName: target.containerName,
containerPort: target.containerPort,
protocol: target.protocol,
}, this);
}
}
/**
* This method is called to attach this service to a Network Load Balancer.
*
* Don't call this function directly. Instead, call `listener.addTargets()`
* to add this service to a load balancer.
*/
public attachToNetworkTargetGroup(targetGroup: elbv2.INetworkTargetGroup): elbv2.LoadBalancerTargetProps {
return this.defaultLoadBalancerTarget.attachToNetworkTargetGroup(targetGroup);
}
/**
* An attribute representing the minimum and maximum task count for an AutoScalingGroup.
*/
public autoScaleTaskCount(props: appscaling.EnableScalingProps) {
if (this.scalableTaskCount) {
throw new Error('AutoScaling of task count already enabled for this service');
}
return this.scalableTaskCount = new ScalableTaskCount(this, 'TaskCount', {
serviceNamespace: appscaling.ServiceNamespace.ECS,
resourceId: `service/${this.cluster.clusterName}/${this.serviceName}`,
dimension: 'ecs:service:DesiredCount',
role: this.makeAutoScalingRole(),
...props,
});
}
/**
* Enable CloudMap service discovery for the service
*
* @returns The created CloudMap service
*/
public enableCloudMap(options: CloudMapOptions): cloudmap.Service {
const sdNamespace = options.cloudMapNamespace ?? this.cluster.defaultCloudMapNamespace;
if (sdNamespace === undefined) {
throw new Error('Cannot enable service discovery if a Cloudmap Namespace has not been created in the cluster.');
}
// Determine DNS type based on network mode
const networkMode = this.taskDefinition.networkMode;
if (networkMode === NetworkMode.NONE) {
throw new Error('Cannot use a service discovery if NetworkMode is None. Use Bridge, Host or AwsVpc instead.');
}
// Bridge or host network mode requires SRV records
let dnsRecordType = options.dnsRecordType;
if (networkMode === NetworkMode.BRIDGE || networkMode === NetworkMode.HOST) {
if (dnsRecordType === undefined) {
dnsRecordType = cloudmap.DnsRecordType.SRV;
}
if (dnsRecordType !== cloudmap.DnsRecordType.SRV) {
throw new Error('SRV records must be used when network mode is Bridge or Host.');
}
}
// Default DNS record type for AwsVpc network mode is A Records
if (networkMode === NetworkMode.AWS_VPC) {
if (dnsRecordType === undefined) {
dnsRecordType = cloudmap.DnsRecordType.A;
}
}
const { containerName, containerPort } = determineContainerNameAndPort({
taskDefinition: this.taskDefinition,
dnsRecordType: dnsRecordType!,
container: options.container,
containerPort: options.containerPort,
});
const cloudmapService = new cloudmap.Service(this, 'CloudmapService', {
namespace: sdNamespace,
name: options.name,
dnsRecordType: dnsRecordType!,
customHealthCheck: { failureThreshold: options.failureThreshold || 1 },
dnsTtl: options.dnsTtl,
});
const serviceArn = cloudmapService.serviceArn;
// add Cloudmap service to the ECS Service's serviceRegistry
this.addServiceRegistry({
arn: serviceArn,
containerName,
containerPort,
});
this.cloudmapService = cloudmapService;
return cloudmapService;
}
/**
* Associates this service with a CloudMap service
*/
public associateCloudMapService(options: AssociateCloudMapServiceOptions): void {
const service = options.service;
const { containerName, containerPort } = determineContainerNameAndPort({
taskDefinition: this.taskDefinition,
dnsRecordType: service.dnsRecordType,
container: options.container,
containerPort: options.containerPort,
});
// add Cloudmap service to the ECS Service's serviceRegistry
this.addServiceRegistry({
arn: service.serviceArn,
containerName,
containerPort,
});
}
/**
* This method returns the specified CloudWatch metric name for this service.
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/ECS',
metricName,
dimensionsMap: { ClusterName: this.cluster.clusterName, ServiceName: this.serviceName },
...props,
}).attachTo(this);
}
/**
* This method returns the CloudWatch metric for this service's memory utilization.
*
* @default average over 5 minutes
*/
public metricMemoryUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('MemoryUtilization', props);
}
/**
* This method returns the CloudWatch metric for this service's CPU utilization.
*
* @default average over 5 minutes
*/
public metricCpuUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('CPUUtilization', props);
}
/**
* This method is called to create a networkConfiguration.
* @deprecated use configureAwsVpcNetworkingWithSecurityGroups instead.
*/
// eslint-disable-next-line max-len
protected configureAwsVpcNetworking(vpc: ec2.IVpc, assignPublicIp?: boolean, vpcSubnets?: ec2.SubnetSelection, securityGroup?: ec2.ISecurityGroup) {
if (vpcSubnets === undefined) {
vpcSubnets = assignPublicIp ? { subnetType: ec2.SubnetType.PUBLIC } : {};
}
if (securityGroup === undefined) {
securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });
}
this.connections.addSecurityGroup(securityGroup);
this.networkConfiguration = {
awsvpcConfiguration: {
assignPublicIp: assignPublicIp ? 'ENABLED' : 'DISABLED',
subnets: vpc.selectSubnets(vpcSubnets).subnetIds,
securityGroups: Lazy.list({ produce: () => [securityGroup!.securityGroupId] }),
},
};
}
/**
* This method is called to create a networkConfiguration.
*/
// eslint-disable-next-line max-len
protected configureAwsVpcNetworkingWithSecurityGroups(vpc: ec2.IVpc, assignPublicIp?: boolean, vpcSubnets?: ec2.SubnetSelection, securityGroups?: ec2.ISecurityGroup[]) {
if (vpcSubnets === undefined) {
vpcSubnets = assignPublicIp ? { subnetType: ec2.SubnetType.PUBLIC } : {};
}
if (securityGroups === undefined || securityGroups.length === 0) {
securityGroups = [new ec2.SecurityGroup(this, 'SecurityGroup', { vpc })];
}
securityGroups.forEach((sg) => { this.connections.addSecurityGroup(sg); }, this);
this.networkConfiguration = {
awsvpcConfiguration: {
assignPublicIp: assignPublicIp ? 'ENABLED' : 'DISABLED',
subnets: vpc.selectSubnets(vpcSubnets).subnetIds,
securityGroups: securityGroups.map((sg) => sg.securityGroupId),
},
};
}
private renderServiceRegistry(registry: ServiceRegistry): CfnService.ServiceRegistryProperty {
return {
registryArn: registry.arn,
containerName: registry.containerName,
containerPort: registry.containerPort,
};
}
/**
* Shared logic for attaching to an ELB
*/
private attachToELB(loadBalancer: elb.LoadBalancer, containerName: string, containerPort: number): void {
if (this.taskDefinition.networkMode === NetworkMode.AWS_VPC) {
throw new Error('Cannot use a Classic Load Balancer if NetworkMode is AwsVpc. Use Host or Bridge instead.');
}
if (this.taskDefinition.networkMode === NetworkMode.NONE) {
throw new Error('Cannot use a Classic Load Balancer if NetworkMode is None. Use Host or Bridge instead.');
}
this.loadBalancers.push({
loadBalancerName: loadBalancer.loadBalancerName,
containerName,
containerPort,
});
}
/**
* Shared logic for attaching to an ELBv2
*/
private attachToELBv2(targetGroup: elbv2.ITargetGroup, containerName: string, containerPort: number): elbv2.LoadBalancerTargetProps {
if (this.taskDefinition.networkMode === NetworkMode.NONE) {
throw new Error('Cannot use a load balancer if NetworkMode is None. Use Bridge, Host or AwsVpc instead.');
}
this.loadBalancers.push({
targetGroupArn: targetGroup.targetGroupArn,
containerName,
containerPort,
});
// Service creation can only happen after the load balancer has
// been associated with our target group(s), so add ordering dependency.
this.resource.node.addDependency(targetGroup.loadBalancerAttached);
const targetType = this.taskDefinition.networkMode === NetworkMode.AWS_VPC ? elbv2.TargetType.IP : elbv2.TargetType.INSTANCE;
return { targetType };
}
private get defaultLoadBalancerTarget() {
return this.loadBalancerTarget({
containerName: this.taskDefinition.defaultContainer!.containerName,
});
}
/**
* Generate the role that will be used for autoscaling this service
*/
private makeAutoScalingRole(): iam.IRole {
// Use a Service Linked Role.
return iam.Role.fromRoleArn(this, 'ScalingRole', Stack.of(this).formatArn({
region: '',
service: 'iam',
resource: 'role/aws-service-role/ecs.application-autoscaling.amazonaws.com',
resourceName: 'AWSServiceRoleForApplicationAutoScaling_ECSService',
}));
}
/**
* Associate Service Discovery (Cloud Map) service
*/
private addServiceRegistry(registry: ServiceRegistry) {
if (this.serviceRegistries.length >= 1) {
throw new Error('Cannot associate with the given service discovery registry. ECS supports at most one service registry per service.');
}
const sr = this.renderServiceRegistry(registry);
this.serviceRegistries.push(sr);
}
/**
* Return the default grace period when load balancers are configured and
* healthCheckGracePeriod is not already set
*/
private evaluateHealthGracePeriod(providedHealthCheckGracePeriod?: Duration): IResolvable {
return Lazy.any({
produce: () => providedHealthCheckGracePeriod?.toSeconds() ?? (this.loadBalancers.length > 0 ? 60 : undefined),
});
}
private enableExecuteCommand() {
this.taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({
actions: [
'ssmmessages:CreateControlChannel',
'ssmmessages:CreateDataChannel',
'ssmmessages:OpenControlChannel',
'ssmmessages:OpenDataChannel',
],
resources: ['*'],
}));
}
}
/**
* The options to enabling AWS Cloud Map for an Amazon ECS service.
*/
export interface CloudMapOptions {
/**
* The name of the Cloud Map service to attach to the ECS service.
*
* @default CloudFormation-generated name
*/
readonly name?: string,
/**
* The service discovery namespace for the Cloud Map service to attach to the ECS service.
*
* @default - the defaultCloudMapNamespace associated to the cluster
*/
readonly cloudMapNamespace?: cloudmap.INamespace;
/**
* The DNS record type that you want AWS Cloud Map to create. The supported record types are A or SRV.
*
* @default - DnsRecordType.A if TaskDefinition.networkMode = AWS_VPC, otherwise DnsRecordType.SRV
*/
readonly dnsRecordType?: cloudmap.DnsRecordType.A | cloudmap.DnsRecordType.SRV,
/**
* The amount of time that you want DNS resolvers to cache the settings for this record.
*
* @default Duration.minutes(1)
*/
readonly dnsTtl?: Duration;
/**
* The number of 30-second intervals that you want Cloud Map to wait after receiving an UpdateInstanceCustomHealthStatus
* request before it changes the health status of a service instance.
*
* NOTE: This is used for HealthCheckCustomConfig
*/
readonly failureThreshold?: number;
/**
* The container to point to for a SRV record.
* @default - the task definition's default container
*/
readonly container?: ContainerDefinition;
/**
* The port to point to for a SRV record.
* @default - the default port of the task definition's default container
*/
readonly containerPort?: number;
}
/**
* The options for using a cloudmap service.
*/
export interface AssociateCloudMapServiceOptions {
/**
* The cloudmap service to register with.
*/
readonly service: cloudmap.IService;
/**
* The container to point to for a SRV record.
* @default - the task definition's default container
*/
readonly container?: ContainerDefinition;
/**
* The port to point to for a SRV record.
* @default - the default port of the task definition's default container
*/
readonly containerPort?: number;
}
/**
* Service Registry for ECS service
*/
interface ServiceRegistry {
/**
* Arn of the Cloud Map Service that will register a Cloud Map Instance for your ECS Service
*/
readonly arn: string;
/**
* The container name value, already specified in the task definition, to be used for your service discovery service.
* If the task definition that your service task specifies uses the bridge or host network mode,
* you must specify a containerName and containerPort combination from the task definition.
* If the task definition that your service task specifies uses the awsvpc network mode and a type SRV DNS record is
* used, you must specify either a containerName and containerPort combination or a port value, but not both.
*/
readonly containerName?: string;
/**
* The container port value, already specified in the task definition, to be used for your service discovery service.
* If the task definition that your service task specifies uses the bridge or host network mode,
* you must specify a containerName and containerPort combination from the task definition.
* If the task definition that your service task specifies uses the awsvpc network mode and a type SRV DNS record is
* used, you must specify either a containerName and containerPort combination or a port value, but not both.
*/
readonly containerPort?: number;
}
/**
* The launch type of an ECS service
*/
export enum LaunchType {
/**
* The service will be launched using the EC2 launch type
*/
EC2 = 'EC2',
/**
* The service will be launched using the FARGATE launch type
*/
FARGATE = 'FARGATE',
/**
* The service will be launched using the EXTERNAL launch type
*/
EXTERNAL = 'EXTERNAL'
}
/**
* The deployment controller type to use for the service.
*/
export enum DeploymentControllerType {
/**
* The rolling update (ECS) deployment type involves replacing the current
* running version of the container with the latest version.
*/
ECS = 'ECS',
/**
* The blue/green (CODE_DEPLOY) deployment type uses the blue/green deployment model powered by AWS CodeDeploy
*/
CODE_DEPLOY = 'CODE_DEPLOY',
/**
* The external (EXTERNAL) deployment type enables you to use any third-party deployment controller
*/
EXTERNAL = 'EXTERNAL'
}
/**
* Propagate tags from either service or task definition
*/
export enum PropagatedTagSource {
/**
* Propagate tags from service
*/
SERVICE = 'SERVICE',
/**
* Propagate tags from task definition
*/
TASK_DEFINITION = 'TASK_DEFINITION',
/**
* Do not propagate
*/
NONE = 'NONE'
}
/**
* Options for `determineContainerNameAndPort`
*/
interface DetermineContainerNameAndPortOptions {
dnsRecordType: cloudmap.DnsRecordType;
taskDefinition: TaskDefinition;
container?: ContainerDefinition;
containerPort?: number;
}
/**
* Determine the name of the container and port to target for the service registry.
*/
function determineContainerNameAndPort(options: DetermineContainerNameAndPortOptions) {
// If the record type is SRV, then provide the containerName and containerPort to target.
// We use the name of the default container and the default port of the default container
// unless the user specifies otherwise.
if (options.dnsRecordType === cloudmap.DnsRecordType.SRV) {
// Ensure the user-provided container is from the right task definition.
if (options.container && options.container.taskDefinition != options.taskDefinition) {
throw new Error('Cannot add discovery for a container from another task definition');
}
const container = options.container ?? options.taskDefinition.defaultContainer!;
// Ensure that any port given by the user is mapped.
if (options.containerPort && !container.portMappings.some(mapping => mapping.containerPort === options.containerPort)) {
throw new Error('Cannot add discovery for a container port that has not been mapped');
}
return {
containerName: container.containerName,
containerPort: options.containerPort ?? options.taskDefinition.defaultContainer!.containerPort,
};
}
return {};
} | the_stack |
import GPUHelper from '../common/GPUHelper';
import { BufferedTomDataR } from '../common/BufferedTomDataR';
import { FileParams, GPUTypedArray } from '../common/types';
import MutableTypedArray from '../common/MutableTypedArray';
import { getBinLength } from '../common/io';
import { log, nullValForType, positionToIndex3D } from '../common/utils';
import { Vector3 } from 'three';
import { BufferedTomDataRWOverwrite } from '../common/BufferedTomDataRWOverwrite';
import { orderNeighborsCC } from '../common/CalcMeshNormals';
export default function run(
gpuHelper: GPUHelper,
fileParams: FileParams,
params: Readonly<{
MAX_NUM_NEIGHBORS: number,
MESHING_NORMAL_ALIGNMENT_TOL: number,
MESHING_EDGE_NORMAL_ORTHOG_TOL: number,
MAX_EDGE_LENGTH: number,
MESHING_MIN_ANGLE: number,
MAX_SINGLE_LAYER_WIDTH: number,
MIN_MESH_COMPONENT_SIZE: number,
}>,
) {
console.time('\tmeshing');
// Constants.
const {
MAX_NUM_NEIGHBORS,
MESHING_NORMAL_ALIGNMENT_TOL,
MESHING_EDGE_NORMAL_ORTHOG_TOL,
MAX_EDGE_LENGTH,
MESHING_MIN_ANGLE,
MAX_SINGLE_LAYER_WIDTH,
MIN_MESH_COMPONENT_SIZE,
} = params;
const INDICES_WINDOW_SIZE = 1;
const NUM_POINTS = getBinLength(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allPointsList');
// Temp objects.
const tempArray1: number[] = [];
const tempArray2: number[] = [];
const tempArray3: number[] = [];
const tempVector1 = new Vector3();
const tempVector2 = new Vector3();
const tempVector3 = new Vector3();
// Load previously computed data.
const allNormalsList = MutableTypedArray.initFromFile(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allNormalsList');
const allPointsList = MutableTypedArray.initFromFile(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allPointsList');
const allWidthsMin = new BufferedTomDataR(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allWidthsMin');
const allWidthsMax = new BufferedTomDataR(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allWidthsMax');
// Count up the number of flagged points from width detection.
const allFlagsList = new MutableTypedArray(new Uint8Array(allPointsList.getLength()), false, 1);
let numFlagged = 0;
for (let i = 0; i < NUM_POINTS; i++) {
const position3D = allPointsList.getVector3(i, tempVector1);
if (!position3D) {
continue;
}
const index3D = positionToIndex3D(position3D, tempVector2, fileParams.DIMENSIONS);
if (!index3D) {
throw new Error('Out of bounds error.');
}
const widthMin = allWidthsMin.get(index3D.x, index3D.y, index3D.z);
if (widthMin === null) {
throw new Error('Bad widthMin.');
}
const widthMax = allWidthsMax.get(index3D.x, index3D.y, index3D.z);
if (widthMax === null) {
throw new Error('Bad widthMax.');
}
const width = widthMax - widthMin;
if (width > MAX_SINGLE_LAYER_WIDTH) {
numFlagged++;
allFlagsList.set(i, 1);
}
}
log(`\t${numFlagged} low quality points detected based on widths, ${allPointsList.getLength() - numFlagged} remaining.`);
// Find coplanar points.
gpuHelper.initProgram(
'./src/segmentation/gpu/findCoplanarPointsProgram.cl',
'findCoplanarPoints',
{
WINDOW_SIZE: {
value: INDICES_WINDOW_SIZE,
type: 'uint32',
},
NUM_NEIGHBORING_CELLS: {
value: (2 * INDICES_WINDOW_SIZE + 1) * (2 * INDICES_WINDOW_SIZE + 1) * (2 * INDICES_WINDOW_SIZE + 1) - 1,
type: 'uint32',
},
MAX_NUM_NEIGHBORS: {
value: MAX_NUM_NEIGHBORS,
type: 'uint32',
},
MAX_EDGE_LENGTH_SQ: {
value: MAX_EDGE_LENGTH * MAX_EDGE_LENGTH,
type: 'float32',
},
COS_MESHING_NORMAL_ALIGNMENT_TOL: {
value: Math.cos(MESHING_NORMAL_ALIGNMENT_TOL),
type: 'float32',
},
COS_MESHING_EDGE_NORMAL_ORTHOG_TOL: {
value: Math.cos(Math.PI/2 - MESHING_EDGE_NORMAL_ORTHOG_TOL),
type: 'float32',
},
});
// Set kernel buffers.
gpuHelper.createGPUBuffer('neighbors', null, 'int*', 'write', NUM_POINTS * MAX_NUM_NEIGHBORS);
gpuHelper.createGPUBuffer('points', allPointsList.getData() as Float32Array, 'float*', 'read', NUM_POINTS * allPointsList.numElementsPerIndex);
gpuHelper.createGPUBufferFromTom('indices', fileParams.OUTPUT_PATH, fileParams.FILENAME + '_allIndices', 'read');
gpuHelper.createGPUBuffer('normals', allNormalsList.getData() as Float32Array, 'float*', 'read', NUM_POINTS * allNormalsList.numElementsPerIndex);
gpuHelper.createGPUBuffer('flags', allFlagsList.getData() as Uint8Array, 'uchar*', 'read', NUM_POINTS * allFlagsList.numElementsPerIndex);
gpuHelper.createGPUBuffer('size', Int32Array.from(fileParams.DIMENSIONS.toArray()), 'int*', 'read');
// Set neighbors to null.
gpuHelper.nullBuffer('neighbors');
// Set kernel arguments.
gpuHelper.setBufferArgument('findCoplanarPoints', 0, 'neighbors');
gpuHelper.setBufferArgument('findCoplanarPoints', 1, 'points');
gpuHelper.setBufferArgument('findCoplanarPoints', 2, 'indices');
gpuHelper.setBufferArgument('findCoplanarPoints', 3, 'normals');
gpuHelper.setBufferArgument('findCoplanarPoints', 4, 'flags');
gpuHelper.setBufferArgument('findCoplanarPoints', 5, 'size');
// Run program.
gpuHelper.runProgram('findCoplanarPoints', NUM_POINTS);
// Copy data off GPU.
const allNeighbors = gpuHelper.mutableTypedArrayFromGPUBuffer('neighbors', 'int32', true, MAX_NUM_NEIGHBORS)
// Remove any neighboring points that are not reciprocal.
let numBadNeighbors = 0;
for (let i = 0; i < NUM_POINTS; i++) {
const pointNeighbors = allNeighbors.get(i, tempArray1);
if (!pointNeighbors) {
continue;
}
let needsUpdate = false;
for (let j = pointNeighbors.length - 1; j >= 0; j--) {
const neighborNeighbors = allNeighbors.get(pointNeighbors[j], tempArray2);
if (neighborNeighbors === null || neighborNeighbors.indexOf(i) < 0) {
pointNeighbors.splice(j, 1);
numBadNeighbors++;
needsUpdate = true;
}
}
if (needsUpdate) {
allNeighbors.set(i, pointNeighbors);
}
}
if (numBadNeighbors) {
log(`\t${numBadNeighbors} invalid neighbors pruned.`);
}
// Mesh with neighbors - this is not parallelized for now.
const COS_MESHING_MIN_ANGLE = Math.cos(MESHING_MIN_ANGLE);
const allMeshNeighbors = new MutableTypedArray(new Int32Array(allNeighbors.getLength() * allNeighbors.numElementsPerIndex), true, MAX_NUM_NEIGHBORS);
allMeshNeighbors.clear();
for (let i = 0; i < NUM_POINTS; i++) {
const pointNeighbors = allNeighbors.get(i, tempArray1);
if (!pointNeighbors) continue;
let pointMeshNeighbors = allMeshNeighbors.get(i, tempArray2) as number[];
if (!pointMeshNeighbors) {
pointMeshNeighbors = [];
}
const pointPosition = allPointsList.getVector3(i, tempVector1);
if (!pointPosition) {
return;
}
pointNeighbors.forEach(neighborIndex => {
if (neighborIndex < i) {
// This neighbor has already been checked.
return;
}
// Check that adding this edge doesn't violate minMeshAngle for either point.
const neighborPosition = allPointsList.getVector3(neighborIndex, tempVector2);
if (!neighborPosition) {
return;
}
let edgeVector1 = (tempVector3.copy(neighborPosition).sub(pointPosition)).normalize();
// Check against all of pointMeshNeighbors.
for (let j = 0; j < pointMeshNeighbors.length; j++) {
const neighbor2Position = allPointsList.getVector3(pointMeshNeighbors[j], tempVector2);
if (!neighbor2Position) {
return;
}
const edgeVector2 = neighbor2Position.sub(pointPosition).normalize();
if (edgeVector1.dot(edgeVector2) > COS_MESHING_MIN_ANGLE) {
return;
}
}
let neighborMeshNeighbors = allMeshNeighbors.get(neighborIndex, tempArray3);
if (neighborMeshNeighbors === null) {
neighborMeshNeighbors = [];
}
edgeVector1 = edgeVector1.multiplyScalar(-1);
// Check against all of neighborMeshNeighbors.
for (let j = 0; j < neighborMeshNeighbors.length; j++) {
const neighbor2Position = allPointsList.getVector3(neighborMeshNeighbors[j], tempVector2);
if (!neighbor2Position) {
return;
}
const edgeVector2 = neighbor2Position.sub(neighborPosition).normalize();
if (edgeVector1.dot(edgeVector2) > COS_MESHING_MIN_ANGLE) {
return;
}
}
// Add new edge.
neighborMeshNeighbors.push(i);
pointMeshNeighbors.push(neighborIndex);
allMeshNeighbors.set(neighborIndex, neighborMeshNeighbors);
});
allMeshNeighbors.set(i, pointMeshNeighbors);
}
allNeighbors.destroy();
// Prune away any points with less than 3 neighbors.
let underConnectedPoints = 0;
for (let i = 0; i < NUM_POINTS; i++) {
// Ignore flagged points.
const flag = allFlagsList.get(i);
if (flag) {
continue;
}
// All points must have at least 3 neighbors.
const neighbors = allMeshNeighbors.get(i, tempArray1);
if (!neighbors || neighbors.length < 3) {
allFlagsList.set(i, 1);
if (neighbors) {
// Remove point i from neighbors.
for (let j = 0; j < neighbors.length; j++) {
const neighbor = neighbors[j];
const neighborNeighbors = allMeshNeighbors.get(neighbor, tempArray2);
neighborNeighbors?.splice(neighborNeighbors.indexOf(i), 1);
allMeshNeighbors.set(neighbor, neighborNeighbors);
}
}
allMeshNeighbors.set(i, null);
underConnectedPoints++;
numFlagged++;
}
}
for (let i = 0; i < NUM_POINTS; i++) {
// Ignore flagged points.
const flag = allFlagsList.get(i);
if (flag) {
continue;
}
const neighbors = allMeshNeighbors.get(i, tempArray1);
if (!neighbors) {
// It's possible that we could create some stray points in the last step, prune these if needed.
allFlagsList.set(i, 1);
underConnectedPoints++;
numFlagged++;
}
}
log(`\t${underConnectedPoints} low quality points detected based mesh connectivity, ${allPointsList.getLength() - numFlagged} remaining.`);
// Calc connected components.
const allMeshNumbers = new MutableTypedArray(new Int32Array(NUM_POINTS), true);
allMeshNumbers.clear();
for (let i = 0; i < NUM_POINTS; i++) {
// Give every point a unique number to start.
if (!allFlagsList.get(i)) {
allMeshNumbers.set(i, i);
}
}
// Iteratively propagate mesh numbers across mesh.
// Init gpu programs.
gpuHelper.initProgram(
'./src/segmentation/gpu/connectedComponentsProgram.cl',
'iterConnections',
{
MAX_NUM_NEIGHBORS: {
value: MAX_NUM_NEIGHBORS,
type: 'uint32',
},
});
gpuHelper.initProgram(
'./src/segmentation/gpu/connectedComponentsProgram.cl',
'findNeighborMeshNums',
{
MAX_NUM_NEIGHBORS: {
value: MAX_NUM_NEIGHBORS,
type: 'uint32',
},
});
gpuHelper.createGPUBuffer('meshNeighbors', allMeshNeighbors.getData() as Int32Array, 'int*', 'read', NUM_POINTS * allMeshNeighbors.numElementsPerIndex);
gpuHelper.createGPUBuffer('meshNumbers', allMeshNumbers.getData() as Int32Array, 'int*', 'readwrite', NUM_POINTS);
// Init adjacent mesh lookup as all nulls.
gpuHelper.createGPUBuffer('adjacentMeshNumbers', null, 'int*', 'readwrite', NUM_POINTS);
gpuHelper.nullBuffer('adjacentMeshNumbers');
// Set arguments.
gpuHelper.setBufferArgument('iterConnections', 0, 'meshNumbers');
gpuHelper.setBufferArgument('iterConnections', 1, 'meshNeighbors');
gpuHelper.setBufferArgument('findNeighborMeshNums', 0, 'adjacentMeshNumbers');
gpuHelper.setBufferArgument('findNeighborMeshNums', 1, 'meshNumbers');
gpuHelper.setBufferArgument('findNeighborMeshNums', 2, 'meshNeighbors');
const adjacentMeshNumbers = allMeshNumbers.clone();
adjacentMeshNumbers.clear();
let finished = false;
let numIter = 0;
do {
for (let i = 0; i < 100; i++) {
gpuHelper.runProgram('iterConnections', NUM_POINTS);
}
numIter += 100;
// Set adjacentMeshNumbers array to null.
gpuHelper.nullBuffer('adjacentMeshNumbers');
// Find neighboring regions.
gpuHelper.runProgram('findNeighborMeshNums', NUM_POINTS);
gpuHelper.copyDataFromGPUBuffer('adjacentMeshNumbers', adjacentMeshNumbers.getData() as Int32Array, 0, NUM_POINTS);
finished = true;
for (let i = 0; i < NUM_POINTS; i++) {
if (adjacentMeshNumbers.get(i) !== null) {
finished = false;
break;
}
}
} while (!finished);
gpuHelper.copyDataFromGPUBuffer('meshNumbers', allMeshNumbers.getData() as Int32Array, 0, NUM_POINTS);
// Find all connected components.
const components: {[key: string]: number} = {};
for (let i = 0; i < NUM_POINTS; i++) {
const num = allMeshNumbers.get(i);
if (num !== null) {
if (!components[num]) {
components[num] = 1;
} else {
components[num]++;
}
}
}
log(`\t${Object.keys(components).length} components found in ${numIter} iterations.`);
// Remove any small components.
let smallComponentPts = 0;
let smallComponents = 0;
for (let i = 0; i < NUM_POINTS; i++) {
const meshNum = allMeshNumbers.get(i);
if (meshNum === null) {
continue;
}
if (components[meshNum] >= MIN_MESH_COMPONENT_SIZE) {
continue;
}
// Flag this point for removal.
allFlagsList.set(i, 1);
allMeshNumbers.set(i, null);
allMeshNeighbors.set(i, null);
smallComponentPts++;
numFlagged++;
}
Object.keys(components).forEach(key => {
if (components[key] < MIN_MESH_COMPONENT_SIZE) {
delete components[key];
smallComponents++;
}
});
log(`\t${smallComponentPts} points on ${smallComponents} small mesh components removed, ${allPointsList.getLength() - numFlagged} remaining.`);
log(`\t${Object.keys(components).length} components remaining after removing small components.`);
// Reindex all mesh numbers to remove any missing numbers.
// IE the numbers should read: 0, 1, 2, 3...
const meshNumberReindexLookup = new MutableTypedArray(new Float32Array(NUM_POINTS), true);
meshNumberReindexLookup.clear();
// Mark all valid mesh numbers with 1.
for (let i = 0; i < NUM_POINTS; i++) {
const meshNum = allMeshNumbers.get(i);
if (meshNum === null) {
continue;
}
meshNumberReindexLookup.set(meshNum, 1);
}
// Generate a new index for each mesh number.
let newIndex = 0;
for (let i = 0; i < NUM_POINTS; i++) {
if (meshNumberReindexLookup.get(i) === null) {
continue;
}
meshNumberReindexLookup.set(i, newIndex);
newIndex++;
}
// Update mesh numbers.
for (let i = 0; i < NUM_POINTS; i++) {
const meshNum = allMeshNumbers.get(i);
if (meshNum === null) {
continue;
}
const newMeshNum = meshNumberReindexLookup.get(meshNum);
allMeshNumbers.set(i, newMeshNum);
}
// Print largest component sizes.
let numLargeComponents = 10;
if (Object.keys(components).length < 10) {
numLargeComponents = Object.keys(components).length;
}
const largestComponents: {[key: string]: number} = {};
let smallestOfLargestComponentsSize = Infinity;
let smallestOfLargestComponentsKey: string | null = null;
Object.keys(components).forEach(key => {
if (Object.values(largestComponents).length < numLargeComponents) {
largestComponents[key] = components[key];
if (components[key] < smallestOfLargestComponentsSize) {
smallestOfLargestComponentsSize = components[key];
smallestOfLargestComponentsKey = key;
}
return;
}
if (components[key] > smallestOfLargestComponentsSize) {
delete largestComponents[smallestOfLargestComponentsKey!];
largestComponents[key] = components[key];
// Calc next smallest.
smallestOfLargestComponentsSize = Infinity;
Object.keys(largestComponents).forEach(largeComponentKey => {
if (components[largeComponentKey] < smallestOfLargestComponentsSize) {
smallestOfLargestComponentsSize = components[largeComponentKey];
smallestOfLargestComponentsKey = largeComponentKey;
}
});
}
});
// Sort largest components.
const sortedLargestComponents = Object.keys(largestComponents).map(key => [meshNumberReindexLookup.get(parseInt(key)), largestComponents[key]]);
sortedLargestComponents.sort((a, b) => {
return (b[1] as number) - (a[1] as number);
});
sortedLargestComponents.forEach(comp => {
log(`\t Mesh ${comp[0]}:\t\t${comp[1]} vertices`);
});
// Split all points into points and flagged points.
const pointsList = new MutableTypedArray(new Float32Array(), false, 3);
const meshNeighborsList = new MutableTypedArray(new Int32Array(), true, MAX_NUM_NEIGHBORS);
const meshNumbersList = new MutableTypedArray(new Int32Array(), false);
const normalsList = new MutableTypedArray(new Float32Array(), false, 3);
const widthsMinList = new MutableTypedArray(new Float32Array(), false);
const widthsMaxList = new MutableTypedArray(new Float32Array(), false);
const indices = new BufferedTomDataRWOverwrite(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_indices', 'int32', fileParams.DIMENSIONS, 1, true, 0);
// Mapping from allPointsList to pointsList indices.
const pointsIndexMapping = new MutableTypedArray(new Int32Array(), true);
const pointsList_FLAGGED = new MutableTypedArray(new Float32Array(), false, 3);
const normalsList_FLAGGED = new MutableTypedArray(new Float32Array(), false, 3);
const widthsMinList_FLAGGED = new MutableTypedArray(new Float32Array(), false);
const widthsMaxList_FLAGGED = new MutableTypedArray(new Float32Array(), false);
const indices_FLAGGED = new BufferedTomDataRWOverwrite(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_indices_FLAGGED', 'int32', fileParams.DIMENSIONS, 1, true, 0);
for (let i = 0; i < NUM_POINTS; i++) {
pointsIndexMapping.push(null);
const position3D = allPointsList.getVector3(i, tempVector1);
if (!position3D) {
continue;
}
const index3D = positionToIndex3D(position3D, tempVector2, fileParams.DIMENSIONS);
if (!index3D) {
throw new Error('Out of bounds error.');
}
const widthMin = allWidthsMin.get(index3D.x, index3D.y, index3D.z);
if (widthMin === null) {
throw new Error('Bad widthMin.');
}
const widthMax = allWidthsMax.get(index3D.x, index3D.y, index3D.z);
if (widthMax === null) {
throw new Error('Bad widthMax.');
}
const flag = allFlagsList.get(i);
if (flag) {
widthsMinList_FLAGGED.push(widthMin);
widthsMaxList_FLAGGED.push(widthMax);
indices_FLAGGED.set(index3D.x, index3D.y, index3D.z, pointsList_FLAGGED.getLength());
pointsList_FLAGGED.pushVector3(allPointsList.getVector3(i, tempVector3));
normalsList_FLAGGED.pushVector3(allNormalsList.getVector3(i, tempVector3));
} else {
pointsIndexMapping.set(i, pointsList.getLength());
meshNeighborsList.push(allMeshNeighbors.get(i, tempArray1));
meshNumbersList.push(allMeshNumbers.get(i));
widthsMinList.push(widthMin);
widthsMaxList.push(widthMax);
indices.set(index3D.x, index3D.y, index3D.z, pointsList.getLength());
pointsList.pushVector3(allPointsList.getVector3(i, tempVector3));
normalsList.pushVector3(allNormalsList.getVector3(i, tempVector3));
}
}
// Reindex all neighbors.
for (let i = 0, length = meshNeighborsList.getLength(); i < length; i++) {
const neighbors = meshNeighborsList.get(i, tempArray1);
if (neighbors === null) {
continue;
}
for (let j = 0; j < neighbors.length; j++) {
const index = pointsIndexMapping.get(neighbors[j]);
if (index === null) {
throw new Error('Bad neighbor index found.');
}
neighbors[j] = index;
}
meshNeighborsList.set(i, neighbors);
}
log(`\tA total of ${pointsList_FLAGGED.getLength()} low quality points removed, ${pointsList.getLength()} remaining.`);
// Finally reorder all neighbors so that they are in CC order around point relative to normal.
gpuHelper.createGpuBufferFromMutableTypedArray('points', pointsList, 'read', pointsList.getLength(), true);
gpuHelper.createGpuBufferFromMutableTypedArray('normals', normalsList, 'read', pointsList.getLength(), true);
gpuHelper.createGpuBufferFromMutableTypedArray('meshNeighbors', meshNeighborsList, 'readwrite', meshNeighborsList.getLength(), true);
orderNeighborsCC(gpuHelper, {
pointsBufferName: 'points',
neighborsBufferName: 'meshNeighbors',
normalsBufferName: 'normals',
}, pointsList.getLength(), MAX_NUM_NEIGHBORS);
gpuHelper.copyDataToMutableTypedArray('meshNeighbors', meshNeighborsList);
// Save files.
pointsList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_points3DList');
normalsList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_normalsList');
widthsMinList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_widthsMinList');
widthsMaxList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_widthsMaxList');
pointsList_FLAGGED.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_points3DList_FLAGGED');
normalsList_FLAGGED.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_normalsList_FLAGGED');
widthsMinList_FLAGGED.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_widthsMinList_FLAGGED');
widthsMaxList_FLAGGED.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_widthsMaxList_FLAGGED');
meshNeighborsList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_meshNeighborsList');
meshNumbersList.saveAsBin(fileParams.OUTPUT_PATH, fileParams.FILENAME + '_meshNumbersList');
// Close all files.
allWidthsMin.close();
allWidthsMax.close();
allPointsList.destroy();
allNormalsList.destroy();
allFlagsList.destroy();
allMeshNeighbors.destroy();
allMeshNumbers.destroy();
indices.close();
pointsList.destroy();
normalsList.destroy();
widthsMinList.destroy();
widthsMaxList.destroy();
indices_FLAGGED.close();
pointsList_FLAGGED.destroy();
normalsList_FLAGGED.destroy();
widthsMinList_FLAGGED.destroy();
widthsMaxList_FLAGGED.destroy();
meshNeighborsList.destroy();
meshNumbersList.destroy();
gpuHelper.clear();
console.timeEnd('\tmeshing');
}; | the_stack |
* @module WebGL
*/
import { assert, dispose } from "@itwin/core-bentley";
import { Point3d, Range3d, Transform } from "@itwin/core-geometry";
import { InstancedGraphicParams, PatternGraphicParams } from "../InstancedGraphicParams";
import { RenderMemory } from "../RenderMemory";
import { AttributeMap } from "./AttributeMap";
import { CachedGeometry, LUTGeometry } from "./CachedGeometry";
import { ShaderProgramParams } from "./DrawCommand";
import { GL } from "./GL";
import { BufferHandle, BufferParameters, BuffersContainer } from "./AttributeBuffers";
import { Target } from "./Target";
import { TechniqueId } from "./TechniqueId";
import { Matrix4 } from "./Matrix";
/** @internal */
export function isInstancedGraphicParams(params: any): params is InstancedGraphicParams {
return typeof params === "object" && typeof params.count === "number" && params.transforms instanceof Float32Array && params.transformCenter instanceof Point3d;
}
class InstanceData {
public readonly numInstances: number;
public readonly range: Range3d;
// A transform including only rtcCenter.
private readonly _rtcOnlyTransform: Transform;
// A transform from _rtcCenter including model matrix
private readonly _rtcModelTransform: Transform;
// The model matrix from which _rtcModelTransform was previously computed. If it changes, _rtcModelTransform must be recomputed.
private readonly _modelMatrix = Transform.createIdentity();
protected constructor(numInstances: number, rtcCenter: Point3d, range: Range3d) {
this.numInstances = numInstances;
this.range = range;
this._rtcOnlyTransform = Transform.createTranslation(rtcCenter);
this._rtcModelTransform = this._rtcOnlyTransform.clone();
}
public getRtcModelTransform(modelMatrix: Transform): Transform {
if (!this._modelMatrix.isAlmostEqual(modelMatrix)) {
modelMatrix.clone(this._modelMatrix);
modelMatrix.multiplyTransformTransform(this._rtcOnlyTransform, this._rtcModelTransform);
}
return this._rtcModelTransform;
}
public getRtcOnlyTransform(): Transform {
return this._rtcOnlyTransform;
}
private static readonly _noFeatureId = new Float32Array([0, 0, 0]);
public get patternFeatureId(): Float32Array {
return InstanceData._noFeatureId;
}
}
/** @internal */
export interface PatternTransforms {
readonly orgTransform: Matrix4;
readonly localToModel: Matrix4;
readonly symbolToLocal: Matrix4;
readonly origin: Float32Array;
}
/** @internal */
export class InstanceBuffers extends InstanceData {
private static readonly _patternParams = new Float32Array([0, 0, 0, 0]);
public readonly transforms: BufferHandle;
public readonly featureIds?: BufferHandle;
public readonly hasFeatures: boolean;
public readonly symbology?: BufferHandle;
public readonly patternParams = InstanceBuffers._patternParams;
public readonly patternTransforms = undefined;
public readonly viewIndependentOrigin = undefined;
private constructor(count: number, transforms: BufferHandle, rtcCenter: Point3d, range: Range3d, symbology?: BufferHandle, featureIds?: BufferHandle) {
super(count, rtcCenter, range);
this.transforms = transforms;
this.featureIds = featureIds;
this.hasFeatures = undefined !== featureIds;
this.symbology = symbology;
}
public static createTransformBufferParameters(techniqueId: TechniqueId): BufferParameters[] {
const params: BufferParameters[] = [];
const numRows = 3;
let row = 0;
while (row < numRows) {
// 3 rows per instance; 4 floats per row; 4 bytes per float.
const floatsPerRow = 4;
const bytesPerVertex = floatsPerRow * 4;
const offset = row * bytesPerVertex;
const stride = 3 * bytesPerVertex;
const name = `a_instanceMatrixRow${row}`;
const details = AttributeMap.findAttribute(name, techniqueId, true);
assert(details !== undefined);
const bParams: BufferParameters = {
glAttribLoc: details.location,
glSize: floatsPerRow,
glType: GL.DataType.Float,
glNormalized: false,
glStride: stride,
glOffset: offset,
glInstanced: true,
};
params.push(bParams);
row++;
}
return params;
}
public static create(params: InstancedGraphicParams, range: Range3d): InstanceBuffers | undefined {
const { count, featureIds, symbologyOverrides, transforms } = params;
assert(count > 0 && Math.floor(count) === count);
assert(count === transforms.length / 12);
assert(undefined === featureIds || count === featureIds.length / 3);
assert(undefined === symbologyOverrides || count * 8 === symbologyOverrides.length);
let idBuf: BufferHandle | undefined;
if (undefined !== featureIds && undefined === (idBuf = BufferHandle.createArrayBuffer(featureIds)))
return undefined;
let symBuf: BufferHandle | undefined;
if (undefined !== symbologyOverrides && undefined === (symBuf = BufferHandle.createArrayBuffer(symbologyOverrides)))
return undefined;
const tfBuf = BufferHandle.createArrayBuffer(transforms);
return undefined !== tfBuf ? new InstanceBuffers(count, tfBuf, params.transformCenter, range, symBuf, idBuf) : undefined;
}
public get isDisposed(): boolean {
return this.transforms.isDisposed
&& (undefined === this.featureIds || this.featureIds.isDisposed)
&& (undefined === this.symbology || this.symbology.isDisposed);
}
public dispose() {
dispose(this.transforms);
dispose(this.featureIds);
dispose(this.symbology);
}
public collectStatistics(stats: RenderMemory.Statistics): void {
const featureBytes = undefined !== this.featureIds ? this.featureIds.bytesUsed : 0;
const symBytes = undefined !== this.symbology ? this.symbology.bytesUsed : 0;
const bytesUsed = this.transforms.bytesUsed + symBytes + featureBytes;
stats.addInstances(bytesUsed);
}
private static extendTransformedRange(tfs: Float32Array, i: number, range: Range3d, x: number, y: number, z: number) {
range.extendXYZ(tfs[i + 3] + tfs[i + 0] * x + tfs[i + 1] * y + tfs[i + 2] * z,
tfs[i + 7] + tfs[i + 4] * x + tfs[i + 5] * y + tfs[i + 6] * z,
tfs[i + 11] + tfs[i + 8] * x + tfs[i + 9] * y + tfs[i + 10] * z);
}
public static computeRange(reprRange: Range3d, tfs: Float32Array, rtcCenter: Point3d, out?: Range3d): Range3d {
const range = out ?? new Range3d();
const numFloatsPerTransform = 3 * 4;
assert(0 === tfs.length % (3 * 4));
for (let i = 0; i < tfs.length; i += numFloatsPerTransform) {
this.extendTransformedRange(tfs, i, range, reprRange.low.x, reprRange.low.y, reprRange.low.z);
this.extendTransformedRange(tfs, i, range, reprRange.low.x, reprRange.low.y, reprRange.high.z);
this.extendTransformedRange(tfs, i, range, reprRange.low.x, reprRange.high.y, reprRange.low.z);
this.extendTransformedRange(tfs, i, range, reprRange.low.x, reprRange.high.y, reprRange.high.z);
this.extendTransformedRange(tfs, i, range, reprRange.high.x, reprRange.low.y, reprRange.low.z);
this.extendTransformedRange(tfs, i, range, reprRange.high.x, reprRange.low.y, reprRange.high.z);
this.extendTransformedRange(tfs, i, range, reprRange.high.x, reprRange.high.y, reprRange.low.z);
this.extendTransformedRange(tfs, i, range, reprRange.high.x, reprRange.high.y, reprRange.high.z);
}
range.low.addInPlace(rtcCenter);
range.high.addInPlace(rtcCenter);
return range.clone(out);
}
}
/** @internal */
export class PatternBuffers extends InstanceData {
private readonly _featureId?: Float32Array;
private constructor(
count: number,
rtcCenter: Point3d,
range: Range3d,
public readonly patternParams: Float32Array, // [ isAreaPattern, spacingX, spacingY, scale ]
public readonly origin: Float32Array, // [ x, y ]
public readonly orgTransform: Matrix4,
public readonly localToModel: Matrix4,
public readonly symbolToLocal: Matrix4,
public readonly offsets: BufferHandle,
featureId: number | undefined,
public readonly viewIndependentOrigin: Point3d | undefined
) {
super(count, rtcCenter, range);
this.patternTransforms = this;
if (undefined !== featureId) {
this._featureId = new Float32Array([
(featureId & 0x0000ff) >>> 0,
(featureId & 0x00ff00) >>> 8,
(featureId & 0xff0000) >>> 16,
]);
}
}
public static create(params: PatternGraphicParams): PatternBuffers | undefined {
const count = params.xyOffsets.byteLength / 2;
assert(Math.floor(count) === count);
const offsets = BufferHandle.createArrayBuffer(params.xyOffsets);
if (!offsets)
return undefined;
return new PatternBuffers(
count,
new Point3d(),
params.range,
new Float32Array([1, params.spacing.x, params.spacing.y, params.scale]),
new Float32Array([params.origin.x, params.origin.y]),
Matrix4.fromTransform(params.orgTransform),
Matrix4.fromTransform(params.patternToModel),
Matrix4.fromTransform(Transform.createTranslation(params.symbolTranslation)),
offsets,
params.featureId,
params.viewIndependentOrigin,
);
}
public readonly patternTransforms: PatternTransforms;
public get hasFeatures(): boolean {
return undefined !== this._featureId;
}
public override get patternFeatureId(): Float32Array {
return this._featureId ?? super.patternFeatureId;
}
public get isDisposed(): boolean {
return this.offsets.isDisposed;
}
public dispose(): void {
dispose(this.offsets);
}
public collectStatistics(stats: RenderMemory.Statistics): void {
stats.addInstances(this.offsets.bytesUsed);
}
}
/** @internal */
export class InstancedGeometry extends CachedGeometry {
private readonly _buffersContainer: BuffersContainer;
private readonly _buffers: InstanceBuffers | PatternBuffers;
private readonly _repr: LUTGeometry;
private readonly _ownsBuffers: boolean;
public getRtcModelTransform(modelMatrix: Transform) { return this._buffers.getRtcModelTransform(modelMatrix); }
public getRtcOnlyTransform() { return this._buffers.getRtcOnlyTransform(); }
public override get viewIndependentOrigin(): Point3d | undefined { return this._buffers.viewIndependentOrigin; }
public override get asInstanced() { return this; }
public override get asLUT() { return this._repr.asLUT; }
public override get asMesh() { return this._repr.asMesh; }
public override get asSurface() { return this._repr.asSurface; }
public override get asEdge() { return this._repr.asEdge; }
public override get asSilhouette() { return this._repr.asSilhouette; }
public override get asIndexedEdge() { return this._repr.asIndexedEdge; }
public get renderOrder() { return this._repr.renderOrder; }
public override get isLitSurface() { return this._repr.isLitSurface; }
public override get hasBakedLighting() { return this._repr.hasBakedLighting; }
public override get hasAnimation() { return this._repr.hasAnimation; }
public get qOrigin() { return this._repr.qOrigin; }
public get qScale() { return this._repr.qScale; }
public override get materialInfo() { return this._repr.materialInfo; }
public override get polylineBuffers() { return this._repr.polylineBuffers; }
public override get isEdge() { return this._repr.isEdge; }
public override get hasFeatures() { return this._buffers.hasFeatures; }
public get techniqueId(): TechniqueId { return this._repr.techniqueId; }
public override get supportsThematicDisplay() { return this._repr.supportsThematicDisplay; }
public override getPass(target: Target) { return this._repr.getPass(target); }
public override wantWoWReversal(params: ShaderProgramParams) { return this._repr.wantWoWReversal(params); }
public override getLineCode(params: ShaderProgramParams) { return this._repr.getLineCode(params); }
public override getLineWeight(params: ShaderProgramParams) { return this._repr.getLineWeight(params); }
public override wantMonochrome(target: Target) { return this._repr.wantMonochrome(target); }
public override wantMixMonochromeColor(target: Target): boolean { return this._repr.wantMixMonochromeColor(target); }
public static create(repr: LUTGeometry, ownsBuffers: boolean, buffers: InstanceBuffers): InstancedGeometry {
const techId = repr.techniqueId;
const container = BuffersContainer.create();
container.appendLinkages(repr.lutBuffers.linkages);
container.addBuffer(buffers.transforms, InstanceBuffers.createTransformBufferParameters(repr.techniqueId));
if (buffers.symbology) {
const attrInstanceOverrides = AttributeMap.findAttribute("a_instanceOverrides", techId, true);
const attrInstanceRgba = AttributeMap.findAttribute("a_instanceRgba", techId, true);
assert(attrInstanceOverrides !== undefined);
assert(attrInstanceRgba !== undefined);
container.addBuffer(buffers.symbology, [
BufferParameters.create(attrInstanceOverrides.location, 4, GL.DataType.UnsignedByte, false, 8, 0, true),
BufferParameters.create(attrInstanceRgba.location, 4, GL.DataType.UnsignedByte, false, 8, 4, true),
]);
}
if (buffers.featureIds) {
const attrFeatureId = AttributeMap.findAttribute("a_featureId", techId, true);
assert(attrFeatureId !== undefined);
container.addBuffer(buffers.featureIds, [BufferParameters.create(attrFeatureId.location, 3, GL.DataType.UnsignedByte, false, 0, 0, true)]);
}
return new this(repr, ownsBuffers, buffers, container);
}
public static createPattern(repr: LUTGeometry, ownsBuffers: boolean, buffers: PatternBuffers): InstancedGeometry {
const techId = repr.techniqueId;
const container = BuffersContainer.create();
container.appendLinkages(repr.lutBuffers.linkages);
const attrX = AttributeMap.findAttribute("a_patternX", techId, true);
const attrY = AttributeMap.findAttribute("a_patternY", techId, true);
assert(undefined !== attrX && undefined !== attrY);
container.addBuffer(buffers.offsets, [
BufferParameters.create(attrX.location, 1, GL.DataType.Float, false, 8, 0, true),
BufferParameters.create(attrY.location, 1, GL.DataType.Float, false, 8, 4, true),
]);
return new this(repr, ownsBuffers, buffers, container);
}
private constructor(repr: LUTGeometry, ownsBuffers: boolean, buffers: InstanceBuffers | PatternBuffers, container: BuffersContainer) {
super();
this._repr = repr;
this._ownsBuffers = ownsBuffers;
this._buffers = buffers;
this._buffersContainer = container;
}
public get isDisposed(): boolean {
if (!this._repr.isDisposed)
return false;
return !this._ownsBuffers || this._buffers.isDisposed;
}
public dispose() {
this._repr.dispose();
if (this._ownsBuffers)
dispose(this._buffers);
}
protected _wantWoWReversal(_target: Target) {
assert(false, "Should never be called");
return false;
}
public draw() {
this._repr.drawInstanced(this._buffers.numInstances, this._buffersContainer);
}
public override computeRange(output?: Range3d): Range3d {
return this._buffers.range.clone(output);
}
public collectStatistics(stats: RenderMemory.Statistics) {
this._repr.collectStatistics(stats);
if (this._ownsBuffers)
this._buffers.collectStatistics(stats);
}
public get patternParams(): Float32Array { return this._buffers.patternParams; }
public get patternTransforms(): PatternTransforms | undefined { return this._buffers.patternTransforms; }
public get patternFeatureId(): Float32Array { return this._buffers.patternFeatureId; }
} | the_stack |
import { resolve, dirname, relative } from 'path';
import resolveDependency from '../resolve-dependency';
import { getPackageName } from './get-package-base';
import { readFileSync } from 'fs';
import { Job } from '../node-file-trace';
import { Ast } from './types';
type Node = Ast['body'][0]
const specialCases: Record<string, (o: SpecialCaseOpts) => void> = {
'@generated/photon' ({ id, emitAssetDirectory }) {
if (id.endsWith('@generated/photon/index.js')) {
emitAssetDirectory(resolve(dirname(id), 'runtime/'));
}
},
'argon2' ({ id, emitAssetDirectory }) {
if (id.endsWith('argon2/argon2.js')) {
emitAssetDirectory(resolve(dirname(id), 'build', 'Release'));
emitAssetDirectory(resolve(dirname(id), 'prebuilds'));
emitAssetDirectory(resolve(dirname(id), 'lib', 'binding'));
}
},
'bull' ({ id, emitAssetDirectory }) {
if (id.endsWith('bull/lib/commands/index.js')) {
emitAssetDirectory(resolve(dirname(id)));
}
},
'camaro' ({ id, emitAsset }) {
if (id.endsWith('camaro/dist/camaro.js')) {
emitAsset(resolve(dirname(id), 'camaro.wasm'));
}
},
'google-gax' ({ id, ast, emitAssetDirectory }) {
if (id.endsWith('google-gax/build/src/grpc.js')) {
// const googleProtoFilesDir = path.normalize(google_proto_files_1.getProtoPath('..'));
// ->
// const googleProtoFilesDir = resolve(__dirname, '../../../google-proto-files');
for (const statement of ast.body) {
if (statement.type === 'VariableDeclaration' &&
statement.declarations[0].id.type === 'Identifier' &&
statement.declarations[0].id.name === 'googleProtoFilesDir') {
emitAssetDirectory(resolve(dirname(id), '../../../google-proto-files'));
}
}
}
},
'oracledb' ({ id, ast, emitAsset }) {
if (id.endsWith('oracledb/lib/oracledb.js')) {
for (const statement of ast.body) {
if (statement.type === 'ForStatement' &&
'body' in statement.body &&
statement.body.body &&
Array.isArray(statement.body.body) &&
statement.body.body[0] &&
statement.body.body[0].type === 'TryStatement' &&
statement.body.body[0].block.body[0] &&
statement.body.body[0].block.body[0].type === 'ExpressionStatement' &&
statement.body.body[0].block.body[0].expression.type === 'AssignmentExpression' &&
statement.body.body[0].block.body[0].expression.operator === '=' &&
statement.body.body[0].block.body[0].expression.left.type === 'Identifier' &&
statement.body.body[0].block.body[0].expression.left.name === 'oracledbCLib' &&
statement.body.body[0].block.body[0].expression.right.type === 'CallExpression' &&
statement.body.body[0].block.body[0].expression.right.callee.type === 'Identifier' &&
statement.body.body[0].block.body[0].expression.right.callee.name === 'require' &&
statement.body.body[0].block.body[0].expression.right.arguments.length === 1 &&
statement.body.body[0].block.body[0].expression.right.arguments[0].type === 'MemberExpression' &&
statement.body.body[0].block.body[0].expression.right.arguments[0].computed === true &&
statement.body.body[0].block.body[0].expression.right.arguments[0].object.type === 'Identifier' &&
statement.body.body[0].block.body[0].expression.right.arguments[0].object.name === 'binaryLocations' &&
statement.body.body[0].block.body[0].expression.right.arguments[0].property.type === 'Identifier' &&
statement.body.body[0].block.body[0].expression.right.arguments[0].property.name === 'i') {
statement.body.body[0].block.body[0].expression.right.arguments = [{ type: 'Literal', value: '_' }];
const version = (global as any)._unit ? '3.0.0' : JSON.parse(readFileSync(id.slice(0, -15) + 'package.json', 'utf8')).version;
const useVersion = Number(version.slice(0, version.indexOf('.'))) >= 4;
const binaryName = 'oracledb-' + (useVersion ? version : 'abi' + process.versions.modules) + '-' + process.platform + '-' + process.arch + '.node';
emitAsset(resolve(id, '../../build/Release/' + binaryName));
}
}
}
},
'phantomjs-prebuilt' ({ id, emitAssetDirectory }) {
if (id.endsWith('phantomjs-prebuilt/lib/phantomjs.js')) {
emitAssetDirectory(resolve(dirname(id), '..', 'bin'));
}
},
'remark-prism' ({ id, emitAssetDirectory }) {
const file = 'remark-prism/src/highlight.js';
if (id.endsWith(file)) {
try {
const node_modules = id.slice(0, -file.length);
emitAssetDirectory(resolve(node_modules, 'prismjs', 'components'));
} catch (e) {
// fail silently
}
}
},
'semver' ({ id, emitAsset }) {
if (id.endsWith('semver/index.js')) {
// See https://github.com/npm/node-semver/blob/master/CHANGELOG.md#710
emitAsset(resolve(id.replace('index.js', 'preload.js')));
}
},
'socket.io': async function ({ id, ast, job }) {
if (id.endsWith('socket.io/lib/index.js')) {
async function replaceResolvePathStatement (statement: Node) {
if (statement.type === 'ExpressionStatement' &&
statement.expression.type === 'AssignmentExpression' &&
statement.expression.operator === '=' &&
statement.expression.right.type === 'CallExpression' &&
statement.expression.right.callee.type === 'Identifier' &&
statement.expression.right.callee.name === 'read' &&
statement.expression.right.arguments.length >= 1 &&
statement.expression.right.arguments[0].type === 'CallExpression' &&
statement.expression.right.arguments[0].callee.type === 'Identifier' &&
statement.expression.right.arguments[0].callee.name === 'resolvePath' &&
statement.expression.right.arguments[0].arguments.length === 1 &&
statement.expression.right.arguments[0].arguments[0].type === 'Literal') {
const arg = statement.expression.right.arguments[0].arguments[0].value;
let resolved: string;
try {
const dep = await resolveDependency(String(arg), id, job);
if (typeof dep === 'string') {
resolved = dep;
} else {
return undefined;
}
}
catch (e) {
return undefined;
}
// The asset relocator will then pick up the AST rewriting from here
const relResolved = '/' + relative(dirname(id), resolved);
statement.expression.right.arguments[0] = {
type: 'BinaryExpression',
// @ts-ignore Its okay if start is undefined
start: statement.expression.right.arguments[0].start,
// @ts-ignore Its okay if end is undefined
end: statement.expression.right.arguments[0].end,
operator: '+',
left: {
type: 'Identifier',
name: '__dirname'
},
right: {
type: 'Literal',
value: relResolved,
raw: JSON.stringify(relResolved)
}
};
}
return undefined;
}
for (const statement of ast.body) {
if (statement.type === 'ExpressionStatement' &&
statement.expression.type === 'AssignmentExpression' &&
statement.expression.operator === '=' &&
statement.expression.left.type === 'MemberExpression' &&
statement.expression.left.object.type === 'MemberExpression' &&
statement.expression.left.object.object.type === 'Identifier' &&
statement.expression.left.object.object.name === 'Server' &&
statement.expression.left.object.property.type === 'Identifier' &&
statement.expression.left.object.property.name === 'prototype' &&
statement.expression.left.property.type === 'Identifier' &&
statement.expression.left.property.name === 'serveClient' &&
statement.expression.right.type === 'FunctionExpression') {
for (const node of statement.expression.right.body.body) {
if (node.type === 'IfStatement' && node.consequent && 'body' in node.consequent && node.consequent.body) {
const ifBody = node.consequent.body;
let replaced: boolean | undefined = false;
if (Array.isArray(ifBody) && ifBody[0] && ifBody[0].type === 'ExpressionStatement') {
replaced = await replaceResolvePathStatement(ifBody[0]);
}
if (Array.isArray(ifBody) && ifBody[1] && ifBody[1].type === 'TryStatement' && ifBody[1].block.body && ifBody[1].block.body[0]) {
replaced = await replaceResolvePathStatement(ifBody[1].block.body[0]) || replaced;
}
return;
}
}
}
}
}
},
'typescript' ({ id, emitAssetDirectory }) {
if (id.endsWith('typescript/lib/tsc.js')) {
emitAssetDirectory(resolve(id, '../'));
}
},
'uglify-es' ({ id, emitAsset }) {
if (id.endsWith('uglify-es/tools/node.js')) {
emitAsset(resolve(id, '../../lib/utils.js'));
emitAsset(resolve(id, '../../lib/ast.js'));
emitAsset(resolve(id, '../../lib/parse.js'));
emitAsset(resolve(id, '../../lib/transform.js'));
emitAsset(resolve(id, '../../lib/scope.js'));
emitAsset(resolve(id, '../../lib/output.js'));
emitAsset(resolve(id, '../../lib/compress.js'));
emitAsset(resolve(id, '../../lib/sourcemap.js'));
emitAsset(resolve(id, '../../lib/mozilla-ast.js'));
emitAsset(resolve(id, '../../lib/propmangle.js'));
emitAsset(resolve(id, '../../lib/minify.js'));
emitAsset(resolve(id, '../exports.js'));
}
},
'uglify-js' ({ id, emitAsset, emitAssetDirectory }) {
if (id.endsWith('uglify-js/tools/node.js')) {
emitAssetDirectory(resolve(id, '../../lib'));
emitAsset(resolve(id, '../exports.js'));
}
},
'playwright-core' ({ id, emitAsset }) {
if (id.endsWith('playwright-core/index.js')) {
emitAsset(resolve(dirname(id), 'browsers.json'));
}
},
'geo-tz'({ id, emitAsset }) {
if (id.endsWith('geo-tz/dist/geo-tz.js')) {
emitAsset(resolve(dirname(id), '../data/geo.dat'));
}
},
};
interface SpecialCaseOpts {
id: string;
ast: Ast;
emitAsset: (filename: string) => void;
emitAssetDirectory: (dirname: string) => void;
job: Job;
}
export default async function handleSpecialCases({ id, ast, emitAsset, emitAssetDirectory, job }: SpecialCaseOpts) {
const pkgName = getPackageName(id);
const specialCase = specialCases[pkgName || ''];
id = id.replace(/\\/g, '/');
if (specialCase) await specialCase({ id, ast, emitAsset, emitAssetDirectory, job });
}; | the_stack |
import Electron, { Menu } from 'electron'
import CommonUtil from '~/src/library/util/common'
import ConfigHelperUtil from '~/src/library/util/config_helper'
import PathConfig from '~/src/config/path'
import Logger from '~/src/library/logger'
import DispatchTaskCommand from '~/src/command/dispatch_task'
import DataTransferExport from '~/src/command/datatransfer/export'
import DataTransferImport from '~/src/command/datatransfer/import'
import InitEnvCommand from '~/src/command/init_env'
import MUser from '~/src/model/mblog_user'
import MBlog from '~/src/model/mblog'
import fs from 'fs'
import _ from 'lodash'
import sharp from 'sharp'
import path from 'path'
let argv = process.argv
let isDebug = argv.includes('--debug')
let { app, BrowserWindow, ipcMain, session, shell } = Electron
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow: Electron.BrowserWindow
// 关闭https证书校验
app.commandLine.appendSwitch('ignore-certificate-errors', 'true')
// 解除node.js内存限制
app.commandLine.appendSwitch('js-flags', '--max-old-space-size=8192');
app.commandLine.appendSwitch('--js-flags', '--max-old-space-size=8192');
let isRunning = false
// subWindow需要放在外边, 以便在全局中传递
let subWindow: InstanceType<typeof BrowserWindow> = null
function createWindow() {
// 项目启动时先初始化运行环境
let initCommand = new InitEnvCommand()
initCommand.handle({}, {})
if (process.platform === 'darwin') {
const template = [
{
label: 'Application',
submenu: [
{
label: 'Quit',
accelerator: 'Command+Q',
click: function () {
app.quit()
},
},
],
},
{
label: 'Edit',
submenu: [
{ label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' },
{ label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' },
],
},
]
Menu.setApplicationMenu(Menu.buildFromTemplate(template))
} else {
Menu.setApplicationMenu(null)
}
const { screen } = Electron
const { width, height } = screen.getPrimaryDisplay().workAreaSize
// Create the browser window.
mainWindow = new BrowserWindow({
width,
height,
// 自动隐藏菜单栏
autoHideMenuBar: true,
// 窗口的默认标题
title: '稳部落',
// 在屏幕中间展示窗口
center: true,
// 展示原生窗口栏
frame: true,
// 禁用web安全功能 --> 个人软件, 要啥自行车
webPreferences: {
// 开启 DevTools.
devTools: true,
// 禁用同源策略, 允许加载任何来源的js
webSecurity: false,
// 允许 https 页面运行 http url 里的资源
allowRunningInsecureContent: true,
// 启用node支持
nodeIntegration: true,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true,
// contextIsolation: false,
// 启用remote模块支持
enableRemoteModule: true,
// 启用webview标签
webviewTag: true,
},
})
// and load the index.html of the app.
if (isDebug) {
// 本地调试 & 打开控制台
mainWindow.loadURL('http://127.0.0.1:8000')
mainWindow.webContents.openDevTools()
} else {
// 线上地址
mainWindow.loadFile('./client/dist/index.html')
}
// 通过Electron自身将html渲染为图片, 借此将代码体积由300mb压缩至90mb
subWindow = new BrowserWindow({
enableLargerThanScreen: true,
width: 760,
height: 10,
// 配置最大高度, 该值默认值为屏幕高度, 如果大于该高度, 会出现滚动条
maxHeight: 10000,
// 负责渲染的子窗口不需要显示出来, 避免被用户误关闭
show: false
})
async function debugCaputure() {
let targetSource = "file:///F:/www/share/github/stablog/%E7%A8%B3%E9%83%A8%E8%90%BD%E8%BE%93%E5%87%BA%E7%9A%84%E7%94%B5%E5%AD%90%E4%B9%A6/%E5%85%94%E4%B8%BB%E5%B8%AD-%E5%BE%AE%E5%8D%9A%E6%95%B4%E7%90%86(2021-03-08~2021-03-27)/html_to_pdf/2021%EF%BC%8D03%EF%BC%8D27%2013%EF%BC%9A27%EF%BC%9A40_4619352240819112.html"
let demoUri = path.resolve(__dirname, "../demo.jpg")
const Const_Max_Webview_Render_Height_Px = 5000
const Const_Default_Webview_Width = 760
const Const_Default_Webview_Height = 10
let webview = subWindow.webContents
let globalSubWindow = subWindow
await webview.loadURL(targetSource);
// this.log("setContentSize -> ", Const_Default_Webview_Width, Const_Default_Webview_Height)
await globalSubWindow.setContentSize(
Const_Default_Webview_Width,
Const_Default_Webview_Height,
);
// @alert 注意, 在这里有可能卡死, 表现为卡住停止执行. 所以需要在外部加一个超时限制
// this.log("resize page, executeJavaScript ")
let scrollHeight = await webview.executeJavaScript(
`document.children[0].children[1].scrollHeight`,
);
let jpgContent: Buffer
if (scrollHeight > Const_Max_Webview_Render_Height_Px) {
// html页面太大, 需要分页输出, 最后再合成一张图片返回
let imgContentList: any[] = []
let remainHeight = scrollHeight
await subWindow.setContentSize(Const_Default_Webview_Width, Const_Max_Webview_Render_Height_Px);
// console.log("remainHeight => ", remainHeight)
// console.log("Const_Max_Height_Px => ", Const_Max_Height_Px)
let mergeImg = sharp({
create: {
width: Const_Default_Webview_Width,
height: scrollHeight,
channels: 4,
background: {
r: 255, g: 255, b: 255, alpha: 1,
},
}
}).jpeg({ quality: 100 })
while (remainHeight >= Const_Max_Webview_Render_Height_Px) {
let imgIndex = imgContentList.length;
let currentOffsetHeight = Const_Max_Webview_Render_Height_Px * imgIndex
// 先移动到offset高度
let command = `document.children[0].children[1].scrollTop = ${currentOffsetHeight}`
await webview.executeJavaScript(command);
// 然后对界面截屏
// js指令执行后, 滚动到指定位置还需要时间, 所以截屏前需要sleep一下
await CommonUtil.asyncSleep(1000 * 0.5)
let nativeImg = await webview.capturePage();
let content = await nativeImg.toJPEG(100)
remainHeight = remainHeight - Const_Max_Webview_Render_Height_Px
imgContentList.push(
{
input: content,
top: Const_Max_Webview_Render_Height_Px * imgIndex,
left: 0,
}
)
}
if (remainHeight > 0) {
// 最后捕捉剩余高度页面
// 首先调整页面高度
await subWindow.setContentSize(Const_Default_Webview_Width, remainHeight);
// 然后走流程, 捕捉界面
let currentOffsetHeight = Const_Max_Webview_Render_Height_Px * imgContentList.length
let imgIndex = imgContentList.length;
// 先移动到offset高度
let command = `document.children[0].children[1].scrollTop = ${currentOffsetHeight}`
await webview.executeJavaScript(command);
// 然后对界面截屏
// js指令执行后, 滚动到指定位置还需要时间, 所以截屏前需要sleep一下
await CommonUtil.asyncSleep(1000 * 0.5)
let nativeImg = await webview.capturePage();
let content = await nativeImg.toJPEG(100)
imgContentList.push(
{
input: content,
top: Const_Max_Webview_Render_Height_Px * imgIndex,
left: 0,
}
)
}
// 最后将imgContentList合并为一张图片
mergeImg.composite(
imgContentList
)
jpgContent = await mergeImg.toBuffer()
} else {
// 小于最大宽度, 只要截屏一次就可以
await subWindow.setContentSize(Const_Default_Webview_Width, scrollHeight);
// this.log("setContentSize with scrollHeight -> ", scrollHeight)
let nativeImg = await webview.capturePage();
jpgContent = await nativeImg.toJPEG(100);
}
console.log("demoUri => ", demoUri)
fs.writeFileSync(demoUri, jpgContent)
}
// debugCaputure()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
// 主窗口关闭时, 子窗口需要随之关闭
subWindow.close()
subWindow = null
})
session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
// 设置ua
details.requestHeaders['User-Agent'] =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
// 设置reffer
details.requestHeaders['Referer'] = 'https://m.weibo.cn/'
callback({ cancel: false, requestHeaders: details.requestHeaders })
})
global.pathConfig = PathConfig
// 向html代码注入MUser, 方便查询
global.mUser = MUser
global.mBlog = MBlog
// 向html代码中注入子窗口, 方便将html渲染为图片
global.subWindow = subWindow
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
ipcMain.on('openOutputDir', async event => {
shell.showItemInFolder(PathConfig.outputPath)
event.returnValue = true
return
})
ipcMain.on('startCustomerTask', async event => {
if (isRunning) {
event.returnValue = '目前尚有任务执行, 请稍后'
return
}
isRunning = true
Logger.log('开始工作')
let cookieContent = ''
await new Promise((resolve, reject) => {
// 获取页面cookie
session.defaultSession.cookies.get({}, (error, cookieList) => {
for (let cookie of cookieList) {
cookieContent = `${cookie.name}=${cookie.value};${cookieContent}`
}
// 顺利获取cookie列表
resolve()
})
})
// 将cookie更新到本地配置中
let config = CommonUtil.getConfig()
_.set(config, ['request', 'cookie'], cookieContent)
fs.writeFileSync(PathConfig.configUri, JSON.stringify(config, null, 4))
Logger.log(`任务配置生成完毕`)
Logger.log(`重新载入cookie配置`)
ConfigHelperUtil.reloadConfig()
Logger.log(`开始执行任务`)
event.returnValue = 'success'
let dispatchTaskCommand = new DispatchTaskCommand()
await dispatchTaskCommand.handle({
subWindow
}, {})
Logger.log(`所有任务执行完毕, 打开电子书文件夹 => `, PathConfig.outputPath)
// 输出打开文件夹
shell.showItemInFolder(PathConfig.outputPath)
isRunning = false
})
ipcMain.on('dataTransferExport', async (event, arg: {
exportUri: string,
uid: string,
exportStartAt: number,
exportEndAt: number
}) => {
let {
exportUri,
uid,
exportStartAt,
exportEndAt
} = arg
Logger.log('开始导出', {
exportUri,
uid,
exportStartAt,
exportEndAt
})
let exportCommand = new DataTransferExport()
await exportCommand.handle({
exportUri,
uid,
exportStartAt,
exportEndAt
}, {}).catch()
Logger.log(`数据导出完毕, 打开导出目录 => `, PathConfig.outputPath)
// 输出打开文件夹
shell.showItemInFolder(exportUri)
event.returnValue = 'success'
})
ipcMain.on('dataTransferImport', async (event, arg: {
importUri: string,
}) => {
let {
importUri,
} = arg
Logger.log('开始导入数据', {
importUri
})
let importCommand = new DataTransferImport()
await importCommand.handle({
importUri
}, {}).catch()
Logger.log(`数据导入完毕`)
event.returnValue = 'success'
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here. | the_stack |
import { addClass, Browser, EventHandler, detach, removeClass, select, selectAll, KeyboardEvents} from '@syncfusion/ej2-base';
import { isNullOrUndefined as isNOU, KeyboardEventArgs, closest, isNullOrUndefined } from '@syncfusion/ej2-base';
import { setStyleAttribute, extend } from '@syncfusion/ej2-base';
import { Toolbar as tool, OverflowMode, ClickEventArgs } from '@syncfusion/ej2-navigations';
import * as events from '../base/constant';
import * as classes from '../base/classes';
import { RenderType, ToolbarType, ToolbarItems } from '../base/enum';
import { setToolbarStatus, updateUndoRedoStatus, getTBarItemsIndex, getCollection, toObjectLowerCase, isIDevice } from '../base/util';
import { updateDropDownFontFormatLocale } from '../base/util';
import * as model from '../models/items';
import { IRichTextEditor, IRenderer, NotifyArgs, IToolbarRenderOptions, IColorPickerRenderArgs } from '../base/interface';
import { IToolbarItemModel, IToolsItems, IUpdateItemsModel, IDropDownRenderArgs, ISetToolbarStatusArgs } from '../base/interface';
import { ServiceLocator } from '../services/service-locator';
import { RendererFactory } from '../services/renderer-factory';
import { ToolbarRenderer } from '../renderer/toolbar-renderer';
import { BaseToolbar } from './base-toolbar';
import { DropDownButtons } from './dropdown-buttons';
import { ToolbarAction } from './toolbar-action';
import { IToolbarStatus } from '../../common/interface';
import { RichTextEditorModel } from '../base/rich-text-editor-model';
/**
* `Toolbar` module is used to handle Toolbar actions.
*/
export class Toolbar {
public toolbarObj: tool;
private editPanel: Element;
private isToolbar: boolean;
private editableElement: Element;
private tbItems: HTMLElement[];
public baseToolbar: BaseToolbar;
private tbElement: HTMLElement;
private tbWrapper: HTMLElement;
protected parent: IRichTextEditor;
protected locator: ServiceLocator;
private isTransformChild: boolean;
private contentRenderer: IRenderer;
protected toolbarRenderer: IRenderer;
private dropDownModule: DropDownButtons;
private toolbarActionModule: ToolbarAction;
protected renderFactory: RendererFactory;
private keyBoardModule: KeyboardEvents;
private tools: { [key: string]: IToolsItems };
public constructor(parent?: IRichTextEditor, serviceLocator?: ServiceLocator) {
this.parent = parent;
this.isToolbar = false;
this.locator = serviceLocator;
this.isTransformChild = false;
this.renderFactory = this.locator.getService<RendererFactory>('rendererFactory');
model.updateDropDownLocale(this.parent);
updateDropDownFontFormatLocale(this.parent);
this.renderFactory.addRenderer(RenderType.Toolbar, new ToolbarRenderer(this.parent));
this.toolbarRenderer = this.renderFactory.getRenderer(RenderType.Toolbar);
this.baseToolbar = new BaseToolbar(this.parent, this.locator);
this.addEventListener();
if (this.parent.toolbarSettings && Object.keys(this.parent.toolbarSettings.itemConfigs).length > 0) {
extend(this.tools, model.tools, toObjectLowerCase(this.parent.toolbarSettings.itemConfigs), true);
} else {
this.tools = model.tools;
}
}
private initializeInstance(): void {
this.contentRenderer = this.renderFactory.getRenderer(RenderType.Content);
this.editableElement = this.contentRenderer.getEditPanel();
this.editPanel = this.contentRenderer.getPanel();
}
private toolbarBindEvent(): void {
if (!this.parent.inlineMode.enable) {
this.keyBoardModule = new KeyboardEvents(this.getToolbarElement() as HTMLElement, {
keyAction: this.toolBarKeyDown.bind(this), keyConfigs: this.parent.formatter.keyConfig, eventName: 'keydown'
});
}
}
private toolBarKeyDown(e: KeyboardEvent): void {
switch ((e as KeyboardEventArgs).action) {
case 'escape':
(this.parent.contentModule.getEditPanel() as HTMLElement).focus();
break;
}
}
private createToolbarElement(): void {
this.tbElement = this.parent.createElement('div', { id: this.parent.getID() + '_toolbar' });
if (!Browser.isDevice && this.parent.inlineMode.enable && isIDevice()) {
return;
} else {
if (this.parent.toolbarSettings.enableFloating && !this.parent.inlineMode.enable) {
this.tbWrapper = this.parent.createElement('div', {
id: this.parent.getID() + '_toolbar_wrapper',
innerHTML: this.tbElement.outerHTML,
className: classes.CLS_TB_WRAP
});
this.tbElement = this.tbWrapper.firstElementChild as HTMLElement;
this.parent.element.insertBefore(this.tbWrapper, this.editPanel);
} else {
this.parent.element.insertBefore(this.tbElement, this.editPanel);
}
}
}
private getToolbarMode(): OverflowMode {
let tbMode: OverflowMode;
switch (this.parent.toolbarSettings.type) {
case ToolbarType.Expand:
tbMode = 'Extended';
break;
case ToolbarType.Scrollable:
tbMode = 'Scrollable';
break;
default:
tbMode = 'MultiRow';
}
if (isIDevice() && this.parent.toolbarSettings.type === ToolbarType.Expand) {
tbMode = ToolbarType.Scrollable;
}
return tbMode;
}
private checkToolbarResponsive(ele: HTMLElement): boolean {
if (!Browser.isDevice || isIDevice()) {
return false;
}
let tBarMode : string;
if (this.parent.toolbarSettings.type === ToolbarType.Expand) {
tBarMode = ToolbarType.MultiRow;
} else {
tBarMode = this.parent.toolbarSettings.type;
}
this.baseToolbar.render({
container: ((this.parent.inlineMode.enable) ? 'quick' : 'toolbar'),
items: this.parent.toolbarSettings.items,
mode: tBarMode,
target: ele
} as IToolbarRenderOptions);
if (this.parent.toolbarSettings.type === ToolbarType.Expand) {
addClass([ele], ['e-rte-tb-mobile']);
if (this.parent.inlineMode.enable) {
this.addFixedTBarClass();
} else {
addClass([ele], [classes.CLS_TB_STATIC]);
}
}
this.wireEvents();
this.dropDownModule.renderDropDowns({
container: ele,
containerType: ((this.parent.inlineMode.enable) ? 'quick' : 'toolbar'),
items: this.parent.toolbarSettings.items
} as IDropDownRenderArgs);
this.parent.notify(events.renderColorPicker, {
container: this.tbElement,
containerType: ((this.parent.inlineMode.enable) ? 'quick' : 'toolbar'),
items: this.parent.toolbarSettings.items
} as IColorPickerRenderArgs);
return true;
}
private checkIsTransformChild(): void {
this.isTransformChild = false;
const transformElements: HTMLElement[] = <HTMLElement[]>selectAll('[style*="transform"]', document);
for (let i: number = 0; i < transformElements.length; i++) {
if (!isNullOrUndefined(transformElements[i].contains) && transformElements[i].contains(this.parent.element)) {
this.isTransformChild = true;
break;
}
}
}
private toggleFloatClass(e?: Event): void {
let topValue: number;
let isBody: boolean = false;
let isFloat: boolean = false;
let scrollParent: HTMLElement;
const floatOffset: number = this.parent.floatingToolbarOffset;
if (e && this.parent.iframeSettings.enable && this.parent.inputElement.ownerDocument === e.target) {
scrollParent = (e.target as Document).body as HTMLElement;
} else if (e && e.target !== document) {
scrollParent = e.target as HTMLElement;
} else {
isBody = true;
scrollParent = document.body;
}
const tbHeight: number = this.getToolbarHeight() + this.getExpandTBarPopHeight();
if (this.isTransformChild) {
topValue = 0;
let scrollParentRelativeTop: number = 0;
const trgHeight: number = this.parent.element.offsetHeight;
if (isBody) {
const bodyStyle: CSSStyleDeclaration = window.getComputedStyle(scrollParent);
scrollParentRelativeTop = parseFloat(bodyStyle.marginTop.split('px')[0]) + parseFloat(bodyStyle.paddingTop.split('px')[0]);
}
const targetTop: number = this.parent.element.getBoundingClientRect().top;
const scrollParentYOffset: number = (Browser.isMSPointer && isBody) ? window.pageYOffset : scrollParent.parentElement.scrollTop;
const scrollParentRect: ClientRect = scrollParent.getBoundingClientRect();
const scrollParentTop: number = (!isBody) ? scrollParentRect.top : (scrollParentRect.top + scrollParentYOffset);
const outOfRange: boolean = ((targetTop - ((!isBody) ? scrollParentTop : 0))
+ trgHeight > tbHeight + floatOffset) ? false : true;
if (targetTop > (scrollParentTop + floatOffset) || targetTop < -trgHeight || ((targetTop < 0) ? outOfRange : false)) {
isFloat = false;
removeClass([this.tbElement], [classes.CLS_TB_ABS_FLOAT]);
} else if (targetTop < (scrollParentTop + floatOffset)) {
if (targetTop < 0) {
topValue = (-targetTop) + scrollParentTop;
} else {
topValue = scrollParentTop - targetTop;
}
topValue = (isBody) ? topValue - scrollParentRelativeTop : topValue;
addClass([this.tbElement], [classes.CLS_TB_ABS_FLOAT]);
isFloat = true;
}
} else {
const parent: ClientRect = this.parent.element.getBoundingClientRect();
if (window.innerHeight < parent.top) {
return;
}
topValue = (e && e.target !== document) ? scrollParent.getBoundingClientRect().top : 0;
if ((parent.bottom < (floatOffset + tbHeight + topValue)) || parent.bottom < 0 || parent.top > floatOffset + topValue) {
isFloat = false;
} else if (parent.top < floatOffset) {
isFloat = true;
}
}
if (!isFloat) {
removeClass([this.tbElement], [classes.CLS_TB_FLOAT]);
setStyleAttribute(this.tbElement, { top: 0 + 'px', width: '100%' });
} else {
addClass([this.tbElement], [classes.CLS_TB_FLOAT]);
setStyleAttribute(this.tbElement, { width: this.parent.element.offsetWidth + 'px', top: (floatOffset + topValue) + 'px' });
}
}
private renderToolbar(): void {
this.initializeInstance();
this.createToolbarElement();
if (this.checkToolbarResponsive(this.tbElement)) {
return;
}
if (this.parent.inlineMode.enable) {
this.parent.notify(events.renderInlineToolbar, {});
} else {
this.baseToolbar.render({
container: 'toolbar',
items: this.parent.toolbarSettings.items,
mode: this.getToolbarMode(),
target: this.tbElement
} as IToolbarRenderOptions);
if (!this.parent.inlineMode.enable) {
if (this.parent.toolbarSettings.enableFloating) {
this.checkIsTransformChild();
this.toggleFloatClass();
}
addClass([this.parent.element], [classes.CLS_RTE_TB_ENABLED]);
if (this.parent.toolbarSettings.type === ToolbarType.Expand) {
addClass([this.parent.element], [classes.CLS_RTE_EXPAND_TB]);
}
}
}
this.wireEvents();
if (this.parent.inlineMode.enable && !isIDevice()) {
this.addFixedTBarClass();
}
if (!this.parent.inlineMode.enable) {
this.dropDownModule.renderDropDowns({
container: this.tbElement,
containerType: 'toolbar',
items: this.parent.toolbarSettings.items
} as IDropDownRenderArgs);
this.parent.notify(events.renderColorPicker, {
container: this.tbElement,
containerType: 'toolbar',
items: this.parent.toolbarSettings.items
} as IColorPickerRenderArgs);
this.refreshToolbarOverflow();
}
const divEle: HTMLElement = this.parent.element.querySelector('.e-rte-srctextarea') as HTMLElement;
const iframeEle: HTMLElement = this.parent.element.querySelector('.e-source-content') as HTMLElement;
if ((!this.parent.iframeSettings.enable && (!isNOU(divEle) && divEle.style.display === 'block')) ||
(this.parent.iframeSettings.enable && (!isNOU(iframeEle) && iframeEle.style.display === 'block'))) {
this.parent.notify(events.updateToolbarItem, {
targetItem: 'SourceCode', updateItem: 'Preview',
baseToolbar: this.parent.getBaseToolbarObject()
});
this.parent.disableToolbarItem(this.parent.toolbarSettings.items as string[]);
}
}
/**
* addFixedTBarClass method
*
* @returns {void}
* @hidden
* @deprecated
*/
public addFixedTBarClass(): void {
addClass([this.tbElement], [classes.CLS_TB_FIXED]);
}
/**
* removeFixedTBarClass method
*
* @returns {void}
* @hidden
* @deprecated
*/
public removeFixedTBarClass(): void {
removeClass([this.tbElement], [classes.CLS_TB_FIXED]);
}
private showFixedTBar(): void {
addClass([this.tbElement], [classes.CLS_SHOW]);
if (Browser.isIos) {
addClass([this.tbElement], [classes.CLS_TB_IOS_FIX]);
}
}
private hideFixedTBar(): void {
// eslint-disable-next-line
(!this.isToolbar) ? removeClass([this.tbElement], [classes.CLS_SHOW, classes.CLS_TB_IOS_FIX]) : this.isToolbar = false;
}
/**
* updateItem method
*
* @param {IUpdateItemsModel} args - specifies the arguments.
* @returns {void}
* @hidden
* @deprecated
*/
public updateItem(args: IUpdateItemsModel): void {
const item: IToolsItems = this.tools[args.updateItem.toLocaleLowerCase() as ToolbarItems];
const trgItem: IToolsItems = this.tools[args.targetItem.toLocaleLowerCase() as ToolbarItems];
const index: number = getTBarItemsIndex(getCollection(trgItem.subCommand), args.baseToolbar.toolbarObj.items)[0];
if (!isNOU(index)) {
const prefixId: string = this.parent.inlineMode.enable ? '_quick_' : '_toolbar_';
args.baseToolbar.toolbarObj.items[index].id = this.parent.getID() + prefixId + item.id;
args.baseToolbar.toolbarObj.items[index].prefixIcon = item.icon;
args.baseToolbar.toolbarObj.items[index].tooltipText = item.tooltip;
(args.baseToolbar.toolbarObj.items as IToolbarItemModel[])[index].subCommand = item.subCommand;
args.baseToolbar.toolbarObj.dataBind();
} else {
this.addTBarItem(args, 0);
}
}
private updateToolbarStatus(args: IToolbarStatus): void {
if (!this.tbElement || (this.parent.inlineMode.enable && (isIDevice() || !Browser.isDevice))) {
return;
}
const options: ISetToolbarStatusArgs = {
args: args,
dropDownModule: this.dropDownModule,
parent: this.parent,
tbElements: selectAll('.' + classes.CLS_TB_ITEM, this.tbElement),
tbItems: this.baseToolbar.toolbarObj.items
};
setToolbarStatus(options, (this.parent.inlineMode.enable ? true : false), this.parent);
}
private fullScreen(e?: MouseEvent): void {
this.parent.fullScreenModule.showFullScreen(e);
}
private hideScreen(e?: MouseEvent): void {
this.parent.fullScreenModule.hideFullScreen(e);
}
/**
* getBaseToolbar method
*
* @returns {void}
* @hidden
* @deprecated
*/
public getBaseToolbar(): BaseToolbar {
return this.baseToolbar;
}
/**
* addTBarItem method
*
* @param {IUpdateItemsModel} args - specifies the arguments.
* @param {number} index - specifies the index value.
* @returns {void}
* @hidden
* @deprecated
*/
public addTBarItem(args: IUpdateItemsModel, index: number): void {
args.baseToolbar.toolbarObj.addItems([args.baseToolbar.getObject(args.updateItem, 'toolbar')], index);
}
/**
* enableTBarItems method
*
* @param {BaseToolbar} baseToolbar - specifies the toolbar.
* @param {string} items - specifies the string value.
* @param {boolean} isEnable - specifies the boolean value.
* @param {boolean} muteToolbarUpdate - specifies the toolbar.
* @returns {void}
* @hidden
* @deprecated
*/
public enableTBarItems(baseToolbar: BaseToolbar, items: string | string[], isEnable: boolean , muteToolbarUpdate?: boolean): void {
const trgItems: number[] = getTBarItemsIndex(getCollection(items), baseToolbar.toolbarObj.items);
this.tbItems = selectAll('.' + classes.CLS_TB_ITEM, baseToolbar.toolbarObj.element);
for (let i: number = 0; i < trgItems.length; i++) {
const item: HTMLElement = this.tbItems[trgItems[i]];
if (item) {
baseToolbar.toolbarObj.enableItems(item, isEnable);
}
}
if (!select('.e-rte-srctextarea', this.parent.element) && !muteToolbarUpdate) {
updateUndoRedoStatus(baseToolbar, this.parent.formatter.editorManager.undoRedoManager.getUndoStatus());
}
}
/**
* removeTBarItems method
*
* @param {string} items - specifies the string value.
* @returns {void}
* @hidden
* @deprecated
*/
public removeTBarItems(items: string | string[]): void {
if (isNullOrUndefined(this.baseToolbar.toolbarObj)) {
this.baseToolbar = this.parent.getBaseToolbarObject();
}
const trgItems: number[] = getTBarItemsIndex(getCollection(items), this.baseToolbar.toolbarObj.items);
this.tbItems = (this.parent.inlineMode.enable) ? selectAll('.' + classes.CLS_TB_ITEM, this.baseToolbar.toolbarObj.element)
: selectAll('.' + classes.CLS_TB_ITEM, this.parent.element);
for (let i: number = 0; i < trgItems.length; i++) {
this.baseToolbar.toolbarObj.removeItems(this.tbItems[trgItems[i]]);
}
}
/**
* getExpandTBarPopHeight method
*
* @returns {void}
* @hidden
* @deprecated
*/
public getExpandTBarPopHeight(): number {
let popHeight: number = 0;
if (this.parent.toolbarSettings.type === ToolbarType.Expand && this.tbElement.classList.contains('e-extended-toolbar')) {
const expandPopup: HTMLElement = <HTMLElement>select('.e-toolbar-extended', this.tbElement);
if (expandPopup && this.tbElement.classList.contains('e-expand-open')
|| expandPopup && expandPopup.classList.contains('e-popup-open')) {
addClass([expandPopup], [classes.CLS_VISIBLE]);
popHeight = popHeight + expandPopup.offsetHeight;
removeClass([expandPopup], [classes.CLS_VISIBLE]);
} else {
removeClass([this.tbElement], [classes.CLS_EXPAND_OPEN]);
}
}
return popHeight;
}
/**
* getToolbarHeight method
*
* @returns {void}
* @hidden
* @deprecated
*/
public getToolbarHeight(): number {
return this.tbElement.offsetHeight;
}
/**
* getToolbarElement method
*
* @returns {void}
* @hidden
* @deprecated
*/
public getToolbarElement(): Element {
return select('.' + classes.CLS_TOOLBAR, this.parent.element);
}
/**
* refreshToolbarOverflow method
*
* @returns {void}
* @hidden
* @deprecated
*/
public refreshToolbarOverflow(): void {
this.baseToolbar.toolbarObj.refreshOverflow();
}
private isToolbarDestroyed(): boolean {
return this.baseToolbar.toolbarObj && !this.baseToolbar.toolbarObj.isDestroyed;
}
private destroyToolbar(): void {
if (this.isToolbarDestroyed()) {
this.parent.unWireScrollElementsEvents();
this.unWireEvents();
this.parent.notify(events.destroyColorPicker, {});
this.dropDownModule.destroyDropDowns();
this.baseToolbar.toolbarObj.destroy();
this.removeEventListener();
removeClass([this.parent.element], [classes.CLS_RTE_TB_ENABLED]);
removeClass([this.parent.element], [classes.CLS_RTE_EXPAND_TB]);
const tbWrapper: HTMLElement = <HTMLElement>select('.' + classes.CLS_TB_WRAP, this.parent.element);
const tbElement: HTMLElement = <HTMLElement>select('.' + classes.CLS_TOOLBAR, this.parent.element);
if (!isNullOrUndefined(tbWrapper)) {
detach(tbWrapper);
} else if (!isNullOrUndefined(tbElement)) {
detach(tbElement);
}
}
}
/**
* Destroys the ToolBar.
*
* @function destroy
* @returns {void}
* @hidden
* @deprecated
*/
public destroy(): void {
if (this.isToolbarDestroyed()) {
this.destroyToolbar();
if (this.keyBoardModule) {
this.keyBoardModule.destroy();
}
}
}
private scrollHandler(e: NotifyArgs): void {
if (!this.parent.inlineMode.enable) {
if (this.parent.toolbarSettings.enableFloating && this.getDOMVisibility(this.tbElement)) {
this.toggleFloatClass(e.args as Event);
}
}
}
private getDOMVisibility(el: HTMLElement): boolean {
if (!el.offsetParent && el.offsetWidth === 0 && el.offsetHeight === 0) {
return false;
}
return true;
}
private mouseDownHandler(): void {
if (Browser.isDevice && this.parent.inlineMode.enable && !isIDevice()) {
this.showFixedTBar();
}
}
private focusChangeHandler(): void {
if (Browser.isDevice && this.parent.inlineMode.enable && !isIDevice()) {
this.isToolbar = false;
this.hideFixedTBar();
}
}
private dropDownBeforeOpenHandler(): void {
this.isToolbar = true;
}
// eslint-disable-next-line
private tbFocusHandler(e: Event): void {
const activeElm: Element = document.activeElement;
const isToolbaractive: Element = closest(activeElm as Element, '.e-rte-toolbar');
if (activeElm === this.parent.getToolbarElement() || isToolbaractive === this.parent.getToolbarElement()) {
const toolbarItem: NodeList = this.parent.getToolbarElement().querySelectorAll('.e-expended-nav');
for (let i: number = 0; i < toolbarItem.length; i++) {
if (isNOU(this.parent.getToolbarElement().querySelector('.e-insert-table-btn'))) {
(toolbarItem[i] as HTMLElement).setAttribute('tabindex', '0');
} else {
(toolbarItem[i] as HTMLElement).setAttribute('tabindex', '1');
}
}
}
}
private tbKeydownHandler(e: Event): void {
if ((e.target as HTMLElement).classList.contains('e-dropdown-btn') ||
(e.target as HTMLElement).getAttribute('id') === this.parent.getID() + '_toolbar_CreateTable') {
(e.target as HTMLElement).setAttribute('tabindex', '0');
}
}
private toolbarClickHandler(e: ClickEventArgs): void {
const trg: Element = closest(e.originalEvent.target as Element, '.e-hor-nav');
if (trg && this.parent.toolbarSettings.type === ToolbarType.Expand && !isNOU(trg)) {
if (!trg.classList.contains('e-nav-active')) {
removeClass([this.tbElement], [classes.CLS_EXPAND_OPEN]);
this.parent.setContentHeight('toolbar', false);
} else {
addClass([this.tbElement], [classes.CLS_EXPAND_OPEN]);
this.parent.setContentHeight('toolbar', true);
}
} else if (Browser.isDevice || this.parent.inlineMode.enable) {
this.isToolbar = true;
}
if (isNOU(trg) && this.parent.toolbarSettings.type === ToolbarType.Expand) {
removeClass([this.tbElement], [classes.CLS_EXPAND_OPEN]);
}
}
protected wireEvents(): void {
if (this.parent.inlineMode.enable && isIDevice()) {
return;
}
EventHandler.add(this.tbElement, 'focusin', this.tbFocusHandler, this);
EventHandler.add(this.tbElement, 'keydown', this.tbKeydownHandler, this);
}
protected unWireEvents(): void {
EventHandler.remove(this.tbElement, 'focusin', this.tbFocusHandler);
EventHandler.remove(this.tbElement, 'keydown', this.tbKeydownHandler);
}
protected addEventListener(): void {
if (this.parent.isDestroyed) {
return;
}
this.dropDownModule = new DropDownButtons(this.parent, this.locator);
this.toolbarActionModule = new ToolbarAction(this.parent);
this.parent.on(events.initialEnd, this.renderToolbar, this);
this.parent.on(events.scroll, this.scrollHandler, this);
this.parent.on(events.bindOnEnd, this.toolbarBindEvent, this);
this.parent.on(events.toolbarUpdated, this.updateToolbarStatus, this);
this.parent.on(events.modelChanged, this.onPropertyChanged, this);
this.parent.on(events.refreshBegin, this.onRefresh, this);
this.parent.on(events.destroy, this.destroy, this);
this.parent.on(events.enableFullScreen, this.fullScreen, this);
this.parent.on(events.disableFullScreen, this.hideScreen, this);
this.parent.on(events.updateToolbarItem, this.updateItem, this);
this.parent.on(events.beforeDropDownOpen, this.dropDownBeforeOpenHandler, this);
this.parent.on(events.expandPopupClick, this.parent.setContentHeight, this.parent);
this.parent.on(events.focusChange, this.focusChangeHandler, this);
this.parent.on(events.mouseDown, this.mouseDownHandler, this);
this.parent.on(events.sourceCodeMouseDown, this.mouseDownHandler, this);
if (!this.parent.inlineMode.enable && !isIDevice()) {
this.parent.on(events.toolbarClick, this.toolbarClickHandler, this);
}
}
protected removeEventListener(): void {
if (this.parent.isDestroyed) {
return;
}
this.parent.off(events.initialEnd, this.renderToolbar);
this.parent.off(events.scroll, this.scrollHandler);
this.parent.off(events.bindOnEnd, this.toolbarBindEvent);
this.parent.off(events.toolbarUpdated, this.updateToolbarStatus);
this.parent.off(events.modelChanged, this.onPropertyChanged);
this.parent.off(events.refreshBegin, this.onRefresh);
this.parent.off(events.destroy, this.destroy);
this.parent.off(events.enableFullScreen, this.parent.fullScreenModule.showFullScreen);
this.parent.off(events.disableFullScreen, this.parent.fullScreenModule.hideFullScreen);
this.parent.off(events.updateToolbarItem, this.updateItem);
this.parent.off(events.beforeDropDownOpen, this.dropDownBeforeOpenHandler);
this.parent.off(events.expandPopupClick, this.parent.setContentHeight);
this.parent.off(events.focusChange, this.focusChangeHandler);
this.parent.off(events.mouseDown, this.mouseDownHandler);
this.parent.off(events.sourceCodeMouseDown, this.mouseDownHandler);
if (!this.parent.inlineMode.enable && !isIDevice()) {
this.parent.off(events.toolbarClick, this.toolbarClickHandler);
}
}
private onRefresh(): void {
this.refreshToolbarOverflow();
this.parent.setContentHeight('', true);
}
/**
* Called internally if any of the property value changed.
*
* @param {RichTextEditorModel} e - specifies the string value
* @returns {void}
* @hidden
* @deprecated
*/
protected onPropertyChanged(e: { [key: string]: RichTextEditorModel }): void {
if (!isNullOrUndefined(e.newProp.inlineMode)) {
for (const prop of Object.keys(e.newProp.inlineMode)) {
switch (prop) {
case 'enable':
this.refreshToolbar();
break;
}
}
}
if (e.module !== this.getModuleName()) {
return;
}
this.refreshToolbar();
}
private refreshToolbar(): void {
if (isNullOrUndefined(this.baseToolbar.toolbarObj)) {
this.baseToolbar = this.parent.getBaseToolbarObject();
}
const tbWrapper: Element = select('.' + classes.CLS_TB_WRAP, this.parent.element);
const tbElement: Element = select('.' + classes.CLS_TOOLBAR, this.parent.element);
if (tbElement || tbWrapper) {
this.destroyToolbar();
}
if (this.parent.toolbarSettings.enable) {
this.addEventListener();
this.renderToolbar();
this.parent.wireScrollElementsEvents();
if (!select('.e-rte-srctextarea', this.parent.element)) {
updateUndoRedoStatus(this.baseToolbar, this.parent.formatter.editorManager.undoRedoManager.getUndoStatus());
}
this.parent.notify(events.dynamicModule, {});
}
}
/**
* For internal use only - Get the module name.
*
* @returns {void}
* @hidden
*/
private getModuleName(): string {
return 'toolbar';
}
} | the_stack |
import { Animation, AnimationOptions, isNullOrUndefined } from '@syncfusion/ej2-base';
import { effect, getPathArc } from '../utils/helper';
import { ProgressBar } from '../progressbar';
import { lineCapRadius, completeAngle } from '../model/constant';
/**
* Animation for progress bar
*/
export class ProgressAnimation {
/** Linear Animation */
public doLinearAnimation(element: Element, progress: ProgressBar, delay: number, previousWidth?: number, active?: Element): void {
const animation: Animation = new Animation({});
const linearPath: HTMLElement = <HTMLElement>element;
const duration: number = (progress.isActive) ? 3000 : progress.animation.duration;
const width: string = linearPath.getAttribute('width');
const x: string = linearPath.getAttribute('x');
let opacityValue: number = 0;
let value: number = 0;
const start: number = (!progress.enableRtl || (progress.cornerRadius === 'Round4px')) ? previousWidth : parseInt(x, 10);
const end: number = (!progress.enableRtl || (progress.cornerRadius === 'Round4px')) ? parseInt(width, 10) - start :
parseInt(width, 10) - previousWidth;
const rtlX: number = parseInt(x, 10) - end;
linearPath.style.visibility = 'hidden';
animation.animate(linearPath, {
duration: duration,
delay: delay,
progress: (args: AnimationOptions): void => {
progress.cancelResize = true;
if (progress.enableRtl && !(progress.cornerRadius === 'Round4px')) {
if (args.timeStamp >= args.delay) {
linearPath.style.visibility = 'visible';
if (progress.isActive) {
value = this.activeAnimate((args.timeStamp / args.duration), parseInt(x, 10), parseInt(width, 10), true);
opacityValue = effect(args.timeStamp, 0.5, 0.5, args.duration, true);
active.setAttribute('opacity', opacityValue.toString());
linearPath.setAttribute('x', value.toString());
} else {
value = effect(args.timeStamp, start, end, args.duration, true);
linearPath.setAttribute('x', value.toString());
}
}
} else {
if (args.timeStamp >= args.delay) {
linearPath.style.visibility = 'visible';
if (progress.isActive) {
value = this.activeAnimate((args.timeStamp / args.duration), 0, parseInt(width, 10), false);
opacityValue = effect(args.timeStamp, 0.5, 0.5, args.duration, true);
active.setAttribute('opacity', opacityValue.toString());
linearPath.setAttribute('width', value.toString());
} else {
value = effect(args.timeStamp, start, end, args.duration, false);
linearPath.setAttribute('width', value.toString());
}
}
}
},
end: () => {
progress.cancelResize = false;
linearPath.style.visibility = '';
if (progress.enableRtl && !(progress.cornerRadius === 'Round4px')) {
if (progress.isActive) {
linearPath.setAttribute('x', x.toString());
this.doLinearAnimation(element, progress, delay, previousWidth, active);
} else {
linearPath.setAttribute('x', rtlX.toString());
}
} else {
linearPath.setAttribute('width', width);
if (progress.isActive) {
this.doLinearAnimation(element, progress, delay, previousWidth, active);
}
}
progress.trigger('animationComplete', {
value: progress.value, trackColor: progress.trackColor,
progressColor: progress.progressColor
});
}
});
}
/** Linear Indeterminate */
public doLinearIndeterminate(
element: Element, progressWidth: number, thickness: number, progress: ProgressBar, clipPath: Element
): void {
const animation: Animation = new Animation({});
const linearPath: HTMLElement = <HTMLElement>element;
const x: string = linearPath.getAttribute('x');
const width: string = linearPath.getAttribute('width');
let value: number = 0;
const start: number = (width) ? -(parseInt(width, 10)) : -progressWidth;
const end: number = (progress.progressRect.x + progress.progressRect.width) + ((width) ? (parseInt(width, 10)) : progressWidth);
const duration: number = (!progress.enableProgressSegments) ? 2500 : 3500;
animation.animate(<HTMLElement>clipPath, {
duration: duration,
delay: 0,
progress: (args: AnimationOptions): void => {
if (progress.enableRtl && !(progress.cornerRadius === 'Round4px')) {
value = effect(
args.timeStamp, parseInt(x, 10) || progress.progressRect.x + progressWidth,
end, args.duration, true
);
if (!progress.enableProgressSegments) {
linearPath.setAttribute('x', value.toString());
} else {
linearPath.setAttribute('d', progress.getPathLine(value, progressWidth, thickness));
}
} else {
value = effect(args.timeStamp, start, end, args.duration, false);
if (!progress.enableProgressSegments) {
linearPath.setAttribute('x', value.toString());
} else {
linearPath.setAttribute('d', progress.getPathLine(value, progressWidth, thickness));
}
}
},
end: () => {
if (progress.enableRtl && !progress.enableProgressSegments && !(progress.cornerRadius === 'Round4px')) {
linearPath.setAttribute('x', x.toString());
} else if (!progress.enableProgressSegments) {
linearPath.setAttribute('x', start.toString());
}
if (!progress.destroyIndeterminate) {
this.doLinearIndeterminate(element, progressWidth, thickness, progress, clipPath);
}
}
});
}
/** Linear striped */
public doStripedAnimation(element: Element, progress: ProgressBar, value: number): void {
const animation: Animation = new Animation({});
const point: number = 1000 / progress.animation.duration;
animation.animate(<HTMLElement>element, {
duration: progress.animation.duration,
delay: progress.animation.delay,
progress: (): void => {
value += (progress.enableRtl) ? -point : point;
element.setAttribute('gradientTransform', 'translate(' + value + ') rotate(-45)');
},
end: () => {
if (!progress.destroyIndeterminate) {
this.doStripedAnimation(element, progress, value);
}
}
});
}
/** Circular animation */
public doCircularAnimation(
x: number, y: number, radius: number, progressEnd: number, totalEnd: number,
element: Element, progress: ProgressBar, thickness: number, delay: number, startValue?: number,
previousTotal?: number, active?: Element
): void {
const animation: Animation = new Animation({});
const circularPath: HTMLElement = <HTMLElement>element;
let start: number = progress.startAngle;
const pathRadius: number = radius + (thickness / 2);
let end: number = 0;
let opacityValue: number = 0;
const duration: number = (progress.isActive) ? 3000 : progress.animation.duration;
start += (progress.cornerRadius === 'Round' && totalEnd !== completeAngle && totalEnd !== 0) ?
((progress.enableRtl) ? (lineCapRadius / 2) * thickness : -(lineCapRadius / 2) * thickness) : 0;
totalEnd += (progress.cornerRadius === 'Round' && totalEnd !== completeAngle && totalEnd !== 0) ?
(lineCapRadius / 2) * thickness : 0;
progressEnd += (progress.cornerRadius === 'Round' && totalEnd !== completeAngle && totalEnd !== 0) ?
((progress.enableRtl) ? -(lineCapRadius / 2) * thickness : (lineCapRadius / 2) * thickness) : 0;
const startPos: number = (!isNullOrUndefined(startValue)) ? startValue : start;
const endPos: number = (!isNullOrUndefined(startValue)) ? totalEnd - previousTotal : totalEnd;
circularPath.setAttribute('visibility', 'Hidden');
animation.animate(circularPath, {
duration: duration,
delay: delay,
progress: (args: AnimationOptions): void => {
progress.cancelResize = true;
if (args.timeStamp >= args.delay) {
circularPath.setAttribute('visibility', 'visible');
if (progress.isActive) {
end = this.activeAnimate((args.timeStamp / args.duration), startPos, endPos, progress.enableRtl);
opacityValue = effect(args.timeStamp, 0.5, 0.5, args.duration, true);
active.setAttribute('opacity', opacityValue.toString());
circularPath.setAttribute('d', getPathArc(x, y, pathRadius, start, end % 360, progress.enableRtl, true));
} else {
end = effect(args.timeStamp, startPos, endPos, args.duration, progress.enableRtl);
circularPath.setAttribute('d', getPathArc(x, y, pathRadius, start, end % 360, progress.enableRtl, true));
}
}
},
end: () => {
progress.cancelResize = false;
circularPath.setAttribute('visibility', '');
circularPath.setAttribute('d', getPathArc(x, y, pathRadius, start, progressEnd, progress.enableRtl, true));
if (progress.isActive) {
this.doCircularAnimation(
x, y, radius, progressEnd, totalEnd, element, progress, thickness,
delay, startValue, previousTotal, active
);
}
progress.trigger('animationComplete', {
value: progress.value, trackColor: progress.trackColor,
progressColor: progress.progressColor
});
}
});
}
/** Circular indeterminate */
public doCircularIndeterminate(
circularProgress: Element, progress: ProgressBar,
start: number, end: number, x: number, y: number, radius: number, thickness: number, clipPath: Element
): void {
const animation: Animation = new Animation({});
const pathRadius: number = radius + ((!progress.enableProgressSegments) ? (thickness / 2) : 0);
const value: number = (!progress.enableProgressSegments) ? 3 : 2;
animation.animate((<HTMLElement>clipPath), {
progress: (): void => {
(<HTMLElement>circularProgress).style.visibility = 'visible';
start += (progress.enableRtl) ? -value : value;
end += (progress.enableRtl) ? -value : value;
circularProgress.setAttribute(
'd', getPathArc(x, y, pathRadius, start % 360, end % 360, progress.enableRtl, !progress.enableProgressSegments)
);
},
end: () => {
if (!progress.destroyIndeterminate) {
this.doCircularIndeterminate(circularProgress, progress, start, end, x, y, radius, thickness, clipPath);
}
}
});
}
/** To do the label animation for progress bar */
public doLabelAnimation(labelPath: Element, start: number, end: number, progress: ProgressBar, delay: number, textSize?: number): void {
const animation: Animation = new Animation({});
const label: Animation = new Animation({});
let startPos: number;
let endPos: number;
const text: string = labelPath.innerHTML;
let value: number = 0;
let xPos: number = 0;
let valueChanged: number = 0;
const percentage: number = 100;
const labelText: string = progress.labelStyle.text;
const labelPos: string = progress.labelStyle.textAlignment;
const posX: number = parseInt(labelPath.getAttribute('x'), 10);
labelPath.setAttribute('visibility', 'Hidden');
if (progress.type === 'Linear') {
startPos = (progress.enableRtl) ? (progress.progressRect.x + progress.progressRect.width) + (textSize / 2) :
start - (textSize / 2);
startPos = (startPos <= 0) ? 0 : startPos;
endPos = (progress.enableRtl) ? startPos - posX : posX - startPos;
}
animation.animate(<HTMLElement>labelPath, {
duration: progress.animation.duration,
delay: delay,
progress: (args: AnimationOptions): void => {
progress.cancelResize = true;
args.name = "SlideRight";
if (progress.type === 'Linear') {
if (args.timeStamp >= args.delay) {
if (labelText === '') {
labelPath.setAttribute('visibility', 'visible');
value = effect(args.timeStamp, start, end, args.duration, false);
valueChanged = parseInt((((Math.round(value)) / progress.progressRect.width) * percentage).toString(), 10);
labelPath.innerHTML = valueChanged.toString() + '%';
if (labelPos === 'Far' || labelPos === 'Center') {
xPos = effect(args.timeStamp, startPos, endPos, args.duration, progress.enableRtl);
labelPath.setAttribute('x', xPos.toString());
}
}
}
} else if (progress.type === 'Circular') {
if (labelText === '') {
labelPath.setAttribute('visibility', 'visible');
value = effect(args.timeStamp, start, end - start, args.duration, false);
valueChanged = parseInt((((Math.round(value)) / progress.totalAngle) * percentage).toString(), 10);
labelPath.innerHTML = valueChanged.toString() + '%';
}
}
},
end: () => {
progress.cancelResize = false;
if (labelText === '') {
labelPath.innerHTML = text;
labelPath.setAttribute('x', posX.toString());
} else {
label.animate(<HTMLElement>labelPath, {
progress: (args: AnimationOptions): void => {
labelPath.setAttribute('visibility', 'visible');
value = effect(args.timeStamp, 0, 1, args.duration, false);
labelPath.setAttribute('opacity', value.toString());
},
end: () => {
labelPath.setAttribute('opacity', '1');
}
});
}
}
});
}
/** To do the annotation animation for circular progress bar */
public doAnnotationAnimation(circularPath: Element, progress: ProgressBar, previousEnd?: number, previousTotal?: number): void {
const animation: Animation = new Animation({});
let value: number = 0;
const percentage: number = 100;
const isAnnotation: boolean = progress.annotations.length > 0;
let annotatElementChanged: Element;
let firstAnnotatElement: Element;
const start: number = progress.startAngle;
const totalAngle: number = progress.totalAngle;
let totalEnd: number;
let annotateValueChanged: number;
let annotateValue: number;
if (isAnnotation && progress.progressAnnotationModule) {
firstAnnotatElement = document.getElementById(progress.element.id + 'Annotation0').children[0];
if (firstAnnotatElement && firstAnnotatElement.children[0]) {
if (firstAnnotatElement.children[0].tagName === 'SPAN') {
annotatElementChanged = firstAnnotatElement.children[0];
}
}
}
totalEnd = ((progress.argsData.value - progress.minimum) / (progress.maximum - progress.minimum)) * progress.totalAngle;
progress.annotateTotal = totalEnd =
(progress.argsData.value < progress.minimum || progress.argsData.value > progress.maximum) ? 0 : totalEnd;
progress.annotateEnd = start + totalEnd;
annotateValue = ((progress.argsData.value - progress.minimum) / (progress.maximum - progress.minimum)) * percentage;
annotateValue = (progress.argsData.value < progress.minimum || progress.argsData.value > progress.maximum) ? 0 :
Math.round(annotateValue);
const startValue: number = (!isNullOrUndefined(previousEnd)) ? previousEnd : start;
const endValue: number = (!isNullOrUndefined(previousEnd)) ? totalEnd - previousTotal : totalEnd;
if (progress.argsData.value <= progress.minimum || progress.argsData.value > progress.maximum) {
annotatElementChanged.innerHTML = annotateValue + '%';
} else {
animation.animate((<HTMLElement>circularPath), {
duration: progress.animation.duration,
delay: progress.animation.delay,
progress: (args: AnimationOptions): void => {
progress.cancelResize = true;
if (isAnnotation && annotatElementChanged) {
value = effect(args.timeStamp, startValue, endValue, args.duration, false);
annotateValueChanged = parseInt((((Math.round(value) - start) / totalAngle) * percentage).toString(), 10);
annotatElementChanged.innerHTML = annotateValueChanged ? annotateValueChanged.toString() + '%' : '0%';
}
},
end: () => {
progress.cancelResize = false;
annotatElementChanged.innerHTML = annotateValue + '%';
}
});
}
}
private activeAnimate(t: number, start: number, end: number, enableRtl: boolean): number {
const time: number = 1 - Math.pow(1 - t, 3);
const attrValue: number = start + ((!enableRtl) ? (time * end) : -(time * end));
return attrValue;
}
} | the_stack |
import {TestBed, ComponentFixture, inject} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {createGenericTestComponent, isBrowserVisible} from '../test/common';
import {Component} from '@angular/core';
import {NgbAccordionModule, NgbPanelChangeEvent, NgbAccordionConfig, NgbAccordion} from './accordion.module';
import {NgbConfig} from '../ngb-config';
import {NgbConfigAnimation} from '../test/ngb-config-animation';
const createTestComponent = (html: string) =>
createGenericTestComponent(html, TestComponent) as ComponentFixture<TestComponent>;
function getPanels(element: HTMLElement): HTMLDivElement[] {
return <HTMLDivElement[]>Array.from(element.querySelectorAll('.card > .card-header'));
}
function getPanelsContent(element: HTMLElement): HTMLDivElement[] {
return <HTMLDivElement[]>Array.from(element.querySelectorAll('.card > .collapse, .card > .collapsing'));
}
function getPanelsButton(element: HTMLElement): HTMLButtonElement[] {
return <HTMLButtonElement[]>Array.from(element.querySelectorAll('.card > .card-header button'));
}
function getPanelsTitle(element: HTMLElement): string[] {
return getPanelsButton(element).map(button => button.textContent !.trim());
}
function getButton(element: HTMLElement, index: number): HTMLButtonElement {
return <HTMLButtonElement>element.querySelectorAll('button[type="button"]')[index];
}
function expectOpenPanels(nativeEl: HTMLElement, openPanelsDef: boolean[]) {
const noOfOpenPanels = openPanelsDef.reduce((soFar, def) => def ? soFar + 1 : soFar, 0);
const panels = getPanels(nativeEl);
expect(panels.length).toBe(openPanelsDef.length);
const panelsButton = getPanelsButton(nativeEl);
const result = panelsButton.map(titleEl => {
const isAriaExpanded = titleEl.getAttribute('aria-expanded') === 'true';
const isCSSCollapsed = titleEl.classList.contains('collapsed');
return isAriaExpanded === !isCSSCollapsed ? isAriaExpanded : fail('inconsistent state');
});
const panelContents = getPanelsContent(nativeEl);
panelContents.forEach(panelContent => { expect(panelContent.classList.contains('show')).toBeTruthy(); });
expect(panelContents.length).toBe(noOfOpenPanels);
expect(result).toEqual(openPanelsDef);
}
describe('ngb-accordion', () => {
let html = `
<ngb-accordion #acc="ngbAccordion" [closeOthers]="closeOthers" [activeIds]="activeIds"
(panelChange)="changeCallback($event)" (shown)="shownCallback($event)" (hidden)="hiddenCallback($event)" [type]="classType">
<ngb-panel *ngFor="let panel of panels" [id]="panel.id" [disabled]="panel.disabled" [type]="panel.type"
(shown)="panelShownCallback($event)" (hidden)="panelHiddenCallback($event)">
<ng-template ngbPanelTitle>{{panel.title}}</ng-template>
<ng-template ngbPanelContent>{{panel.content}}</ng-template>
</ngb-panel>
</ngb-accordion>
<button *ngFor="let panel of panels" (click)="acc.toggle(panel.id)">Toggle the panel {{ panel.id }}</button>
`;
beforeEach(() => {
TestBed.configureTestingModule({declarations: [TestComponent], imports: [NgbAccordionModule]});
TestBed.overrideComponent(TestComponent, {set: {template: html}});
});
it('should initialize inputs with default values', () => {
const defaultConfig = new NgbAccordionConfig(new NgbConfig());
const accordionCmp = TestBed.createComponent(NgbAccordion).componentInstance;
expect(accordionCmp.type).toBe(defaultConfig.type);
expect(accordionCmp.closeOtherPanels).toBe(defaultConfig.closeOthers);
});
it('should have no open panels', () => {
const fixture = TestBed.createComponent(TestComponent);
const accordionEl = fixture.nativeElement.children[0];
const el = fixture.nativeElement;
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
expect(accordionEl.getAttribute('role')).toBe('tablist');
expect(accordionEl.getAttribute('aria-multiselectable')).toBe('true');
});
it('should have proper css classes', () => {
const fixture = TestBed.createComponent(TestComponent);
const accordion = fixture.debugElement.query(By.directive(NgbAccordion));
expect(accordion.nativeElement).toHaveCssClass('accordion');
});
it('should toggle panels based on "activeIds" values', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
const el = fixture.nativeElement;
// as array
tc.activeIds = ['one', 'two'];
fixture.detectChanges();
expectOpenPanels(el, [true, true, false]);
tc.activeIds = ['two', 'three'];
fixture.detectChanges();
expectOpenPanels(el, [false, true, true]);
tc.activeIds = [];
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
tc.activeIds = ['wrong id', 'one'];
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
// as string
tc.activeIds = 'one';
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
tc.activeIds = 'two, three';
fixture.detectChanges();
expectOpenPanels(el, [false, true, true]);
tc.activeIds = '';
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
tc.activeIds = 'wrong id,one';
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
});
it('should toggle panels independently', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const el = fixture.nativeElement;
getButton(el, 1).click();
fixture.detectChanges();
expectOpenPanels(el, [false, true, false]);
getButton(el, 0).click();
fixture.detectChanges();
expectOpenPanels(el, [true, true, false]);
getButton(el, 1).click();
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
getButton(el, 2).click();
fixture.detectChanges();
expectOpenPanels(el, [true, false, true]);
getButton(el, 0).click();
fixture.detectChanges();
expectOpenPanels(el, [false, false, true]);
getButton(el, 2).click();
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
});
it('should allow only one panel to be active with "closeOthers" flag', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const tc = fixture.componentInstance;
const el = fixture.nativeElement;
tc.closeOthers = true;
fixture.detectChanges();
expect(el.children[0].getAttribute('aria-multiselectable')).toBe('false');
getButton(el, 0).click();
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
getButton(el, 1).click();
fixture.detectChanges();
expectOpenPanels(el, [false, true, false]);
});
it('should update the activeIds after closeOthers is set to true', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
const el = fixture.nativeElement;
tc.activeIds = 'one,two,three';
fixture.detectChanges();
expectOpenPanels(el, [true, true, true]);
tc.closeOthers = true;
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
tc.closeOthers = false;
fixture.detectChanges();
expectOpenPanels(el, [true, false, false]);
});
it('should have the appropriate heading', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
const titles = getPanelsTitle(compiled);
expect(titles.length).not.toBe(0);
titles.forEach((title, idx) => { expect(title).toBe(`Panel ${idx + 1}`); });
});
it('can use a title without template', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel [title]="panels[0].title">
<ng-template ngbPanelContent>{{panels[0].content}}</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
fixture.detectChanges();
const title = getPanelsTitle(fixture.nativeElement)[0];
expect(title).toBe('Panel 1');
});
it('can mix title and template', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel [title]="panels[0].title">
<ng-template ngbPanelContent>{{panels[0].content}}</ng-template>
</ngb-panel>
<ngb-panel>
<ng-template ngbPanelTitle>{{panels[1].title}}</ng-template>
<ng-template ngbPanelContent>{{panels[1].content}}</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
fixture.detectChanges();
const titles = getPanelsTitle(fixture.nativeElement);
titles.forEach((title, idx) => { expect(title).toBe(`Panel ${idx + 1}`); });
});
it('can use header as a template', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel>
<ng-template ngbPanelHeader>
<button ngbPanelToggle>Title 1</button>
</ng-template>
<ng-template ngbPanelContent>Content 1</ng-template>
</ngb-panel>
<ngb-panel>
<ng-template ngbPanelHeader>
<button ngbPanelToggle>Title 2</button>
</ng-template>
<ng-template ngbPanelContent>Content 2</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
const titles = getPanelsTitle(fixture.nativeElement);
titles.forEach((title, idx) => { expect(title).toBe(`Title ${idx + 1}`); });
});
it('should pass context to a header template', () => {
const testHtml = `
<ngb-accordion [activeIds]="activeIds">
<ngb-panel id="one">
<ng-template ngbPanelHeader let-opened="opened">
<button ngbPanelToggle>{{ opened ? 'opened' : 'closed' }}</button>
</ng-template>
<ng-template ngbPanelContent>Content 1</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
let title = getPanelsTitle(fixture.nativeElement)[0];
expectOpenPanels(fixture.nativeElement, [false]);
expect(title).toBe(`closed`);
fixture.componentInstance.activeIds = 'one';
fixture.detectChanges();
title = getPanelsTitle(fixture.nativeElement)[0];
expectOpenPanels(fixture.nativeElement, [true]);
expect(title).toBe(`opened`);
});
it('can should prefer header as a template to other ways of providing a title', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel title="Panel Title 1">
<ng-template ngbPanelHeader>
<button ngbPanelToggle>Header Title 1</button>
</ng-template>
<ng-template ngbPanelContent>Content 1</ng-template>
</ngb-panel>
<ngb-panel>
<ng-template ngbPanelTitle>Panel Title 2</ng-template>
<ng-template ngbPanelHeader>
<button ngbPanelToggle>Header Title 2</button>
</ng-template>
<ng-template ngbPanelContent>Content 2</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
const titles = getPanelsTitle(fixture.nativeElement);
titles.forEach((title, idx) => { expect(title).toBe(`Header Title ${idx + 1}`); });
});
it('should not pick up titles from nested accordions', () => {
const testHtml = `
<ngb-accordion activeIds="open_me">
<ngb-panel title="parent title" id="open_me">
<ng-template ngbPanelContent>
<ngb-accordion>
<ngb-panel>
<ng-template ngbPanelTitle>child title</ng-template>
<ng-template ngbPanelContent>child content</ng-template>
</ngb-panel>
</ngb-accordion>
</ng-template>
</ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
// additional change detection is required to reproduce the problem in the test environment
fixture.detectChanges();
const[parentTitle, childTitle] = getPanelsTitle(fixture.nativeElement);
expect(parentTitle).toContain('parent title');
expect(parentTitle).not.toContain('child title');
expect(childTitle).toContain('child title');
expect(childTitle).not.toContain('parent title');
});
it('should not crash for an empty accordion', () => {
const fixture = createTestComponent('<ngb-accordion></ngb-accordion>');
expect(getPanels(fixture.nativeElement).length).toBe(0);
});
it('should not crash for panels without content', () => {
const fixture =
createTestComponent('<ngb-accordion activeIds="open_me"><ngb-panel id="open_me"></ngb-panel></ngb-accordion>');
const panelsContent = getPanelsContent(fixture.nativeElement);
expect(panelsContent.length).toBe(1);
expect(panelsContent[0].textContent !.trim()).toBe('');
});
it('should have the appropriate content', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
const originalContent = fixture.componentInstance.panels;
fixture.componentInstance.activeIds = 'one,two,three';
fixture.detectChanges();
const contents = getPanelsContent(compiled);
expect(contents.length).not.toBe(0);
contents.forEach((content, idx) => {
expect(content.getAttribute('aria-labelledby')).toBe(`${content.id}-header`);
expect(content.textContent !.trim()).toBe(originalContent[idx].content);
});
});
it('should have the appropriate CSS visibility classes', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
fixture.componentInstance.activeIds = 'one,two,three';
fixture.detectChanges();
const contents = getPanelsContent(compiled);
expect(contents.length).not.toBe(0);
contents.forEach(content => {
expect(content).toHaveCssClass('collapse');
expect(content).toHaveCssClass('show');
});
});
it('should only open one at a time', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
tc.closeOthers = true;
fixture.detectChanges();
const headingLinks = getPanelsButton(fixture.nativeElement);
headingLinks[0].click();
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [true, false, false]);
headingLinks[2].click();
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [false, false, true]);
headingLinks[2].click();
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [false, false, false]);
});
it('should have only one open panel even if binding says otherwise', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
tc.activeIds = ['one', 'two'];
tc.closeOthers = true;
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [true, false, false]);
});
it('should not open disabled panels from click', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
tc.panels[0].disabled = true;
fixture.detectChanges();
const headingLinks = getPanelsButton(fixture.nativeElement);
headingLinks[0].click();
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [false, false, false]);
});
it('should not update activeIds when trying to toggle a disabled panel', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
const el = fixture.nativeElement;
tc.panels[0].disabled = true;
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
const headingLinks = getPanelsButton(fixture.nativeElement);
headingLinks[0].click();
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
tc.panels[0].disabled = false;
fixture.detectChanges();
expectOpenPanels(el, [false, false, false]);
});
it('should open/collapse disabled panels', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
tc.activeIds = ['one'];
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [true, false, false]);
tc.panels[0].disabled = true;
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [false, false, false]);
tc.panels[0].disabled = false;
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [true, false, false]);
});
it('should have correct disabled state', () => {
const fixture = TestBed.createComponent(TestComponent);
const tc = fixture.componentInstance;
tc.activeIds = ['one'];
fixture.detectChanges();
const headingLinks = getPanelsButton(fixture.nativeElement);
expectOpenPanels(fixture.nativeElement, [true, false, false]);
expect(headingLinks[0].disabled).toBeFalsy();
tc.panels[0].disabled = true;
fixture.detectChanges();
expectOpenPanels(fixture.nativeElement, [false, false, false]);
expect(headingLinks[0].disabled).toBeTruthy();
});
it('should add custom class to the card element', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel></ngb-panel>
<ngb-panel cardClass="custom-class"></ngb-panel>
<ngb-panel cardClass="custom-class custom-class-2"></ngb-panel>
<ngb-panel [cardClass]="null"></ngb-panel>
</ngb-accordion>
`;
const fixture = createTestComponent(testHtml);
const cards = <HTMLDivElement[]>Array.from(fixture.nativeElement.querySelectorAll('.card'));
fixture.detectChanges();
expect(cards[0].classList.length).toBe(1);
expect(cards[0]).toHaveCssClass('card');
expect(cards[1].classList.length).toBe(2);
expect(cards[1]).toHaveCssClass('card');
expect(cards[1]).toHaveCssClass('custom-class');
expect(cards[2].classList.length).toBe(3);
expect(cards[2]).toHaveCssClass('card');
expect(cards[2]).toHaveCssClass('custom-class');
expect(cards[2]).toHaveCssClass('custom-class-2');
expect(cards[3].classList.length).toBe(1);
expect(cards[3]).toHaveCssClass('card');
});
it('should remove collapsed panels content from DOM', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(getPanelsContent(fixture.nativeElement).length).toBe(0);
getButton(fixture.nativeElement, 0).click();
fixture.detectChanges();
expect(getPanelsContent(fixture.nativeElement).length).toBe(1);
});
it('should not remove collapsed panels content from DOM with `destroyOnHide` flag', () => {
const testHtml = `
<ngb-accordion #acc="ngbAccordion" [closeOthers]="true" [destroyOnHide]="false">
<ngb-panel *ngFor="let panel of panels" [id]="panel.id">
<ng-template ngbPanelTitle>{{panel.title}}</ng-template>
<ng-template ngbPanelContent>{{panel.content}}</ng-template>
</ngb-panel>
</ngb-accordion>
<button *ngFor="let panel of panels" (click)="acc.toggle(panel.id)">Toggle the panel {{ panel.id }}</button>
`;
const fixture = createTestComponent(testHtml);
fixture.detectChanges();
getButton(fixture.nativeElement, 1).click();
fixture.detectChanges();
let panelContents = getPanelsContent(fixture.nativeElement);
expect(panelContents[1]).toHaveCssClass('show');
expect(panelContents.length).toBe(3);
});
it('should emit panel events when toggling panels', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
spyOn(fixture.componentInstance, 'changeCallback');
spyOn(fixture.componentInstance, 'shownCallback');
spyOn(fixture.componentInstance, 'hiddenCallback');
spyOn(fixture.componentInstance, 'panelShownCallback');
spyOn(fixture.componentInstance, 'panelHiddenCallback');
// Select the first tab -> change event
getButton(fixture.nativeElement, 0).click();
fixture.detectChanges();
expect(fixture.componentInstance.changeCallback)
.toHaveBeenCalledWith(jasmine.objectContaining({panelId: 'one', nextState: true}));
expect(fixture.componentInstance.shownCallback).toHaveBeenCalledWith('one');
expect(fixture.componentInstance.panelShownCallback).toHaveBeenCalledWith(undefined);
// Select the first tab again -> change event
getButton(fixture.nativeElement, 0).click();
fixture.detectChanges();
expect(fixture.componentInstance.changeCallback)
.toHaveBeenCalledWith(jasmine.objectContaining({panelId: 'one', nextState: false}));
expect(fixture.componentInstance.hiddenCallback).toHaveBeenCalledWith('one');
expect(fixture.componentInstance.panelHiddenCallback).toHaveBeenCalledWith(undefined);
});
it('should cancel panel toggle when preventDefault() is called', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
let changeEvent: NgbPanelChangeEvent | null = null;
fixture.componentInstance.changeCallback = event => {
changeEvent = event;
event.preventDefault();
};
// Select the first tab -> toggle will be canceled
getButton(fixture.nativeElement, 0).click();
fixture.detectChanges();
expect(changeEvent !).toEqual(jasmine.objectContaining({panelId: 'one', nextState: true}));
expectOpenPanels(fixture.nativeElement, [false, false, false]);
});
it('should have specified type of accordion ', () => {
const testHtml = `
<ngb-accordion #acc="ngbAccordion" [closeOthers]="closeOthers" [type]="classType">
<ngb-panel *ngFor="let panel of panels" [id]="panel.id" [disabled]="panel.disabled">
<ng-template ngbPanelTitle>{{panel.title}}</ng-template>
<ng-template ngbPanelContent>{{panel.content}}</ng-template>
</ngb-panel>
</ngb-accordion>
<button *ngFor="let panel of panels" (click)="acc.toggle(panel.id)">Toggle the panel {{ panel.id }}</button>
`;
const fixture = createTestComponent(testHtml);
fixture.componentInstance.classType = 'warning';
fixture.detectChanges();
let el = fixture.nativeElement.querySelectorAll('.card-header');
expect(el[0]).toHaveCssClass('bg-warning');
expect(el[1]).toHaveCssClass('bg-warning');
expect(el[2]).toHaveCssClass('bg-warning');
});
it('should override the type in accordion with type in panel', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
fixture.componentInstance.classType = 'warning';
const tc = fixture.componentInstance;
tc.panels[0].type = 'success';
tc.panels[1].type = 'danger';
fixture.detectChanges();
let el = fixture.nativeElement.querySelectorAll('.card-header');
expect(el[0]).toHaveCssClass('bg-success');
expect(el[1]).toHaveCssClass('bg-danger');
expect(el[2]).toHaveCssClass('bg-warning');
});
it('should have the proper roles', () => {
const fixture = TestBed.createComponent(TestComponent);
fixture.componentInstance.activeIds = 'one,two,three';
fixture.detectChanges();
const headers = getPanels(fixture.nativeElement);
headers.forEach(header => expect(header.getAttribute('role')).toBe('tab'));
const contents = getPanelsContent(fixture.nativeElement);
contents.forEach(content => expect(content.getAttribute('role')).toBe('tabpanel'));
});
describe('Custom config', () => {
let config: NgbAccordionConfig;
beforeEach(() => { TestBed.configureTestingModule({imports: [NgbAccordionModule]}); });
beforeEach(inject([NgbAccordionConfig], (c: NgbAccordionConfig) => {
config = c;
config.closeOthers = true;
config.type = 'success';
}));
it('should initialize inputs with provided config', () => {
const fixture = TestBed.createComponent(NgbAccordion);
fixture.detectChanges();
let accordion = fixture.componentInstance;
expect(accordion.closeOtherPanels).toBe(config.closeOthers);
expect(accordion.type).toBe(config.type);
});
});
describe('Custom config as provider', () => {
let config = new NgbAccordionConfig(new NgbConfig());
config.closeOthers = true;
config.type = 'success';
beforeEach(() => {
TestBed.configureTestingModule(
{imports: [NgbAccordionModule], providers: [{provide: NgbAccordionConfig, useValue: config}]});
});
it('should initialize inputs with provided config as provider', () => {
const fixture = TestBed.createComponent(NgbAccordion);
fixture.detectChanges();
let accordion = fixture.componentInstance;
expect(accordion.closeOtherPanels).toBe(config.closeOthers);
expect(accordion.type).toBe(config.type);
});
});
describe('imperative API', () => {
function createTestImperativeAccordion(testHtml: string) {
const fixture = createTestComponent(testHtml);
const accordion = fixture.debugElement.query(By.directive(NgbAccordion)).componentInstance;
const nativeElement = fixture.nativeElement;
return {fixture, accordion, nativeElement};
}
it('should check if a panel with a given id is expanded', () => {
const testHtml = `
<ngb-accordion activeIds="first">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [true, false]);
expect(accordion.isExpanded('first')).toBe(true);
expect(accordion.isExpanded('second')).toBe(false);
});
it('should expanded and collapse individual panels', () => {
const testHtml = `
<ngb-accordion>
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false, false]);
accordion.expand('first');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
accordion.expand('second');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, true]);
accordion.collapse('second');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
});
it('should not expand / collapse if already expanded / collapsed', () => {
const testHtml = `
<ngb-accordion activeIds="first" (panelChange)="changeCallback()">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [true, false]);
spyOn(fixture.componentInstance, 'changeCallback');
accordion.expand('first');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
accordion.collapse('second');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
expect(fixture.componentInstance.changeCallback).not.toHaveBeenCalled();
});
it('should not expand disabled panels', () => {
const testHtml = `
<ngb-accordion (panelChange)="changeCallback()">
<ngb-panel id="first" [disabled]="true"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false]);
spyOn(fixture.componentInstance, 'changeCallback');
accordion.expand('first');
fixture.detectChanges();
expectOpenPanels(nativeElement, [false]);
expect(fixture.componentInstance.changeCallback).not.toHaveBeenCalled();
});
it('should not expand / collapse when preventDefault called on the panelChange event', () => {
const testHtml = `
<ngb-accordion activeIds="first" (panelChange)="preventDefaultCallback($event)">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [true, false]);
accordion.collapse('first');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
accordion.expand('second');
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
});
it('should expandAll when closeOthers is false', () => {
const testHtml = `
<ngb-accordion [closeOthers]="false">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false, false]);
accordion.expandAll();
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, true]);
});
it('should expand first panel when closeOthers is true and none of panels is expanded', () => {
const testHtml = `
<ngb-accordion [closeOthers]="true">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false, false]);
accordion.expandAll();
fixture.detectChanges();
expectOpenPanels(nativeElement, [true, false]);
});
it('should do nothing if closeOthers is true and one panel is expanded', () => {
const testHtml = `
<ngb-accordion [closeOthers]="true" activeIds="second">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false, true]);
accordion.expandAll();
fixture.detectChanges();
expectOpenPanels(nativeElement, [false, true]);
});
it('should collapse all panels', () => {
const testHtml = `
<ngb-accordion activeIds="second">
<ngb-panel id="first"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>`;
const {accordion, nativeElement, fixture} = createTestImperativeAccordion(testHtml);
expectOpenPanels(nativeElement, [false, true]);
accordion.collapseAll();
fixture.detectChanges();
expectOpenPanels(nativeElement, [false, false]);
});
});
});
if (isBrowserVisible('ngb-accordion animations')) {
describe('ngb-accordion animations', () => {
@Component({
template: `
<ngb-accordion activeIds="first" (panelChange)="onPanelChange($event)" (shown)="onShown($event)" (hidden)="onHidden($event)">
<ngb-panel id="first" (shown)="onPanelShown()" (hidden)="onPanelHidden()"></ngb-panel>
<ngb-panel id="second"></ngb-panel>
</ngb-accordion>
`,
host: {'[class.ngb-reduce-motion]': 'reduceMotion'}
})
class TestAnimationComponent {
reduceMotion = true;
onShown = (panelId) => panelId;
onHidden = (panelId) => panelId;
onPanelChange = () => {};
onPanelShown = () => {};
onPanelHidden = () => {};
}
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestAnimationComponent],
imports: [NgbAccordionModule],
providers: [{provide: NgbConfig, useClass: NgbConfigAnimation}]
});
});
it(`should run collapsing transition (force-reduced-motion = false)`, (done) => {
const fixture = TestBed.createComponent(TestAnimationComponent);
fixture.componentInstance.reduceMotion = false;
fixture.detectChanges();
const buttonEl = getPanelsButton(fixture.nativeElement)[0];
let panelEl = getPanelsContent(fixture.nativeElement)[0];
const onShownSpy = spyOn(fixture.componentInstance, 'onShown');
const onHiddenSpy = spyOn(fixture.componentInstance, 'onHidden');
const onPanelChangeSpy = spyOn(fixture.componentInstance, 'onPanelChange');
const onPanelShownSpy = spyOn(fixture.componentInstance, 'onPanelShown');
const onPanelHiddenSpy = spyOn(fixture.componentInstance, 'onPanelHidden');
onHiddenSpy.and.callFake((panelId) => {
expect(onPanelHiddenSpy).toHaveBeenCalled();
expect(panelId).toBe('first');
expect(panelEl).toHaveClass('collapse');
expect(panelEl).not.toHaveClass('collapsing');
expect(panelEl).not.toHaveClass('show');
// Expanding
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(2);
});
onShownSpy.and.callFake((panelId) => {
expect(onPanelShownSpy).toHaveBeenCalled();
expect(panelId).toBe('first');
// The previous one has been destroyed, need to get the new element
panelEl = getPanelsContent(fixture.nativeElement)[0];
expect(panelEl).toHaveClass('collapse');
expect(panelEl).not.toHaveClass('collapsing');
expect(panelEl).toHaveClass('show');
done();
});
expect(panelEl).toHaveClass('collapse');
expect(panelEl).toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
// Collapsing
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(1);
expect(panelEl).not.toHaveClass('collapse');
expect(panelEl).not.toHaveClass('show');
expect(panelEl).toHaveClass('collapsing');
});
it(`should run collapsing transition (force-reduced-motion = true)`, () => {
const fixture = TestBed.createComponent(TestAnimationComponent);
fixture.componentInstance.reduceMotion = true;
fixture.detectChanges();
const buttonEl = getPanelsButton(fixture.nativeElement)[0];
let panelEl = getPanelsContent(fixture.nativeElement)[0];
const onShownSpy = spyOn(fixture.componentInstance, 'onShown');
const onHiddenSpy = spyOn(fixture.componentInstance, 'onHidden');
const onPanelChangeSpy = spyOn(fixture.componentInstance, 'onPanelChange');
const onPanelShownSpy = spyOn(fixture.componentInstance, 'onPanelShown');
const onPanelHiddenSpy = spyOn(fixture.componentInstance, 'onPanelHidden');
expect(panelEl).toHaveClass('collapse');
expect(panelEl).toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
// Collapsing
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(1);
expect(onHiddenSpy).toHaveBeenCalledWith('first');
expect(onPanelHiddenSpy).toHaveBeenCalled();
expect(panelEl).toHaveClass('collapse');
expect(panelEl).not.toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
// Expanding
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(2);
expect(onShownSpy).toHaveBeenCalledWith('first');
expect(onPanelShownSpy).toHaveBeenCalled();
// The previous one has been destroyed, need to get the new element
panelEl = getPanelsContent(fixture.nativeElement)[0];
expect(panelEl).toHaveClass('collapse');
expect(panelEl).toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
});
it(`should run revert collapsing transition (force-reduced-motion = false)`, (done) => {
const fixture = TestBed.createComponent(TestAnimationComponent);
fixture.componentInstance.reduceMotion = false;
fixture.detectChanges();
const buttonEl = getPanelsButton(fixture.nativeElement)[0];
let panelEl = getPanelsContent(fixture.nativeElement)[0];
const onPanelChangeSpy = spyOn(fixture.componentInstance, 'onPanelChange');
const onHiddenSpy = spyOn(fixture.componentInstance, 'onHidden');
const onShownSpy = spyOn(fixture.componentInstance, 'onShown');
const onPanelShownSpy = spyOn(fixture.componentInstance, 'onPanelShown');
const onPanelHiddenSpy = spyOn(fixture.componentInstance, 'onPanelHidden');
onShownSpy.and.callFake((panelId) => {
expect(onHiddenSpy).not.toHaveBeenCalled();
expect(onPanelHiddenSpy).not.toHaveBeenCalled();
expect(onPanelShownSpy).toHaveBeenCalled();
expect(panelId).toBe('first');
// The previous one has been destroyed, need to get the new element
panelEl = getPanelsContent(fixture.nativeElement)[0];
expect(panelEl).toHaveClass('collapse');
expect(panelEl).toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
done();
});
expect(panelEl).toHaveClass('collapse');
expect(panelEl).toHaveClass('show');
expect(panelEl).not.toHaveClass('collapsing');
// Collapsing
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(1);
expect(panelEl).not.toHaveClass('collapse');
expect(panelEl).not.toHaveClass('show');
expect(panelEl).toHaveClass('collapsing');
// Expanding
buttonEl.click();
fixture.detectChanges();
expect(onPanelChangeSpy).toHaveBeenCalledTimes(2);
panelEl = getPanelsContent(fixture.nativeElement)[0];
expect(panelEl).not.toHaveClass('collapse');
expect(panelEl).not.toHaveClass('show');
expect(panelEl).toHaveClass('collapsing');
});
});
}
@Component({selector: 'test-cmp', template: ''})
class TestComponent {
activeIds: string | string[] = [];
classType;
closeOthers = false;
panels = [
{id: 'one', disabled: false, title: 'Panel 1', content: 'foo', type: ''},
{id: 'two', disabled: false, title: 'Panel 2', content: 'bar', type: ''},
{id: 'three', disabled: false, title: 'Panel 3', content: 'baz', type: ''}
];
changeCallback = (event: NgbPanelChangeEvent) => {};
shownCallback = (panelId: string) => {};
hiddenCallback = (panelId: string) => {};
panelShownCallback = (panelId?: string) => {};
panelHiddenCallback = (panelId?: string) => {};
preventDefaultCallback = (event: NgbPanelChangeEvent) => { event.preventDefault(); };
} | the_stack |
import "@azure/core-paging";
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Keys } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { KeyVaultManagementClientContext } from "../keyVaultManagementClientContext";
import {
Key,
KeysListNextOptionalParams,
KeysListOptionalParams,
KeysListVersionsNextOptionalParams,
KeysListVersionsOptionalParams,
KeyCreateParameters,
KeysCreateIfNotExistOptionalParams,
KeysCreateIfNotExistResponse,
KeysGetOptionalParams,
KeysGetResponse,
KeysListResponse,
KeysGetVersionOptionalParams,
KeysGetVersionResponse,
KeysListVersionsResponse,
KeysListNextResponse,
KeysListVersionsNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class representing a Keys. */
export class KeysImpl implements Keys {
private readonly client: KeyVaultManagementClientContext;
/**
* Initialize a new instance of the class Keys class.
* @param client Reference to the service client
*/
constructor(client: KeyVaultManagementClientContext) {
this.client = client;
}
/**
* Lists the keys in the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the keys to be retrieved.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
vaultName: string,
options?: KeysListOptionalParams
): PagedAsyncIterableIterator<Key> {
const iter = this.listPagingAll(resourceGroupName, vaultName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, vaultName, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
vaultName: string,
options?: KeysListOptionalParams
): AsyncIterableIterator<Key[]> {
let result = await this._list(resourceGroupName, vaultName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
vaultName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
vaultName: string,
options?: KeysListOptionalParams
): AsyncIterableIterator<Key> {
for await (const page of this.listPagingPage(
resourceGroupName,
vaultName,
options
)) {
yield* page;
}
}
/**
* Lists the versions of the specified key in the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the key versions to be retrieved.
* @param keyName The name of the key versions to be retrieved.
* @param options The options parameters.
*/
public listVersions(
resourceGroupName: string,
vaultName: string,
keyName: string,
options?: KeysListVersionsOptionalParams
): PagedAsyncIterableIterator<Key> {
const iter = this.listVersionsPagingAll(
resourceGroupName,
vaultName,
keyName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listVersionsPagingPage(
resourceGroupName,
vaultName,
keyName,
options
);
}
};
}
private async *listVersionsPagingPage(
resourceGroupName: string,
vaultName: string,
keyName: string,
options?: KeysListVersionsOptionalParams
): AsyncIterableIterator<Key[]> {
let result = await this._listVersions(
resourceGroupName,
vaultName,
keyName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listVersionsNext(
resourceGroupName,
vaultName,
keyName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listVersionsPagingAll(
resourceGroupName: string,
vaultName: string,
keyName: string,
options?: KeysListVersionsOptionalParams
): AsyncIterableIterator<Key> {
for await (const page of this.listVersionsPagingPage(
resourceGroupName,
vaultName,
keyName,
options
)) {
yield* page;
}
}
/**
* Creates the first version of a new key if it does not exist. If it already exists, then the existing
* key is returned without any write operations being performed. This API does not create subsequent
* versions, and does not update existing keys.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the key vault which contains the key to be created.
* @param keyName The name of the key to be created.
* @param parameters The parameters used to create the specified key.
* @param options The options parameters.
*/
createIfNotExist(
resourceGroupName: string,
vaultName: string,
keyName: string,
parameters: KeyCreateParameters,
options?: KeysCreateIfNotExistOptionalParams
): Promise<KeysCreateIfNotExistResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, keyName, parameters, options },
createIfNotExistOperationSpec
);
}
/**
* Gets the current version of the specified key from the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the key to be retrieved.
* @param keyName The name of the key to be retrieved.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
vaultName: string,
keyName: string,
options?: KeysGetOptionalParams
): Promise<KeysGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, keyName, options },
getOperationSpec
);
}
/**
* Lists the keys in the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the keys to be retrieved.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
vaultName: string,
options?: KeysListOptionalParams
): Promise<KeysListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, options },
listOperationSpec
);
}
/**
* Gets the specified version of the specified key in the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the key version to be retrieved.
* @param keyName The name of the key version to be retrieved.
* @param keyVersion The version of the key to be retrieved.
* @param options The options parameters.
*/
getVersion(
resourceGroupName: string,
vaultName: string,
keyName: string,
keyVersion: string,
options?: KeysGetVersionOptionalParams
): Promise<KeysGetVersionResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, keyName, keyVersion, options },
getVersionOperationSpec
);
}
/**
* Lists the versions of the specified key in the specified key vault.
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the key versions to be retrieved.
* @param keyName The name of the key versions to be retrieved.
* @param options The options parameters.
*/
private _listVersions(
resourceGroupName: string,
vaultName: string,
keyName: string,
options?: KeysListVersionsOptionalParams
): Promise<KeysListVersionsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, keyName, options },
listVersionsOperationSpec
);
}
/**
* ListNext
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the keys to be retrieved.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
vaultName: string,
nextLink: string,
options?: KeysListNextOptionalParams
): Promise<KeysListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, nextLink, options },
listNextOperationSpec
);
}
/**
* ListVersionsNext
* @param resourceGroupName The name of the resource group which contains the specified key vault.
* @param vaultName The name of the vault which contains the key versions to be retrieved.
* @param keyName The name of the key versions to be retrieved.
* @param nextLink The nextLink from the previous successful call to the ListVersions method.
* @param options The options parameters.
*/
private _listVersionsNext(
resourceGroupName: string,
vaultName: string,
keyName: string,
nextLink: string,
options?: KeysListVersionsNextOptionalParams
): Promise<KeysListVersionsNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vaultName, keyName, nextLink, options },
listVersionsNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createIfNotExistOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Key
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.keyName
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Key
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.keyName
],
headerParameters: [Parameters.accept],
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.KeyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName
],
headerParameters: [Parameters.accept],
serializer
};
const getVersionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions/{keyVersion}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Key
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.keyName,
Parameters.keyVersion
],
headerParameters: [Parameters.accept],
serializer
};
const listVersionsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}/versions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.KeyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.keyName
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.KeyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listVersionsNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.KeyListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.vaultName,
Parameters.keyName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import {
ForceDictationPropertyName,
OutputFormatPropertyName,
ServicePropertiesPropertyName
} from "../common.speech/Exports";
import { IStringDictionary } from "../common/Exports";
import { Contracts } from "./Contracts";
import {
OutputFormat,
ProfanityOption,
PropertyCollection,
PropertyId,
ServicePropertyChannel,
SpeechConfig, SpeechSynthesisOutputFormat,
} from "./Exports";
/**
* Speech translation configuration.
* @class SpeechTranslationConfig
*/
export abstract class SpeechTranslationConfig extends SpeechConfig {
/**
* Creates an instance of recognizer config.
*/
protected constructor() {
super();
}
/**
* Static instance of SpeechTranslationConfig returned by passing a subscription key and service region.
* @member SpeechTranslationConfig.fromSubscription
* @function
* @public
* @param {string} subscriptionKey - The subscription key.
* @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
* @returns {SpeechTranslationConfig} The speech translation config.
*/
public static fromSubscription(subscriptionKey: string, region: string): SpeechTranslationConfig {
Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
Contracts.throwIfNullOrWhitespace(region, "region");
const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();
ret.properties.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);
ret.properties.setProperty(PropertyId.SpeechServiceConnection_Region, region);
return ret;
}
/**
* Static instance of SpeechTranslationConfig returned by passing authorization token and service region.
* Note: The caller needs to ensure that the authorization token is valid. Before the authorization token
* expires, the caller needs to refresh it by setting the property authorizationToken with a new
* valid token. Otherwise, all the recognizers created by this SpeechTranslationConfig instance
* will encounter errors during recognition.
* As configuration values are copied when creating a new recognizer, the new token value will not apply
* to recognizers that have already been created.
* For recognizers that have been created before, you need to set authorization token of the corresponding recognizer
* to refresh the token. Otherwise, the recognizers will encounter errors during recognition.
* @member SpeechTranslationConfig.fromAuthorizationToken
* @function
* @public
* @param {string} authorizationToken - The authorization token.
* @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
* @returns {SpeechTranslationConfig} The speech translation config.
*/
public static fromAuthorizationToken(authorizationToken: string, region: string): SpeechTranslationConfig {
Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
Contracts.throwIfNullOrWhitespace(region, "region");
const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();
ret.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
ret.properties.setProperty(PropertyId.SpeechServiceConnection_Region, region);
return ret;
}
/**
* Creates an instance of the speech config with specified host and subscription key.
* This method is intended only for users who use a non-default service host. Standard resource path will be assumed.
* For services with a non-standard resource path or no path at all, use fromEndpoint instead.
* Note: Query parameters are not allowed in the host URI and must be set by other APIs.
* Note: To use an authorization token with fromHost, use fromHost(URL),
* and then set the AuthorizationToken property on the created SpeechConfig instance.
* Note: Added in version 1.9.0.
* @member SpeechConfig.fromHost
* @function
* @public
* @param {URL} host - The service endpoint to connect to. Format is "protocol://host:port" where ":port" is optional.
* @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.
* @returns {SpeechConfig} A speech factory instance.
*/
public static fromHost(hostName: URL, subscriptionKey?: string): SpeechConfig {
Contracts.throwIfNull(hostName, "hostName");
const speechImpl: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();
speechImpl.setProperty(PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port));
if (undefined !== subscriptionKey) {
speechImpl.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);
}
return speechImpl;
}
/**
* Creates an instance of the speech translation config with specified endpoint and subscription key.
* This method is intended only for users who use a non-standard service endpoint or paramters.
* Note: The query properties specified in the endpoint URL are not changed, even if they are
* set by any other APIs. For example, if language is defined in the uri as query parameter
* "language=de-DE", and also set by the speechRecognitionLanguage property, the language
* setting in uri takes precedence, and the effective language is "de-DE".
* Only the properties that are not specified in the endpoint URL can be set by other APIs.
* Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the
* fromEndpoint method, and then set authorizationToken="token" on the created SpeechConfig instance to
* use the authorization token.
* @member SpeechTranslationConfig.fromEndpoint
* @function
* @public
* @param {URL} endpoint - The service endpoint to connect to.
* @param {string} subscriptionKey - The subscription key.
* @returns {SpeechTranslationConfig} A speech config instance.
*/
public static fromEndpoint(endpoint: URL, subscriptionKey: string): SpeechTranslationConfig {
Contracts.throwIfNull(endpoint, "endpoint");
Contracts.throwIfNull(subscriptionKey, "subscriptionKey");
const ret: SpeechTranslationConfigImpl = new SpeechTranslationConfigImpl();
ret.properties.setProperty(PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);
ret.properties.setProperty(PropertyId.SpeechServiceConnection_Key, subscriptionKey);
return ret;
}
/**
* Gets/Sets the authorization token.
* Note: The caller needs to ensure that the authorization token is valid. Before the authorization token
* expires, the caller needs to refresh it by calling this setter with a new valid token.
* @member SpeechTranslationConfig.prototype.authorizationToken
* @function
* @public
* @param {string} value - The authorization token.
*/
public abstract set authorizationToken(value: string);
/**
* Gets/Sets the speech recognition language.
* @member SpeechTranslationConfig.prototype.speechRecognitionLanguage
* @function
* @public
* @param {string} value - The authorization token.
*/
public abstract set speechRecognitionLanguage(value: string);
/**
* Add a (text) target language to translate into.
* @member SpeechTranslationConfig.prototype.addTargetLanguage
* @function
* @public
* @param {string} value - The language such as de-DE
*/
public abstract addTargetLanguage(value: string): void;
/**
* Gets the (text) target language to translate into.
* @member SpeechTranslationConfig.prototype.targetLanguages
* @function
* @public
* @param {string} value - The language such as de-DE
*/
public abstract get targetLanguages(): string[];
/**
* Gets the selected voice name.
* @member SpeechTranslationConfig.prototype.voiceName
* @function
* @public
* @returns {string} The voice name.
*/
public abstract get voiceName(): string;
/**
* Gets/Sets voice of the translated language, enable voice synthesis output.
* @member SpeechTranslationConfig.prototype.voiceName
* @function
* @public
* @param {string} value - The name of the voice.
*/
public abstract set voiceName(value: string);
/**
* Sets a named property as value
* @member SpeechTranslationConfig.prototype.setProperty
* @function
* @public
* @param {string} name - The name of the property.
* @param {string} value - The value.
*/
public abstract setProperty(name: string, value: string): void;
/**
* Dispose of associated resources.
* @member SpeechTranslationConfig.prototype.close
* @function
* @public
*/
public abstract close(): void;
}
/**
* @private
* @class SpeechTranslationConfigImpl
*/
// tslint:disable-next-line:max-classes-per-file
export class SpeechTranslationConfigImpl extends SpeechTranslationConfig {
private privSpeechProperties: PropertyCollection;
public constructor() {
super();
this.privSpeechProperties = new PropertyCollection();
this.outputFormat = OutputFormat.Simple;
}
/**
* Gets/Sets the authorization token.
* If this is set, subscription key is ignored.
* User needs to make sure the provided authorization token is valid and not expired.
* @member SpeechTranslationConfigImpl.prototype.authorizationToken
* @function
* @public
* @param {string} value - The authorization token.
*/
public set authorizationToken(value: string) {
Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceAuthorization_Token, value);
}
/**
* Sets the speech recognition language.
* @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
* @param {string} value - The authorization token.
*/
public set speechRecognitionLanguage(value: string) {
Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_RecoLanguage, value);
}
/**
* Gets the speech recognition language.
* @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
* @return {string} The speechRecognitionLanguage.
*/
public get speechRecognitionLanguage(): string {
return this.privSpeechProperties.getProperty(PropertyId[PropertyId.SpeechServiceConnection_RecoLanguage]);
}
/**
* @member SpeechTranslationConfigImpl.prototype.subscriptionKey
* @function
* @public
*/
public get subscriptionKey(): string {
return this.privSpeechProperties.getProperty(PropertyId[PropertyId.SpeechServiceConnection_Key]);
}
/**
* Gets the output format
* @member SpeechTranslationConfigImpl.prototype.outputFormat
* @function
* @public
*/
public get outputFormat(): OutputFormat {
return (OutputFormat as any)[this.privSpeechProperties.getProperty(OutputFormatPropertyName, undefined)];
}
/**
* Gets/Sets the output format
* @member SpeechTranslationConfigImpl.prototype.outputFormat
* @function
* @public
*/
public set outputFormat(value: OutputFormat) {
this.privSpeechProperties.setProperty(OutputFormatPropertyName, OutputFormat[value]);
}
/**
* Gets the endpoint id.
* @member SpeechTranslationConfigImpl.prototype.endpointId
* @function
* @public
*/
public get endpointId(): string {
return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_EndpointId);
}
/**
* Gets/Sets the endpoint id.
* @member SpeechTranslationConfigImpl.prototype.endpointId
* @function
* @public
*/
public set endpointId(value: string) {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_EndpointId, value);
}
/**
* Add a (text) target language to translate into.
* @member SpeechTranslationConfigImpl.prototype.addTargetLanguage
* @function
* @public
* @param {string} value - The language such as de-DE
*/
public addTargetLanguage(value: string): void {
Contracts.throwIfNullOrWhitespace(value, "value");
const languages: string[] = this.targetLanguages;
languages.push(value);
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
}
/**
* Gets the (text) target language to translate into.
* @member SpeechTranslationConfigImpl.prototype.targetLanguages
* @function
* @public
* @param {string} value - The language such as de-DE
*/
public get targetLanguages(): string[] {
if (this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
} else {
return [];
}
}
/**
* Gets the voice name.
* @member SpeechTranslationConfigImpl.prototype.voiceName
* @function
* @public
*/
public get voiceName(): string {
return this.getProperty(PropertyId[PropertyId.SpeechServiceConnection_TranslationVoice]);
}
/**
* Gets/Sets the voice of the translated language, enable voice synthesis output.
* @member SpeechTranslationConfigImpl.prototype.voiceName
* @function
* @public
* @param {string} value - The name of the voice.
*/
public set voiceName(value: string) {
Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_TranslationVoice, value);
}
/**
* Provides the region.
* @member SpeechTranslationConfigImpl.prototype.region
* @function
* @public
* @returns {string} The region.
*/
public get region(): string {
return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_Region);
}
public setProxy(proxyHostName: string, proxyPort: number): void;
public setProxy(proxyHostName: string, proxyPort: number, proxyUserName: string, proxyPassword: string): void;
public setProxy(proxyHostName: any, proxyPort: any, proxyUserName?: any, proxyPassword?: any): void {
this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);
this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);
this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);
this.setProperty(PropertyId[PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);
}
/**
* Gets an arbitrary property value.
* @member SpeechTranslationConfigImpl.prototype.getProperty
* @function
* @public
* @param {string} name - The name of the property.
* @param {string} def - The default value of the property in case it is not set.
* @returns {string} The value of the property.
*/
public getProperty(name: string, def?: string): string {
return this.privSpeechProperties.getProperty(name, def);
}
/**
* Gets/Sets an arbitrary property value.
* @member SpeechTranslationConfigImpl.prototype.setProperty
* @function
* @public
* @param {string} name - The name of the property.
* @param {string} value - The value of the property.
*/
public setProperty(name: string | PropertyId, value: string): void {
this.privSpeechProperties.setProperty(name, value);
}
/**
* Provides access to custom properties.
* @member SpeechTranslationConfigImpl.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The properties.
*/
public get properties(): PropertyCollection {
return this.privSpeechProperties;
}
/**
* Dispose of associated resources.
* @member SpeechTranslationConfigImpl.prototype.close
* @function
* @public
*/
public close(): void {
return;
}
public setServiceProperty(name: string, value: string, channel: ServicePropertyChannel): void {
const currentProperties: IStringDictionary<string> = JSON.parse(this.privSpeechProperties.getProperty(ServicePropertiesPropertyName, "{}"));
currentProperties[name] = value;
this.privSpeechProperties.setProperty(ServicePropertiesPropertyName, JSON.stringify(currentProperties));
}
public setProfanity(profanity: ProfanityOption): void {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceResponse_ProfanityOption, ProfanityOption[profanity]);
}
public enableAudioLogging(): void {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_EnableAudioLogging, "true");
}
public requestWordLevelTimestamps(): void {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true");
}
public enableDictation(): void {
this.privSpeechProperties.setProperty(ForceDictationPropertyName, "true");
}
public get speechSynthesisLanguage(): string {
return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthLanguage);
}
public set speechSynthesisLanguage(language: string) {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthLanguage, language);
}
public get speechSynthesisVoiceName(): string {
return this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthVoice);
}
public set speechSynthesisVoiceName(voice: string) {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthVoice, voice);
}
public get speechSynthesisOutputFormat(): SpeechSynthesisOutputFormat {
return (SpeechSynthesisOutputFormat as any)[this.privSpeechProperties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)];
}
public set speechSynthesisOutputFormat(format: SpeechSynthesisOutputFormat) {
this.privSpeechProperties.setProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, SpeechSynthesisOutputFormat[format]);
}
} | the_stack |
import { Logger, LogLevel } from "@pnp/logging";
import find from 'lodash/find';
import findIndex from 'lodash/findIndex';
import cloneDeep from 'lodash/cloneDeep';
import forEach from 'lodash/forEach';
import filter from 'lodash/filter';
import remove from 'lodash/remove';
import includes from 'lodash/includes';
import countBy from 'lodash/countBy';
import flatMapDeep from 'lodash/flatMapDeep';
import * as strings from "M365LPStrings";
import { ICacheConfig, IPlaylist, IAsset, IMetadata, ITechnology, ICustomizations, ICategory, SubCat, ICDN, CDN, IMultilingualString, CacheConfig } from "../models/Models";
import { HttpClientResponse, HttpClient } from "@microsoft/sp-http";
import { CustomDataService, ICustomDataService } from "./CustomDataService";
import { params } from "./Parameters";
import { CustomWebpartSource } from "../models/Enums";
export interface IDataService {
metadata: IMetadata;
customization: ICustomizations;
categoriesAll: ICategory[];
playlistsAll: IPlaylist[];
assetsAll: IAsset[];
init(): Promise<void>;
getCacheConfig(): Promise<ICacheConfig>;
getMetadata(): Promise<IMetadata>;
refreshCache(cache: ICacheConfig): Promise<ICacheConfig>;
refreshCacheCustomOnly(cache: ICacheConfig, playlists: IPlaylist[], assets: IAsset[]): Promise<ICacheConfig>;
refreshPlaylistsAll(customOnly: boolean): Promise<IPlaylist[]>;
refreshAssetsAll(customOnly: boolean): Promise<IAsset[]>;
}
export class DataService implements IDataService {
private LOG_SOURCE: string = "DataService";
public metadata: IMetadata;
public customization: ICustomizations;
public categoriesAll: ICategory[];
public playlistsAll: IPlaylist[];
public assetsAll: IAsset[];
private _cdnBase: string;
private _language: string;
private _downloadedPlaylists: IPlaylist[];
private _downloadedAssets: IAsset[];
private _customDataService: ICustomDataService;
private fieldOptions = {
headers: { Accept: "application/json;odata.metadata=none" }
};
constructor(cdn: string, language: string, customization?: ICustomizations) {
try {
this._language = language;
if (customization)
this.customization = customization;
this._customDataService = new CustomDataService(cdn);
this._cdnBase = params.baseCdnPath;
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (constructor) - ${err}`, LogLevel.Error);
}
}
public async init(): Promise<void> {
if (!this.customization)
this.customization = await this._customDataService.getCustomization();
}
public async getCacheConfig(): Promise<ICacheConfig> {
let retVal = await this._customDataService.getCacheConfig(this._language);
return retVal;
}
//Loads Metadata.json file from Microsoft CDN
public async getMetadata(): Promise<IMetadata> {
try {
let results: HttpClientResponse = await params.httpClient.fetch(`${this._cdnBase}${this._language}/metadata.json`, HttpClient.configurations.v1, this.fieldOptions);
if (results.ok) {
let resultsJson: IMetadata = await results.json();
for (let c = 0; c < resultsJson.Categories.length; c++) {
for (let sc = 0; sc < resultsJson.Categories[c].SubCategories.length; sc++) {
if (resultsJson.Categories[c].SubCategories[sc].Image.length > 1)
resultsJson.Categories[c].SubCategories[sc].Image = `${this._cdnBase}${this._language}/${resultsJson.Categories[c].SubCategories[sc].Image}`;
}
}
return resultsJson;
} else {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getMetadata) Fetch Error: ${results.statusText}`, LogLevel.Error);
return null;
}
return null;
}
catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getMetadata) - ${err}`, LogLevel.Error);
return null;
}
}
//Loads playlists.json file from Microsoft CDN
private async getPlaylists(): Promise<IPlaylist[]> {
try {
let results: HttpClientResponse = await params.httpClient.fetch(`${this._cdnBase}${this._language}/playlists.json`, HttpClient.configurations.v1, this.fieldOptions);
if (results.ok) {
let resultsJson: IPlaylist[] = await results.json();
for (let i = 0; i < resultsJson.length; i++) {
if ((resultsJson[i].Image as string).length > 1)
resultsJson[i].Image = `${this._cdnBase}${this._language}/${resultsJson[i].Image}`;
}
return resultsJson;
} else {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getPlaylists) Fetch Error: ${results.statusText}`, LogLevel.Error);
return null;
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getPlaylists) - ${err}`, LogLevel.Error);
return null;
}
}
//Loads assets.json file from Microsoft CDN
private async getAssets(): Promise<IAsset[]> {
try {
let results: HttpClientResponse = await params.httpClient.fetch(`${this._cdnBase}${this._language}/assets.json`, HttpClient.configurations.v1, this.fieldOptions);
if (results.ok) {
let resultsJson: IAsset[] = await results.json();
return resultsJson;
} else {
return null;
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getAssets) - ${err}`, LogLevel.Error);
return null;
}
}
public async refreshPlaylistsAll(customOnly: boolean = false): Promise<IPlaylist[]> {
let playlists = this._downloadedPlaylists ? cloneDeep(this._downloadedPlaylists) : [];
try {
if (!customOnly || playlists.length < 1) {
playlists = await this.getPlaylists();
this._downloadedPlaylists = cloneDeep(playlists);
}
let customPlaylists = await this._customDataService.getCustomPlaylists();
if (customPlaylists) {
playlists = playlists.concat(customPlaylists);
}
forEach(playlists, (p) => {
p.LevelValue = find(this.metadata.Levels, { Id: p.LevelId });
if (!p.LevelValue)
p.LevelValue = { Id: "", Name: "" };
p.AudienceValue = find(this.metadata.Audiences, { Id: p.AudienceId });
if (!p.AudienceValue)
p.AudienceValue = { Id: "", Name: "" };
});
//Put full playlists details on property
this.playlistsAll = cloneDeep(playlists);
//Remove custom playlists without translation for current language
playlists = remove(playlists, (p) => {
if (p.Source !== CustomWebpartSource.Tenant) return true;
let foundTranslation = find((p.Title as IMultilingualString[]), { LanguageCode: this._language });
return (foundTranslation) ? true : false;
});
//Flatten custom playlists for current language
forEach(playlists, (p) => {
if (p.Source === CustomWebpartSource.Tenant) {
let title = find((p.Title as IMultilingualString[]), { LanguageCode: this._language }).Text;
p.Title = title;
let description = find((p.Description as IMultilingualString[]), { LanguageCode: this._language }).Text;
p.Description = description;
let image = find((p.Image as IMultilingualString[]), { LanguageCode: this._language }).Text;
p.Image = image;
}
});
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (refreshPlaylistsAll) - ${err}`, LogLevel.Error);
}
return playlists;
}
public async refreshAssetsAll(customOnly: boolean = false): Promise<IAsset[]> {
let assets = this._downloadedAssets ? cloneDeep(this._downloadedAssets) : [];
try {
if (!customOnly || this._downloadedAssets.length < 1) {
assets = await this.getAssets();
this._downloadedAssets = cloneDeep(assets);
}
let customAssets = await this._customDataService.getCustomAssets();
if (customAssets) {
assets = assets.concat(customAssets);
}
this.assetsAll = cloneDeep(assets);
//Remove custom assets without translation for current language
assets = remove(assets, (a) => {
if (a.Source !== CustomWebpartSource.Tenant) return true;
let foundTranslation = find((a.Title as IMultilingualString[]), { LanguageCode: this._language });
return (foundTranslation) ? true : false;
});
//Flatten custom assets for language
forEach(assets, (a) => {
if (a.Source === CustomWebpartSource.Tenant) {
let title = find((a.Title as IMultilingualString[]), { LanguageCode: this._language }).Text;
a.Title = title;
let url = find((a.Url as IMultilingualString[]), { LanguageCode: this._language }).Text;
a.Url = url;
}
});
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (refreshAssetsAll) - ${err}`, LogLevel.Error);
}
return assets;
}
public filterPlaylists(playlists: IPlaylist[], hiddenPlaylistsIds: string[], technologies: ITechnology[]): IPlaylist[] {
try {
let p = cloneDeep(playlists);
//Merge customer hidden playlists
if (hiddenPlaylistsIds.length > 0) {
p = remove(p, (item) => {
return !includes(hiddenPlaylistsIds, item.Id);
});
}
//Remove Playlists where Technologies are hidden
if (technologies && technologies.length > 0) {
let filteredPlaylists = [];
//Add all blank technologies
filteredPlaylists = filter(p, { TechnologyId: "" });
//Filter for only visible technologies
for (let i = 0; i < technologies.length; i++) {
let pl = filter(p, { TechnologyId: technologies[i].Id });
if (pl && technologies[i].Subjects.length > 0) {
//validate subject
pl = filter(pl, (item) => {
if (item.SubjectId === "") return true;
return (findIndex(technologies[i].Subjects, { Id: item.SubjectId }) > -1);
});
}
if (pl && pl.length > 0) {
filteredPlaylists = filteredPlaylists.concat(pl);
}
}
if (filteredPlaylists.length > 0)
p = filteredPlaylists;
}
return p;
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (filterPlaylists) - ${err}`, LogLevel.Error);
}
}
private calculateCategoryCount(categories: ICategory[], playlists: IPlaylist[]): void {
try {
for (let countC = 0; countC < categories.length; countC++) {
if (categories[countC].SubCategories.length > 0) {
categories[countC].SubCategories = remove(categories[countC].SubCategories, (sc) => {
if (sc.Source !== CustomWebpartSource.Tenant) return true;
let foundTranslation = find((sc.Name as IMultilingualString[]), { LanguageCode: this._language });
return (foundTranslation) ? true : false;
});
//Flatten custom assets for language
forEach(categories[countC].SubCategories, (sc) => {
if (sc.Source === CustomWebpartSource.Tenant) {
let name = find((sc.Name as IMultilingualString[]), { LanguageCode: this._language }).Text;
sc.Name = name;
let image = find((sc.Image as IMultilingualString[]), { LanguageCode: this._language }).Text;
sc.Image = image;
}
let selectedPlaylist = countBy(playlists, { 'CatId': sc.Id });
sc.Count = selectedPlaylist.true ? selectedPlaylist.true : 0;
});
}
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (calculateCategoryCount) - ${err}`, LogLevel.Error);
}
}
private loadChildrenPath(categories: ICategory[]) {
function getPath(category: ICategory, parentPath: string[]): void {
if (!category.Path)
category.Path = parentPath.concat([category.Id]);
if (category.SubCategories.length > 0) {
for (let child = 0; child < category.SubCategories.length; child++) {
getPath(category.SubCategories[child], category.Path);
}
}
}
try {
for (let i = 0; i < categories.length; i++) {
getPath(categories[i], []);
}
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (loadChildrenPath) - ${err}`, LogLevel.Error);
}
}
//Gets cdn config and merges with custom configuration and updates cache
public async refreshCache(cache: ICacheConfig): Promise<ICacheConfig> {
try {
Logger.write(`Refresh Manifest Config - ${this.LOG_SOURCE} (refreshCache)`, LogLevel.Info);
if (!cache)
cache = new CacheConfig();
this.metadata = await this.getMetadata();
let m = cloneDeep(this.metadata);
if (m) {
if (!this.customization)
this.customization = await this._customDataService.getCustomization();
//Create Children and Path on Categories
this.loadChildrenPath(m.Categories);
//Merge custom created subcategories
if (this.customization.CustomSubcategories.length > 0) {
this.customization.CustomSubcategories.forEach((catItem) => {
if (catItem.SubCategories.length > 0) {
let cat = find(m.Categories, { Id: catItem.Id });
let customSC = cloneDeep(catItem.SubCategories);
cat.SubCategories = cat.SubCategories.concat(customSC);
}
});
}
//Make a copy for public property (includes custom sub categories)
this.categoriesAll = cloneDeep(m.Categories);
//Get a list of all categories, for finding abandoned playlists
let categoryIds = flatMapDeep(m.Categories, (n) => {
let ids: string[] = [];
ids.push(n.Id);
let subIds = flatMapDeep(n.SubCategories, "Id");
ids = ids.concat(subIds);
return ids;
});
//Merge customer hidden technology
if (this.customization.HiddenTechnology.length > 0 || this.customization.HiddenSubject.length > 0) {
m.Technologies = remove(m.Technologies, (item) => {
if (item.Subjects.length > 0) {
item.Subjects = remove(item.Subjects, (subject) => {
return (this.customization.HiddenSubject.indexOf(subject.Id) < 0);
});
}
return (this.customization.HiddenTechnology.indexOf(item.Id) < 0);
});
}
//Merge customer hidden subcategories
if (this.customization.HiddenSubCategories.length > 0) {
m.Categories = remove(m.Categories, (item) => {
if (item.SubCategories.length > 0) {
item.SubCategories = remove(item.SubCategories, (sub) => {
return (this.customization.HiddenSubCategories.indexOf(sub.Id) < 0);
});
}
return (item.SubCategories.length > 0);
});
}
//Get playlists and custom playlists
let playlists = await this.refreshPlaylistsAll();
//Note abandoned playlists
let abandonedCount: number = 0;
forEach(this.playlistsAll, (pl) => {
if (!includes(categoryIds, pl.CatId)) {
abandonedCount++;
pl.CatId = "-1";
}
});
if (abandonedCount > 0) {
let abandonedSubCat = new SubCat("-1", strings.AbandonedPlaylist, "", "", "", "Microsoft", [], [], 0);
let abandonedCat = new SubCat("0", strings.Abandoned, "", "", "", "Microsoft", [abandonedSubCat], [], 0);
this.categoriesAll.unshift(abandonedCat);
m.Categories.unshift(abandonedCat);
}
//Get assets and custom assets
let assets = await this.refreshAssetsAll();
//Filter playlists for cache
playlists = this.filterPlaylists(playlists, this.customization.HiddenPlaylistsIds, m.Technologies);
//Calculate the number of playlists for each subcategory and filter and flatten for language
this.calculateCategoryCount(m.Categories, playlists);
//Update config cache
cache.Categories = m.Categories;
cache.Technologies = m.Technologies;
cache.ManifestVersion = params.manifestVersion;
cache.CachedPlaylists = playlists;
cache.CachedAssets = assets;
cache.AssetOrigins = params.assetOrigins;
cache.LastUpdated = new Date();
params.lastUpdatedCache = cache.LastUpdated;
cache.WebPartVersion = params.webPartVersion;
//Save config to list
let c = cloneDeep(cache);
if (cache.Id > 0) {
let updateConfig = await this._customDataService.modifyCache(c);
cache.eTag = updateConfig;
} else {
//Create first config
let addConfig = await this._customDataService.createCache(c, this._language);
cache.Id = addConfig;
}
} else {
cache = null;
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (refreshCache) Could not retrieve metadata from CDN source: ${this._cdnBase}`, LogLevel.Error);
}
} catch (err) {
cache = null;
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (refreshCache) - ${err}`, LogLevel.Error);
}
return cache;
}
//Update cached config for custom sub-categories, playlists and assets only
public async refreshCacheCustomOnly(cache: ICacheConfig, playlists: IPlaylist[], assets: IAsset[]): Promise<ICacheConfig> {
try {
//Filter playlists for cache
if (playlists) {
let p = this.filterPlaylists(playlists, this.customization.HiddenPlaylistsIds, cache.Technologies);
cache.CachedPlaylists = p;
}
if (assets)
cache.CachedAssets = assets;
cache.LastUpdated = new Date();
//Merge custom created subcategories, if exist
if (this.customization.CustomSubcategories.length > 0) {
cache.Categories = cloneDeep(this.metadata.Categories);
this.customization.CustomSubcategories.forEach((catItem) => {
if (catItem.SubCategories.length > 0) {
let cat = find(cache.Categories, { Id: catItem.Id });
let customSC = cloneDeep(catItem.SubCategories);
cat.SubCategories = cat.SubCategories.concat(customSC);
}
});
}
//Make a copy for public property (includes custom sub categories)
this.categoriesAll = cloneDeep(cache.Categories);
//recalculate category counts
this.calculateCategoryCount(cache.Categories, cache.CachedPlaylists);
let c = cloneDeep(cache);
let updateConfig = await this._customDataService.modifyCache(c);
cache.eTag = updateConfig;
} catch (err) {
Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (refreshCacheCustomOnly) - ${err}`, LogLevel.Error);
}
return cache;
}
} | the_stack |
import * as React from 'react';
import * as PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {isEqual, isObject, throttle} from 'lodash';
import {toast, ToastContainer} from 'react-toastify';
import * as THREE from 'three';
import {randomBytes} from 'crypto';
import ResizeDetector from 'react-resize-detector';
import memoizeOne from 'memoize-one';
import FullScreen from 'react-full-screen';
import {v4} from 'uuid';
import {ActionCreators} from 'redux-undo';
import './virtualGamingTabletop.scss';
import {TabletopViewComponentCameraView} from './tabletopViewComponent';
import * as constants from '../util/constants';
import {
addMapAction,
addMiniAction,
setScenarioLocalAction,
settableScenarioReducer,
updateMiniNameAction
} from '../redux/scenarioReducer';
import {setTabletopIdAction} from '../redux/locationReducer';
import {addFilesAction, FileIndexReducerType} from '../redux/fileIndexReducer';
import {
getAllFilesFromStore,
getConnectedUsersFromStore,
getCreateInitialStructureFromStore,
getDeviceLayoutFromStore,
getLoggedInUserFromStore,
getMyPeerIdFromStore,
getScenarioFromStore,
getServiceWorkerFromStore,
getTabletopFromStore,
getTabletopIdFromStore,
getTabletopResourceKeyFromStore,
getTabletopValidationFromStore,
getWindowTitleFromStore,
GtoveDispatchProp,
ReduxStoreType
} from '../redux/mainReducer';
import {
cartesianToHexCoords,
effectiveHexGridType,
findPositionForNewMap,
getBaseCameraParameters,
getFocusMapIdAndFocusPointAtLevel,
getMapIdAtPoint,
getMapIdClosestToZero,
getMapIdOnNextLevel,
getNetworkHubId,
getUserDiceColours,
isMapFoggedAtPosition,
isTabletopLockedForPeer,
isUserAllowedOnTabletop,
jsonToScenarioAndTabletop,
MovementPathPoint,
ObjectVector3,
PieceVisibilityEnum,
scenarioToJson,
ScenarioType,
spiralHexGridGenerator,
spiralSquareGridGenerator,
TabletopType,
TabletopUserPreferencesType
} from '../util/scenarioUtils';
import InputButton from './inputButton';
import {
castMiniProperties,
DriveMetadata,
DriveUser,
GridType,
MapProperties,
MiniProperties,
TabletopFileAppProperties
} from '../util/googleDriveUtils';
import {
addConnectedUserAction,
ConnectedUserReducerType,
ConnectedUserUsersType,
setUserAllowedAction,
updateConnectedUserDeviceAction
} from '../redux/connectedUserReducer';
import {FileAPI, FileAPIContext, splitFileName} from '../util/fileUtils';
import {buildVector3, vector3ToObject} from '../util/threeUtils';
import {PromiseModalContext} from '../context/promiseModalContextBridge';
import {
setLastSavedHeadActionIdsAction,
setLastSavedPlayerHeadActionIdsAction,
TabletopValidationType
} from '../redux/tabletopValidationReducer';
import {MyPeerIdReducerType} from '../redux/myPeerIdReducer';
import {initialTabletopReducerState, setTabletopAction, updateTabletopAction} from '../redux/tabletopReducer';
import {BundleType, isBundle} from '../util/bundleUtils';
import {setBundleIdAction} from '../redux/bundleReducer';
import {
CreateInitialStructureReducerType,
setCreateInitialStructureAction
} from '../redux/createInitialStructureReducer';
import {getTutorialScenario} from '../tutorial/tutorialUtils';
import DeviceLayoutComponent from './deviceLayoutComponent';
import {
DeviceLayoutReducerType,
updateGroupCameraAction,
updateGroupCameraFocusMapIdAction
} from '../redux/deviceLayoutReducer';
import {appVersion} from '../util/appVersion';
import {WINDOW_TITLE_DEFAULT} from '../redux/windowTitleReducer';
import {isCloseTo} from '../util/mathsUtils';
import {ServiceWorkerReducerType, serviceWorkerSetUpdateAction} from '../redux/serviceWorkerReducer';
import UserPreferencesScreen from './userPreferencesScreen';
import ScreenControlPanelAndTabletop from './screenControlPanelAndTabletop';
import ScreenMapBrowser from '../container/screenMapBrowser';
import ScreenMiniBrowser from '../container/screenMiniBrowser';
import ScreenTemplateBrowser from '../container/screenTemplateBrowser';
import ScreenTabletopBrowser from '../container/screenTabletopBrowser';
import ScreenScenarioBrowser from '../container/screenScenarioBrowser';
import ScreenPDFBrowser from '../container/screenPDFBrowser';
import ScreenBundleBrowser from '../container/screenBundleBrowser';
interface VirtualGamingTabletopProps extends GtoveDispatchProp {
files: FileIndexReducerType;
tabletopId: string;
tabletopResourceKey?: string;
windowTitle: string;
scenario: ScenarioType;
tabletop: TabletopType;
loggedInUser: DriveUser;
connectedUsers: ConnectedUserReducerType;
tabletopValidation: TabletopValidationType;
myPeerId: MyPeerIdReducerType;
createInitialStructure: CreateInitialStructureReducerType;
deviceLayout: DeviceLayoutReducerType;
serviceWorker: ServiceWorkerReducerType;
}
export interface VirtualGamingTabletopCameraState {
cameraPosition: THREE.Vector3;
cameraLookAt: THREE.Vector3;
}
export type SetCameraFunction = (parameters: Partial<VirtualGamingTabletopCameraState>, animate?: number, focusMapId?: string) => void;
interface VirtualGamingTabletopState extends VirtualGamingTabletopCameraState {
width: number;
height: number;
targetCameraPosition?: THREE.Vector3;
targetCameraLookAt?: THREE.Vector3;
cameraAnimationStart?: number;
cameraAnimationEnd?: number;
fullScreen: boolean;
loading: string;
currentPage: VirtualGamingTabletopMode;
replaceMiniMetadataId?: string;
replaceMapMetadataId?: string;
replaceMapImageId?: string;
gmConnected: boolean;
playerView: boolean;
toastIds: {[message: string]: string | number};
focusMapId?: string;
workingMessages: string[];
workingButtons: {[key: string]: () => void};
savingTabletop: number;
}
type MiniSpace = ObjectVector3 & {scale: number};
export enum VirtualGamingTabletopMode {
GAMING_TABLETOP,
MAP_SCREEN,
MINIS_SCREEN,
TEMPLATES_SCREEN,
TABLETOP_SCREEN,
SCENARIOS_SCREEN,
PDFS_SCREEN,
BUNDLES_SCREEN,
WORKING_SCREEN,
DEVICE_LAYOUT_SCREEN,
USER_PREFERENCES_SCREEN
}
class VirtualGamingTabletop extends React.Component<VirtualGamingTabletopProps, VirtualGamingTabletopState> {
static SAVE_FREQUENCY_MS = 5000;
static contextTypes = {
fileAPI: PropTypes.object,
promiseModal: PropTypes.func
};
context: FileAPIContext & PromiseModalContext;
static readonly emptyScenario = settableScenarioReducer(undefined as any, {type: '@@init'});
private readonly emptyTabletop: TabletopType;
constructor(props: VirtualGamingTabletopProps) {
super(props);
this.onResize = this.onResize.bind(this);
this.updateVersionNow = this.updateVersionNow.bind(this);
this.returnToGamingTabletop = this.returnToGamingTabletop.bind(this);
this.setFocusMapId = this.setFocusMapId.bind(this);
this.setCameraParameters = this.setCameraParameters.bind(this);
this.saveTabletopToDrive = throttle(this.saveTabletopToDrive.bind(this), VirtualGamingTabletop.SAVE_FREQUENCY_MS, {leading: false});
this.placeMap = this.placeMap.bind(this);
this.placeMini = this.placeMini.bind(this);
this.findPositionForNewMini = this.findPositionForNewMini.bind(this);
this.findUnusedMiniName = this.findUnusedMiniName.bind(this);
this.replaceMapImage = this.replaceMapImage.bind(this);
this.calculateCameraView = memoizeOne(this.calculateCameraView);
this.getDefaultCameraFocus = this.getDefaultCameraFocus.bind(this);
this.replaceMetadata = this.replaceMetadata.bind(this);
this.changeFocusLevel = this.changeFocusLevel.bind(this);
this.createTutorial = this.createTutorial.bind(this);
this.createNewTabletop = this.createNewTabletop.bind(this);
this.state = {
width: 0,
height: 0,
fullScreen: false,
loading: '',
currentPage: props.tabletopId ? VirtualGamingTabletopMode.GAMING_TABLETOP : VirtualGamingTabletopMode.TABLETOP_SCREEN,
gmConnected: this.isGMConnected(props),
playerView: false,
toastIds: {},
...getBaseCameraParameters(),
workingMessages: [],
workingButtons: {},
savingTabletop: 0
};
this.emptyTabletop = {
...initialTabletopReducerState,
gm: props.loggedInUser.emailAddress
};
}
onResize(width?: number, height?: number) {
if (width !== undefined && height !== undefined) {
this.setState({width, height});
this.props.dispatch(updateConnectedUserDeviceAction(this.props.myPeerId!, width, height));
}
}
isGMConnected(props: VirtualGamingTabletopProps) {
// If I own the tabletop, then the GM is connected by definition. Otherwise, check connectedUsers.
return !props.tabletop || !props.tabletop.gm ||
(props.loggedInUser && props.loggedInUser.emailAddress === props.tabletop.gm) ||
Object.keys(props.connectedUsers.users).reduce<boolean>((result, peerId) => (
result || props.connectedUsers.users[peerId].user.emailAddress === props.tabletop.gm
), false);
}
private isTabletopReadonly() {
return !this.state.gmConnected
|| isTabletopLockedForPeer(this.props.tabletop, this.props.connectedUsers.users, this.props.myPeerId)
|| !isUserAllowedOnTabletop(this.props.tabletop.gm, this.props.loggedInUser.emailAddress, this.props.tabletop.tabletopUserControl);
}
private isCurrentUserPlayer() {
return !this.props.loggedInUser || this.props.loggedInUser.emailAddress !== this.props.tabletop.gm;
}
private async loadPublicPrivateJson(metadataId: string, resourceKey?: string): Promise<(ScenarioType & TabletopType) | BundleType> {
const fileAPI: FileAPI = this.context.fileAPI;
let loadedJson = await fileAPI.getJsonFileContents({id: metadataId, resourceKey});
if (loadedJson.gm && loadedJson.gm === this.props.loggedInUser.emailAddress) {
let metadata = this.props.files.driveMetadata[metadataId] as DriveMetadata<TabletopFileAppProperties, void>;
if (!metadata) {
metadata = await fileAPI.getFullMetadata(metadataId) as DriveMetadata<TabletopFileAppProperties, void>;
this.props.dispatch(addFilesAction([metadata]));
}
const privateJson = await fileAPI.getJsonFileContents({id: metadata.appProperties.gmFile});
loadedJson = {...loadedJson, ...privateJson};
}
return loadedJson;
}
deepEqualWithMetadata(o1: object, o2: object): boolean {
return Object.keys(o1).reduce<boolean>((result, key) => (
result && ((!o1 || !o2) ? o1 === o2 :
(isObject(o1[key]) && isObject(o2[key])) ? (
(key === 'metadata') ? o1[key].id === o2[key].id : this.deepEqualWithMetadata(o1[key], o2[key])
) : (
o1[key] === o2[key]
))
), true);
}
private addWorkingMessage(message: string) {
this.setState((state) => ({workingMessages: [...state.workingMessages, message]}));
}
private appendToLastWorkingMessage(message: string) {
this.setState((state) => ({workingMessages: [
...state.workingMessages.slice(0, state.workingMessages.length - 1),
state.workingMessages[state.workingMessages.length - 1] + message
]}));
}
private async createImageShortcutFromDrive(root: string, bundleName: string, fromBundleId: string, metadataList: string[]): Promise<void> {
let folder;
for (let metadataId of metadataList) {
if (!folder) {
folder = await this.context.fileAPI.createFolder(bundleName, {parents: [this.props.files.roots[root]], properties: {fromBundleId}});
this.addWorkingMessage(`Created folder ${root}/${bundleName}.`);
}
try {
const bundleMetadata = await this.context.fileAPI.getFullMetadata(metadataId);
this.addWorkingMessage(`Creating shortcut to image in ${root}/${bundleName}/${bundleMetadata.name}...`);
await this.context.fileAPI.createShortcut({...bundleMetadata, properties: {...bundleMetadata.properties, fromBundleId}}, [folder.id]);
this.appendToLastWorkingMessage(' done.');
} catch (e) {
this.addWorkingMessage(`Error! failed to create shortcut to image.`);
console.error(e);
}
}
}
private async extractBundle(bundle: BundleType, fromBundleId: string) {
this.props.dispatch(setBundleIdAction(this.props.tabletopId));
if (this.props.files.roots[constants.FOLDER_SCENARIO] && this.props.files.roots[constants.FOLDER_MAP] && this.props.files.roots[constants.FOLDER_MINI]) {
// Check if have files from this bundle already... TODO
// const existingBundleFiles = await this.context.fileAPI.findFilesWithProperty('fromBundleId', fromBundleId);
this.setState({currentPage: VirtualGamingTabletopMode.WORKING_SCREEN, workingMessages: [], workingButtons: {}});
this.addWorkingMessage(`Extracting bundle ${bundle.name}!`);
await this.createImageShortcutFromDrive(constants.FOLDER_MAP, bundle.name, fromBundleId, bundle.driveMaps);
await this.createImageShortcutFromDrive(constants.FOLDER_MINI, bundle.name, fromBundleId, bundle.driveMinis);
let folder;
for (let scenarioName of Object.keys(bundle.scenarios)) {
if (!folder) {
folder = await this.context.fileAPI.createFolder(bundle.name, {parents: [this.props.files.roots[constants.FOLDER_SCENARIO]]});
this.addWorkingMessage(`Created folder ${constants.FOLDER_SCENARIO}/${bundle.name}.`);
}
const scenario = bundle.scenarios[scenarioName];
this.addWorkingMessage(`Saving scenario ${scenarioName}...`);
await this.context.fileAPI.saveJsonToFile({name: scenarioName, parents: [folder.id], properties: {fromBundleId}}, scenario);
this.appendToLastWorkingMessage(' done.');
}
this.addWorkingMessage(`Finished extracting bundle ${bundle.name}!`);
this.setState({workingButtons: {...this.state.workingButtons, 'Close': () => {this.props.dispatch(setTabletopIdAction())}}})
}
}
async loadTabletopFromDrive(metadataId: string) {
try {
const json = metadataId ? await this.loadPublicPrivateJson(metadataId, this.props.tabletopResourceKey) : {...this.emptyTabletop, ...VirtualGamingTabletop.emptyScenario};
if (isBundle(json)) {
await this.extractBundle(json, metadataId);
} else {
const [loadedScenario, loadedTabletop] = jsonToScenarioAndTabletop(json, this.props.files.driveMetadata);
this.props.dispatch(setTabletopAction(loadedTabletop));
this.props.dispatch(setScenarioLocalAction(loadedScenario));
if (metadataId && this.props.windowTitle === WINDOW_TITLE_DEFAULT) {
const metadata = this.props.files.driveMetadata[metadataId] || await this.context.fileAPI.getFullMetadata(metadataId);
this.props.dispatch(setTabletopIdAction(metadataId, metadata.name, this.props.tabletopResourceKey));
}
// Reset Undo history after loading a tabletop
this.props.dispatch(ActionCreators.clearHistory());
}
} catch (err) {
// If the tabletop file doesn't exist, drop off that tabletop
console.error(err);
if (this.context.promiseModal?.isAvailable()) {
await this.context.promiseModal({
children: 'The link you used is no longer valid.'
});
}
this.props.dispatch(setTabletopIdAction());
}
}
async createTutorial(createTabletop = true) {
this.props.dispatch(setCreateInitialStructureAction(false));
const scenarioFolderMetadataId = this.props.files.roots[constants.FOLDER_SCENARIO];
this.setState({loading: ': Creating tutorial scenario...'});
const tutorialScenario = getTutorialScenario();
const scenarioMetadata = await this.context.fileAPI.saveJsonToFile({name: 'Tutorial Scenario', parents: [scenarioFolderMetadataId]}, tutorialScenario);
this.props.dispatch(addFilesAction([scenarioMetadata]));
if (createTabletop) {
this.setState({loading: ': Creating tutorial tabletop...'});
const tabletopFolderMetadataId = this.props.files.roots[constants.FOLDER_TABLETOP];
const publicTabletopMetadata = await this.createNewTabletop([tabletopFolderMetadataId], 'Tutorial Tabletop', tutorialScenario);
this.props.dispatch(setTabletopIdAction(publicTabletopMetadata.id, publicTabletopMetadata.name, publicTabletopMetadata.resourceKey));
this.setState({currentPage: VirtualGamingTabletopMode.GAMING_TABLETOP});
}
this.setState({loading: ''});
}
async componentDidMount() {
await this.loadTabletopFromDrive(this.props.tabletopId);
}
componentDidUpdate() {
if (this.props.createInitialStructure && !this.props.tabletopId) {
this.setState((state) => {
if (!state.loading) {
this.createTutorial();
return {loading: '...'};
}
return null;
});
}
this.animateCameraFromState();
this.checkVersions();
if (Object.keys(this.props.connectedUsers.users).length === 0 && this.props.myPeerId) {
// Add the logged-in user
this.props.dispatch(addConnectedUserAction(this.props.myPeerId, this.props.loggedInUser, appVersion, this.state.width, this.state.height, this.props.deviceLayout));
}
this.checkConnectedUsers();
}
private animateCameraFromState() {
const {targetCameraPosition, targetCameraLookAt, cameraAnimationStart, cameraAnimationEnd} = this.state;
if (targetCameraPosition && targetCameraLookAt) {
window.setTimeout(() => {
this.setState(({cameraPosition, cameraLookAt}) => {
const deltaTime = cameraAnimationStart && cameraAnimationEnd ? (Date.now() - cameraAnimationStart) / (cameraAnimationEnd - cameraAnimationStart) : undefined;
if (deltaTime === undefined || deltaTime > 1) {
return {
cameraLookAt: targetCameraLookAt,
cameraPosition: targetCameraPosition,
targetCameraLookAt: undefined,
targetCameraPosition: undefined,
cameraAnimationStart: undefined,
cameraAnimationEnd: undefined
};
} else if (cameraPosition && cameraLookAt) {
return {
cameraPosition: cameraPosition.clone().lerp(targetCameraPosition, deltaTime),
cameraLookAt: cameraLookAt.clone().lerp(targetCameraLookAt, deltaTime)
};
} else {
return null;
}
});
}, 1);
}
}
private updateVersionNow() {
const serviceWorker = this.props.serviceWorker;
if (serviceWorker.registration && serviceWorker.registration.waiting) {
serviceWorker.registration.waiting.postMessage({ type: 'SKIP_WAITING' });
window.location.reload(true);
}
}
async checkVersions() {
const serviceWorker = this.props.serviceWorker;
// Check if we have a pending update from the service worker
if (serviceWorker.update && serviceWorker.registration && serviceWorker.registration.waiting
&& this.context.promiseModal?.isAvailable()) {
const reload = 'Load latest version';
const response = await this.context.promiseModal({
children: (
<div>
<p>
You are running an outdated version of gTove! This may cause problems.
</p>
<p>
If you don't update now, you can update at any time from the menu opened from your avatar.
</p>
</div>
),
options: [reload, 'Ignore']
});
if (response === reload) {
this.updateVersionNow();
} else {
this.props.dispatch(serviceWorkerSetUpdateAction(false));
}
}
if (serviceWorker.registration && !serviceWorker.registration.waiting) {
// Also check if other clients have a newer version; if so, trigger the service worker to load the new code.
const myClientOutdated = Object.keys(this.props.connectedUsers.users).reduce<boolean>((outdated, peerId) => {
const user = this.props.connectedUsers.users[peerId];
return outdated || (user.version !== undefined && appVersion.numCommits < user.version.numCommits);
}, false);
if (myClientOutdated) {
serviceWorker.registration.update();
}
}
}
async checkConnectedUsers() {
if (this.props.tabletopId && this.context.promiseModal?.isAvailable()) {
for (let peerId of Object.keys(this.props.connectedUsers.users)) {
const user = this.props.connectedUsers.users[peerId];
if (peerId !== this.props.myPeerId && !user.checkedForTabletop && user.user.emailAddress) {
let userAllowed = isUserAllowedOnTabletop(this.props.tabletop.gm, user.user.emailAddress, this.props.tabletop.tabletopUserControl);
if (userAllowed === null) {
const allowConnection = `Allow ${user.user.displayName} to connect`;
const response = await this.context.promiseModal({
children: (
<p>
{user.user.displayName} ({user.user.emailAddress}) is attempting to connect to the
tabletop. Should they be allowed to connect?
</p>
),
options: [allowConnection, 'Add them to the blacklist']
});
userAllowed = (response === allowConnection);
// Need to dispatch this before updating whitelist/blacklist, or an allowed user won't get the
// tabletop update.
this.props.dispatch(setUserAllowedAction(peerId, userAllowed));
const {whitelist, blacklist} = this.props.tabletop.tabletopUserControl || {whitelist: [], blacklist: []};
this.props.dispatch(updateTabletopAction({tabletopUserControl: {
whitelist: userAllowed ? [...whitelist, user.user.emailAddress] : whitelist,
blacklist: userAllowed ? blacklist : [...blacklist, user.user.emailAddress]
}}));
} else {
this.props.dispatch(setUserAllowedAction(peerId, userAllowed));
}
}
}
}
}
saveTabletopToDrive(): void {
// Due to undo and redo, the tabletop may not have unsaved changes any more.
if (this.hasUnsavedActions()) {
const metadataId = this.props.tabletopId;
const driveMetadata = metadataId && this.props.files.driveMetadata[metadataId] as DriveMetadata<TabletopFileAppProperties, void>;
const scenarioState = this.props.tabletopValidation.lastCommonScenario;
if (driveMetadata && driveMetadata.appProperties && scenarioState) {
this.setState((state) => ({savingTabletop: state.savingTabletop + 1}), async () => {
const [privateScenario, publicScenario] = scenarioToJson(scenarioState);
try {
const {gmSecret, lastSavedHeadActionIds, lastSavedPlayerHeadActionIds, ...tabletop} = this.props.tabletop;
await this.context.fileAPI.saveJsonToFile(metadataId, {...publicScenario, ...tabletop});
await this.context.fileAPI.saveJsonToFile(driveMetadata.appProperties.gmFile, {...privateScenario, ...tabletop, gmSecret});
this.props.dispatch(setLastSavedHeadActionIdsAction(scenarioState, lastSavedPlayerHeadActionIds || []));
this.props.dispatch(setLastSavedPlayerHeadActionIdsAction(scenarioState, lastSavedPlayerHeadActionIds || []));
} catch (err) {
if (this.props.loggedInUser) {
throw err;
}
// Else we've logged out in the mean time, so we expect the upload to fail.
} finally {
this.setState((state) => ({savingTabletop: state.savingTabletop - 1}));
}
});
}
}
}
private updatePersistentToast(enable: boolean, message: string) {
if (enable) {
if (!this.state.toastIds[message]) {
this.setState((prevState: VirtualGamingTabletopState) => (
prevState.toastIds[message] ? null : ({
toastIds: {...prevState.toastIds, [message]: toast(message, {autoClose: false})}
})
));
}
} else if (this.state.toastIds[message]) {
toast.dismiss(this.state.toastIds[message]);
let toastIds = {...this.state.toastIds};
delete(toastIds[message]);
this.setState({toastIds});
}
}
private hasUnsavedActions(props: VirtualGamingTabletopProps = this.props) {
if (!props.tabletopValidation.lastCommonScenario) {
return false;
}
if (props.loggedInUser.emailAddress === props.tabletop.gm) {
return !isEqual(props.tabletop.lastSavedHeadActionIds, props.tabletopValidation.lastCommonScenario.headActionIds);
} else {
return !isEqual(props.tabletop.lastSavedPlayerHeadActionIds, props.tabletopValidation.lastCommonScenario.playerHeadActionIds);
}
}
async UNSAFE_componentWillReceiveProps(props: VirtualGamingTabletopProps) {
if (!props.tabletopId) {
if (this.props.tabletopId) {
// Change back to tabletop screen if we're losing our tabletopId
this.setState({currentPage: VirtualGamingTabletopMode.TABLETOP_SCREEN});
}
} else if (props.tabletopId !== this.props.tabletopId) {
await this.loadTabletopFromDrive(props.tabletopId);
} else if (props.myPeerId === getNetworkHubId(props.loggedInUser.emailAddress, props.myPeerId, props.tabletop.gm, props.connectedUsers.users)
&& this.hasUnsavedActions(props)) {
// Only save the scenario data if we are the network hub
this.saveTabletopToDrive();
}
const gmConnected = props.tabletopId !== undefined && this.isGMConnected(props);
if (gmConnected !== this.state.gmConnected) {
this.setState({gmConnected});
this.updatePersistentToast(props.tabletopId !== undefined && !gmConnected, 'View-only mode - no GM is connected.');
}
this.updatePersistentToast(gmConnected && isTabletopLockedForPeer(props.tabletop, props.connectedUsers.users, props.myPeerId),
'The tabletop is locked by the GM - only they can make changes.');
this.updatePersistentToast(gmConnected && !isUserAllowedOnTabletop(props.tabletop.gm, props.loggedInUser.emailAddress, props.tabletop.tabletopUserControl),
'Requesting permission to connect to this tabletop, please wait...');
this.updatePersistentToast(Object.keys(props.tabletopValidation.pendingActions).length > 0,
'Missing actions detected - attempting to re-synchronize.');
this.updatePersistentToast(props.connectedUsers.signalError,
'Signal server not reachable - new clients cannot connect.');
if (!this.state.focusMapId) {
if (Object.keys(props.scenario.maps).length > 0) {
// Maps have appeared for the first time.
this.setFocusMapIdToMapClosestToZero(!props.scenario.startCameraAtOrigin, props);
}
} else if (!props.scenario.maps[this.state.focusMapId]) {
// The focus map has gone
this.setFocusMapIdToMapClosestToZero(true, props);
}
this.updateCameraFromProps(props);
}
private setFocusMapIdToMapClosestToZero(panCamera: boolean, props: VirtualGamingTabletopProps = this.props) {
const closestId = getMapIdClosestToZero(props.scenario.maps);
if (closestId && (!props.scenario.maps[closestId] || !props.scenario.maps[closestId].metadata
|| !props.scenario.maps[closestId].metadata.properties || !props.scenario.maps[closestId].metadata.properties.width)) {
this.setState({focusMapId: undefined});
} else {
this.setFocusMapId(closestId, panCamera, props);
}
}
private updateCameraFromProps(props: VirtualGamingTabletopProps) {
if (props.deviceLayout.layout[props.myPeerId!]) {
const groupId = props.deviceLayout.layout[this.props.myPeerId!].deviceGroupId;
const groupCamera = props.deviceLayout.groupCamera[groupId];
const prevGroupCamera = this.props.deviceLayout.groupCamera[groupId];
const cameraPosition = groupCamera.cameraPosition ? buildVector3(groupCamera.cameraPosition) : this.state.cameraPosition;
const cameraLookAt = groupCamera.cameraLookAt ? buildVector3(groupCamera.cameraLookAt) : this.state.cameraLookAt;
if (groupCamera.animate) {
if (!prevGroupCamera
|| !prevGroupCamera.animate
|| !isEqual(prevGroupCamera.cameraPosition, groupCamera.cameraPosition)
|| !isEqual(prevGroupCamera.cameraLookAt, groupCamera.cameraLookAt)
) {
const cameraAnimationStart = Date.now();
this.setState({
targetCameraPosition: cameraPosition,
targetCameraLookAt: cameraLookAt,
cameraAnimationStart,
cameraAnimationEnd: cameraAnimationStart + groupCamera.animate
});
}
} else if (!prevGroupCamera || !isEqual(prevGroupCamera.cameraPosition, groupCamera.cameraPosition) || !isEqual(prevGroupCamera.cameraLookAt, groupCamera.cameraLookAt)) {
this.setState({cameraPosition, cameraLookAt,
targetCameraPosition: undefined, targetCameraLookAt: undefined,
cameraAnimationStart: undefined, cameraAnimationEnd: undefined});
}
if (!prevGroupCamera || prevGroupCamera.focusMapId !== groupCamera.focusMapId) {
this.setState({focusMapId: groupCamera.focusMapId});
}
}
}
returnToGamingTabletop(callback?: () => void) {
this.setState({currentPage: VirtualGamingTabletopMode.GAMING_TABLETOP,
replaceMapMetadataId: undefined, replaceMapImageId: undefined, replaceMiniMetadataId: undefined}, callback);
}
getDefaultCameraFocus(levelMapId: string | undefined | null = this.state.focusMapId, props = this.props) {
const {focusMapId, cameraLookAt} = this.getLevelCameraLookAtAndFocusMapId(levelMapId, true, props);
return getBaseCameraParameters(focusMapId ? props.scenario.maps[focusMapId] : undefined, 1, cameraLookAt);
}
setCameraParameters(cameraParameters: Partial<VirtualGamingTabletopCameraState>, animate = 0, focusMapId?: string | null) {
if (this.props.deviceLayout.layout[this.props.myPeerId!]) {
// We're part of a combined display - camera parameters are in the Redux store.
this.props.dispatch(updateGroupCameraAction(this.props.deviceLayout.layout[this.props.myPeerId!].deviceGroupId, cameraParameters, animate));
if (focusMapId !== undefined) {
this.props.dispatch(updateGroupCameraFocusMapIdAction(this.props.deviceLayout.layout[this.props.myPeerId!].deviceGroupId, focusMapId || undefined));
}
} else if (animate) {
const cameraAnimationStart = Date.now();
const cameraAnimationEnd = cameraAnimationStart + animate;
this.setState({
cameraAnimationStart,
cameraAnimationEnd,
targetCameraPosition: cameraParameters.cameraPosition || this.state.cameraPosition,
targetCameraLookAt: cameraParameters.cameraLookAt || this.state.cameraLookAt,
focusMapId: focusMapId === undefined ? this.state.focusMapId : (focusMapId || undefined)
});
} else {
this.setState({
cameraPosition: cameraParameters.cameraPosition || this.state.cameraPosition,
cameraLookAt: cameraParameters.cameraLookAt || this.state.cameraLookAt,
targetCameraPosition: undefined,
targetCameraLookAt: undefined,
cameraAnimationStart: undefined,
cameraAnimationEnd: undefined,
focusMapId: focusMapId === undefined ? this.state.focusMapId : (focusMapId || undefined)
});
}
}
lookAtPointPreservingViewAngle(newCameraLookAt: THREE.Vector3): THREE.Vector3 {
// Simply shift the cameraPosition by the same delta as we're shifting the cameraLookAt.
return newCameraLookAt.clone().sub(this.state.cameraLookAt).add(this.state.cameraPosition);
}
/**
* Given a levelMapId, find the actual ID of the best map on that level to focus on, and the selected or defeault
* 3D focus point for the level.
*
* @param levelMapId The mapId of a map on the level. If null or undefined, default to the level at elevation 0.
* @param panCamera If true, the cameraLookAt will be the focus point for the level (if no explicit focus point is
* set, it will be the centre of the focusMapId). If false, the cameraLookAt will be the same as the current
* camera's from this.state, except the elevation will that of focusMapId. If null, act like panCamera is true if
* focusMapId has an explicit focus point, false if not.
* @param props The component's props, to support calling from UNSAFE_componentWillReceiveProps.
* @returns {focusMapId, cameraLookAt} The id of the best mapId on the level (e.g. the highest one with the lowest
* mapId which has an explicit map focus point set), and the cameraLookAt for that map, as controlled by the
* parameters.
*/
getLevelCameraLookAtAndFocusMapId(levelMapId: string | null | undefined, panCamera: boolean | null, props = this.props) {
const elevation = levelMapId ? props.scenario.maps[levelMapId].position.y : 0;
const {focusMapId, cameraFocusPoint} = getFocusMapIdAndFocusPointAtLevel(props.scenario.maps, elevation);
const cameraLookAt = (panCamera || (panCamera === null && cameraFocusPoint)) ? (
(focusMapId && cameraFocusPoint) ? buildVector3(cameraFocusPoint)
: focusMapId ? buildVector3(props.scenario.maps[focusMapId].position)
: new THREE.Vector3()
) : (
new THREE.Vector3(this.state.cameraLookAt.x, focusMapId ? props.scenario.maps[focusMapId].position.y : 0, this.state.cameraLookAt.z)
);
return {focusMapId, cameraLookAt};
}
setFocusMapId(levelMapId: string | undefined, panCamera: boolean | null = true, props = this.props) {
const {focusMapId, cameraLookAt} = this.getLevelCameraLookAtAndFocusMapId(levelMapId, panCamera, props);
const cameraPosition = this.state.focusMapId || !focusMapId ? this.lookAtPointPreservingViewAngle(cameraLookAt)
: getBaseCameraParameters(props.scenario.maps[focusMapId], 1, cameraLookAt).cameraPosition;
this.setCameraParameters({cameraPosition, cameraLookAt}, 1000, focusMapId || null);
if (props.deviceLayout.layout[this.props.myPeerId!]) {
props.dispatch(updateGroupCameraFocusMapIdAction(props.deviceLayout.layout[props.myPeerId!].deviceGroupId, focusMapId));
}
}
changeFocusLevel(direction: 1 | -1) {
const levelMapId = getMapIdOnNextLevel(direction, this.props.scenario.maps, this.state.focusMapId, false);
this.setFocusMapId(levelMapId, null);
}
private doesPositionCollideWithSpace(x: number, y: number, z: number, scale: number, space: MiniSpace[]): boolean {
return space.reduce<boolean>((collide, space) => {
if (collide) {
return true;
} else {
const distance2 = (x - space.x) * (x - space.x)
+ (y - space.y) * (y - space.y)
+ (z - space.z) * (z - space.z);
const minDistance = (scale + space.scale)/2 - 0.1;
return (distance2 < minDistance * minDistance);
}
}, false);
}
findPositionForNewMini(allowHiddenMap: boolean, scale = 1.0, basePosition: THREE.Vector3 | ObjectVector3 = this.state.cameraLookAt, avoid: MiniSpace[] = []): MovementPathPoint {
// Find the map the mini is being placed on, if any.
const onMapId = getMapIdAtPoint(basePosition, this.props.scenario.maps, allowHiddenMap);
// Snap position to the relevant grid.
const gridType = onMapId ? this.props.scenario.maps[onMapId].metadata.properties.gridType : this.props.tabletop.defaultGrid;
const gridSnap = scale > 1 ? 1 : scale;
let baseX, baseZ, spiralGenerator;
switch (gridType) {
case GridType.HEX_VERT:
case GridType.HEX_HORZ:
const mapRotation = onMapId ? this.props.scenario.maps[onMapId].rotation.y : 0;
const effectiveGridType = effectiveHexGridType(mapRotation, gridType);
const {strideX, strideY, centreX, centreY} = cartesianToHexCoords(basePosition.x / gridSnap, basePosition.z / gridSnap, effectiveGridType);
baseX = centreX * strideX * gridSnap;
baseZ = centreY * strideY * gridSnap;
spiralGenerator = spiralHexGridGenerator(effectiveGridType);
break;
default:
baseX = Math.floor(basePosition.x / gridSnap) * gridSnap + (scale / 2) % 1;
baseZ = Math.floor(basePosition.z / gridSnap) * gridSnap + (scale / 2) % 1;
spiralGenerator = spiralSquareGridGenerator();
break;
}
// Get a list of occupied spaces with the same Y coordinates as our basePosition
const occupied: MiniSpace[] = avoid.concat(Object.keys(this.props.scenario.minis)
.filter((miniId) => (isCloseTo(basePosition.y, this.props.scenario.minis[miniId].position.y)))
.map((miniId) => ({...this.props.scenario.minis[miniId].position, scale: this.props.scenario.minis[miniId].scale})));
// Search for free space in a spiral pattern around basePosition.
let offsetX = 0, offsetZ = 0;
while (this.doesPositionCollideWithSpace(baseX + offsetX, basePosition.y, baseZ + offsetZ, scale, occupied)) {
({x: offsetX, y: offsetZ} = spiralGenerator.next().value);
}
return {x: baseX + offsetX, y: basePosition.y, z: baseZ + offsetZ, onMapId};
}
findUnusedMiniName(baseName: string, suffix?: number, space = true): [string, number] {
const allMinis = this.props.scenario.minis;
const allMiniIds = Object.keys(allMinis);
if (baseName === '') {
// Allow duplicate empty names
return ['', 0];
}
if (!suffix) {
// Find the largest current suffix for baseName
let current: number;
suffix = allMiniIds.reduce((largest, miniId) => {
if (allMinis[miniId].name.indexOf(baseName) === 0) {
current = Number(allMinis[miniId].name.substr(baseName.length));
}
return isNaN(current) ? largest : Math.max(largest, current);
}, 0);
}
while (true) {
const name = suffix ? baseName + (space ? ' ' : '') + String(suffix) : baseName;
if (!allMiniIds.reduce((used, miniId) => (used || allMinis[miniId].name === name), false)) {
return [name, suffix];
}
suffix++;
}
}
loggedInUserIsGM(): boolean {
return (this.props.loggedInUser !== null && this.props.loggedInUser.emailAddress === this.props.tabletop.gm);
}
replaceMetadata(isMap: boolean, metadataId?: string) {
if (isMap) {
this.setState({currentPage: VirtualGamingTabletopMode.MAP_SCREEN, replaceMapMetadataId: metadataId});
} else {
this.setState({currentPage: VirtualGamingTabletopMode.MINIS_SCREEN, replaceMiniMetadataId: metadataId});
}
}
calculateCameraView(deviceLayout: DeviceLayoutReducerType, connected: ConnectedUserUsersType, myPeerId: string, width: number, height: number): TabletopViewComponentCameraView | undefined {
const layout = deviceLayout.layout;
if (!layout[myPeerId]) {
return undefined;
}
const groupId = layout[myPeerId].deviceGroupId;
const myX = layout[myPeerId].x;
const myY = layout[myPeerId].y;
let minX = myX, maxX = myX + width;
let minY = myY, maxY = myY + height;
Object.keys(layout).forEach((peerId) => {
if (layout[peerId].deviceGroupId === groupId && connected[peerId]) {
const {x, y} = layout[peerId];
const {deviceWidth, deviceHeight} = connected[peerId];
if (minX > x) {
minX = x;
}
if (maxX < x + deviceWidth) {
maxX = x + deviceWidth;
}
if (minY > y) {
minY = y;
}
if (maxY < y + deviceHeight) {
maxY = y + deviceHeight;
}
}
});
return {
fullWidth: maxX - minX,
fullHeight: maxY - minY,
offsetX: myX - minX,
offsetY: myY - minY,
width,
height
};
}
replaceMapImage(replaceMapImageId?: string) {
this.setState({currentPage: VirtualGamingTabletopMode.MAP_SCREEN, replaceMapImageId});
}
private placeMap(metadata: DriveMetadata<void, MapProperties>) {
const {name} = splitFileName(metadata.name);
const position = vector3ToObject(findPositionForNewMap(this.props.scenario, metadata.properties, this.state.cameraLookAt));
const gmOnly = (this.loggedInUserIsGM() && metadata.properties.gridColour === constants.GRID_NONE && !this.state.playerView);
const mapId = v4();
this.props.dispatch(addMapAction({metadata, name, gmOnly, position}, mapId));
this.setState({currentPage: VirtualGamingTabletopMode.GAMING_TABLETOP, replaceMapMetadataId: undefined, replaceMapImageId: undefined}, () => {
this.setFocusMapId(mapId);
});
}
private placeMini(miniMetadata: DriveMetadata<void, MiniProperties>, avoid: MiniSpace[] = []): MiniSpace {
const match = splitFileName(miniMetadata.name).name.match(/^(.*?) *([0-9]*)$/)!;
let baseName = match[1], suffixStr = match[2];
let [name, suffix] = this.findUnusedMiniName(baseName, suffixStr ? Number(suffixStr) : undefined);
if (suffix === 1 && suffixStr !== '1') {
// There's a mini with baseName (with no suffix) already on the tabletop. Rename it.
const existingMiniId = Object.keys(this.props.scenario.minis).reduce<string | null>((result, miniId) => (
result || ((this.props.scenario.minis[miniId].name === baseName) ? miniId : null)
), null);
existingMiniId && this.props.dispatch(updateMiniNameAction(existingMiniId, name));
name = baseName + ' 2';
}
const properties = castMiniProperties(miniMetadata.properties);
const scale = properties.scale || 1;
const visibility = properties.defaultVisibility || PieceVisibilityEnum.FOGGED;
const position = this.findPositionForNewMini(visibility === PieceVisibilityEnum.HIDDEN, scale, this.state.cameraLookAt, avoid);
const onFog = position.onMapId ? isMapFoggedAtPosition(this.props.scenario.maps[position.onMapId], position) : false;
const gmOnly = (visibility === PieceVisibilityEnum.HIDDEN || (visibility === PieceVisibilityEnum.FOGGED && onFog));
if (gmOnly && (!this.loggedInUserIsGM() || this.state.playerView)) {
toast(name + ' added, but it is hidden from you.');
}
this.props.dispatch(addMiniAction({
metadata: miniMetadata,
name,
visibility,
gmOnly,
position,
movementPath: this.props.scenario.confirmMoves ? [position] : undefined,
scale,
onMapId: position.onMapId
}));
this.setState({currentPage: VirtualGamingTabletopMode.GAMING_TABLETOP});
return {...position, scale};
}
private async createNewTabletop(parents: string[], name = 'New Tabletop', scenario = VirtualGamingTabletop.emptyScenario, tabletop = this.emptyTabletop): Promise<DriveMetadata<TabletopFileAppProperties, void>> {
// Create both the private file in the GM Data folder, and the new shared tabletop file
const newTabletop = {
...tabletop,
gmSecret: randomBytes(48).toString('hex'),
...scenario
};
const privateMetadata = await this.context.fileAPI.saveJsonToFile({name, parents: [this.props.files.roots[constants.FOLDER_GM_DATA]]}, newTabletop);
const publicMetadata = await this.context.fileAPI.saveJsonToFile({name, parents, appProperties: {gmFile: privateMetadata.id}}, {...newTabletop, gmSecret: undefined});
await this.context.fileAPI.makeFileReadableToAll(publicMetadata);
return publicMetadata as DriveMetadata<TabletopFileAppProperties, void>;
}
renderWorkingScreen() {
return (
<div className='workingScreen'>
{
this.state.workingMessages.map((message, index) => (
<div key={index}>{message}</div>
))
}
<div>
{
Object.keys(this.state.workingButtons).map((label, index) => (
<InputButton type='button' key={index} onChange={this.state.workingButtons[label]}>
{label}
</InputButton>
))
}
</div>
</div>
)
}
renderDeviceLayoutScreen() {
return (
<DeviceLayoutComponent
onFinish={this.returnToGamingTabletop}
cameraPosition={this.state.cameraPosition}
cameraLookAt={this.state.cameraLookAt}
focusMapId={this.state.focusMapId}
/>
);
}
renderUserPreferencesScreen() {
const email = this.props.loggedInUser.emailAddress;
const preferences: TabletopUserPreferencesType = this.props.tabletop.userPreferences[email] || {
dieColour: getUserDiceColours(this.props.tabletop, email).diceColour
};
return (
<UserPreferencesScreen
dispatch={this.props.dispatch}
preferences={preferences}
emailAddress={email}
onFinish={this.returnToGamingTabletop}
/>
);
}
renderOptionalScreens() {
switch (this.state.currentPage) {
case VirtualGamingTabletopMode.MAP_SCREEN:
return (
<ScreenMapBrowser onFinish={this.returnToGamingTabletop}
placeMap={this.placeMap}
replaceMapMetadataId={this.state.replaceMapMetadataId}
setReplaceMetadata={this.replaceMetadata}
replaceMapImageId={this.state.replaceMapImageId}
setReplaceMapImage={this.replaceMapImage}
/>
);
case VirtualGamingTabletopMode.MINIS_SCREEN:
return (
<ScreenMiniBrowser onFinish={this.returnToGamingTabletop}
placeMini={this.placeMini}
replaceMiniMetadataId={this.state.replaceMiniMetadataId}
setReplaceMetadata={this.replaceMetadata}
/>
);
case VirtualGamingTabletopMode.TEMPLATES_SCREEN:
return (
<ScreenTemplateBrowser onFinish={this.returnToGamingTabletop}
findPositionForNewMini={this.findPositionForNewMini}
isGM={this.loggedInUserIsGM() && !this.state.playerView}
/>
);
case VirtualGamingTabletopMode.TABLETOP_SCREEN:
return (
<ScreenTabletopBrowser onFinish={this.returnToGamingTabletop}
createNewTabletop={this.createNewTabletop}
isGM={this.loggedInUserIsGM()}
/>
);
case VirtualGamingTabletopMode.SCENARIOS_SCREEN:
return this.isCurrentUserPlayer() ? null : (
<ScreenScenarioBrowser onFinish={this.returnToGamingTabletop}
isGMConnected={this.isGMConnected(this.props)}
cameraLookAt={this.state.cameraLookAt}
cameraPosition={this.state.cameraPosition}
defaultGrid={this.props.tabletop.defaultGrid}
createTutorial={this.createTutorial}
/>
);
case VirtualGamingTabletopMode.PDFS_SCREEN:
return (
<ScreenPDFBrowser onFinish={this.returnToGamingTabletop} />
);
case VirtualGamingTabletopMode.BUNDLES_SCREEN:
return (
<ScreenBundleBrowser onFinish={this.returnToGamingTabletop} />
);
case VirtualGamingTabletopMode.WORKING_SCREEN:
return this.renderWorkingScreen();
case VirtualGamingTabletopMode.DEVICE_LAYOUT_SCREEN:
return this.renderDeviceLayoutScreen();
case VirtualGamingTabletopMode.USER_PREFERENCES_SCREEN:
return this.renderUserPreferencesScreen();
default:
return null;
}
}
renderContent() {
if (this.state.loading) {
return (
<div>
Waiting on Google Drive{this.state.loading}
</div>
);
}
return (
<>
{
!this.props.tabletopId ? null : (
<ScreenControlPanelAndTabletop hidden={this.state.currentPage !== VirtualGamingTabletopMode.GAMING_TABLETOP}
readOnly={this.isTabletopReadonly()}
cameraPosition={this.state.cameraPosition}
cameraLookAt={this.state.cameraLookAt}
setCamera={this.setCameraParameters}
focusMapId={this.state.focusMapId}
setFocusMapId={this.setFocusMapId}
findPositionForNewMini={this.findPositionForNewMini}
findUnusedMiniName={this.findUnusedMiniName}
cameraView={this.calculateCameraView(this.props.deviceLayout, this.props.connectedUsers.users, this.props.myPeerId!, this.state.width, this.state.height)}
replaceMapImage={this.replaceMapImage}
changeFocusLevel={this.changeFocusLevel}
getDefaultCameraFocus={this.getDefaultCameraFocus}
fullScreen={this.state.fullScreen}
setFullScreen={(fullScreen: boolean) => {this.setState({fullScreen})}}
setCurrentScreen={(currentPage: VirtualGamingTabletopMode) => {
this.setState({currentPage});
}}
isGMConnected={this.isGMConnected(this.props)}
savingTabletop={this.state.savingTabletop}
hasUnsavedChanges={this.hasUnsavedActions()}
updateVersionNow={this.updateVersionNow}
replaceMetadata={this.replaceMetadata}
/>
)
}
{this.renderOptionalScreens()}
</>
);
}
render() {
return (
<FullScreen enabled={this.state.fullScreen} onChange={(fullScreen) => {this.setState({fullScreen})}}>
<ResizeDetector handleWidth={true} handleHeight={true} onResize={this.onResize} />
{this.renderContent()}
<ToastContainer className='toastContainer' position={toast.POSITION.BOTTOM_CENTER} hideProgressBar={true}/>
</FullScreen>
);
}
}
function mapStoreToProps(store: ReduxStoreType) {
return {
files: getAllFilesFromStore(store),
tabletopId: getTabletopIdFromStore(store),
tabletopResourceKey: getTabletopResourceKeyFromStore(store),
windowTitle: getWindowTitleFromStore(store),
tabletop: getTabletopFromStore(store),
scenario: getScenarioFromStore(store),
loggedInUser: getLoggedInUserFromStore(store)!,
connectedUsers: getConnectedUsersFromStore(store),
myPeerId: getMyPeerIdFromStore(store),
tabletopValidation: getTabletopValidationFromStore(store),
createInitialStructure: getCreateInitialStructureFromStore(store),
deviceLayout: getDeviceLayoutFromStore(store),
serviceWorker: getServiceWorkerFromStore(store)
}
}
export default connect(mapStoreToProps)(VirtualGamingTabletop); | the_stack |
import * as path from "path";
import * as fs from "fs";
import * as async from "async";
import SpriteAnimations, { SpriteAnimationPub } from "./SpriteAnimations";
// Reference to THREE, client-side only
let THREE: typeof SupEngine.THREE;
if ((global as any).window != null && (window as any).SupEngine != null) THREE = SupEngine.THREE;
type SetMapsCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, maps: any) => void);
type NewMapCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, name: string) => void);
type DeleteMapCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, name: string) => void);
type RenameMapCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, oldName: string, newName: string) => void);
type SetMapSlotCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, slot: string, name: string) => void);
type NewAnimationCallback = SupCore.Data.Base.ErrorCallback & ((err: string, animationId: string, animation: SpriteAnimationPub, index: number) => void);
type DeleteAnimationCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string) => void);
type MoveAnimationCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, index: number) => void);
type SetAnimationPropertyCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, key: string, actualValue: any) => void);
interface TextureWithSize extends THREE.Texture {
size?: {
width: number;
height: number;
};
}
export interface SpriteAssetPub {
formatVersion: number;
// FIXME: This is used client-side to store shared THREE.js textures
// We should probably find a better place for it
textures?: { [name: string]: TextureWithSize; };
maps: { [name: string]: Buffer; };
filtering: string;
wrapping: string;
pixelsPerUnit: number;
framesPerSecond: number;
opacity: number;
alphaTest: number;
frameOrder: string;
grid: { width: number; height: number; };
origin: { x: number; y: number; };
animations: SpriteAnimationPub[];
mapSlots: { [name: string]: string; };
}
export default class SpriteAsset extends SupCore.Data.Base.Asset {
static currentFormatVersion = 3;
static schema: SupCore.Data.Schema = {
formatVersion: { type: "integer" },
maps: {
type: "hash",
values: {
type: "buffer",
}
},
filtering: { type: "enum", items: [ "pixelated", "smooth"], mutable: true },
wrapping: { type: "enum", items: [ "clampToEdge", "repeat", "mirroredRepeat"], mutable: true },
pixelsPerUnit: { type: "number", minExcluded: 0, mutable: true },
framesPerSecond: { type: "number", minExcluded: 0, mutable: true },
opacity: { type: "number?", min: 0, max: 1, mutable: true },
alphaTest: { type: "number", min: 0, max: 1, mutable: true },
frameOrder: { type: "enum", items: [ "rows", "columns"], mutable: true },
grid: {
type: "hash",
properties: {
width: { type: "integer", min: 1, mutable: true },
height: { type: "integer", min: 1, mutable: true }
},
mutable: true
},
origin: {
type: "hash",
properties: {
x: { type: "number", min: 0, max: 1, mutable: true },
y: { type: "number", min: 0, max: 1, mutable: true }
}
},
animations: { type: "array" },
mapSlots: {
type: "hash",
properties: {
map: { type: "string?", mutable: true },
light: { type: "string?", mutable: true },
specular: { type: "string?", mutable: true },
alpha: { type: "string?", mutable: true },
normal: { type: "string?", mutable: true }
}
}
};
animations: SpriteAnimations;
pub: SpriteAssetPub;
// Only used on client-side
mapObjectURLs: { [mapName: string]: string };
constructor(id: string, pub: SpriteAssetPub, server: ProjectServer) {
super(id, pub, SpriteAsset.schema, server);
}
init(options: any, callback: Function) {
this.server.data.resources.acquire("spriteSettings", null, (err: Error, spriteSettings: any) => {
this.server.data.resources.release("spriteSettings", null);
this.pub = {
formatVersion: SpriteAsset.currentFormatVersion,
maps: { map: new Buffer(0) },
filtering: spriteSettings.pub.filtering,
wrapping: "clampToEdge",
pixelsPerUnit: spriteSettings.pub.pixelsPerUnit,
framesPerSecond: spriteSettings.pub.framesPerSecond,
opacity: null,
alphaTest: spriteSettings.pub.alphaTest,
frameOrder: "rows",
grid: { width: 100, height: 100 },
origin: { x: 0.5, y: 0.5 },
animations: [],
mapSlots: {
map: "map",
light: null,
specular: null,
alpha: null,
normal: null
}
};
super.init(options, callback);
});
}
setup() {
this.animations = new SpriteAnimations(this.pub.animations);
}
load(assetPath: string) {
let pub: SpriteAssetPub;
const loadMaps = () => {
let mapsName: string[] = pub.maps as any;
// NOTE: Support for multiple maps was introduced in Superpowers 0.11
if (mapsName == null) mapsName = ["map"];
pub.maps = {};
async.series([
(callback) => {
async.each(mapsName, (key, cb) => {
fs.readFile(path.join(assetPath, `map-${key}.dat`), (err, buffer) => {
// TODO: Handle error but ignore ENOENT
if (err != null) {
// NOTE: image.dat was renamed to "map-map.dat" in Superpowers 0.11
if (err.code === "ENOENT" && key === "map") {
fs.readFile(path.join(assetPath, "image.dat"), (err, buffer) => {
pub.maps[key] = buffer;
fs.writeFile(path.join(assetPath, `map-${key}.dat`), buffer, (err) => { /* Ignore */ });
fs.unlink(path.join(assetPath, "image.dat"), (err) => { /* Ignore */ });
cb();
});
} else cb();
return;
}
pub.maps[key] = buffer;
cb();
});
}, (err) => { callback(err, null); });
}
], (err) => { this._onLoaded(assetPath, pub); });
};
fs.readFile(path.join(assetPath, "sprite.json"), { encoding: "utf8" }, (err, json) => {
// NOTE: "asset.json" was renamed to "sprite.json" in Superpowers 0.11
if (err != null && err.code === "ENOENT") {
fs.readFile(path.join(assetPath, "asset.json"), { encoding: "utf8" }, (err, json) => {
fs.rename(path.join(assetPath, "asset.json"), path.join(assetPath, "sprite.json"), (err) => {
pub = JSON.parse(json);
loadMaps();
});
});
} else {
pub = JSON.parse(json);
loadMaps();
}
});
}
migrate(assetPath: string, pub: SpriteAssetPub, callback: (hasMigrated: boolean) => void) {
if (pub.formatVersion === SpriteAsset.currentFormatVersion) { callback(false); return; }
if (pub.formatVersion == null) {
// NOTE: Opacity setting was introduced in Superpowers 0.8
if (typeof pub.opacity === "undefined") pub.opacity = 1;
// NOTE: Support for multiple maps was introduced in Superpowers 0.11
if (pub.frameOrder == null) pub.frameOrder = "rows";
if ((pub as any).advancedTextures == null) {
(pub as any).advancedTextures = false;
pub.mapSlots = {
map: "map",
light: null,
specular: null,
alpha: null,
normal: null
};
}
// NOTE: Animation speed was introduced in Superpowers 0.12
for (const animation of pub.animations) {
if (animation.speed == null) animation.speed = 1;
}
pub.formatVersion = 1;
}
if (pub.formatVersion === 1) {
delete (pub as any).advancedTextures;
pub.formatVersion = 2;
}
// NOTE : Wrapping was introduced in Superpowers 0.18
if (pub.formatVersion === 2) {
pub.wrapping = "clampToEdge";
pub.formatVersion = 3;
}
callback(true);
}
client_load() {
this.mapObjectURLs = {};
this.loadTextures();
}
client_unload() {
this.unloadTextures();
}
save(outputPath: string, callback: (err: Error) => void) {
this.write(fs.writeFile, outputPath, (err) => {
if (err != null) { callback(err); return; }
// Clean up old maps from disk
async.each(Object.keys(this.pub.maps), (key, cb) => {
const value = this.pub.maps[key];
if (value != null) { cb(); return; }
fs.unlink(path.join(outputPath, `map-${key}.dat`), (err) => {
if (err != null && err.code !== "ENOENT") { cb(err); return; }
cb();
});
}, callback);
});
}
clientExport(outputPath: string, callback: (err: Error) => void) {
this.write(SupApp.writeFile, outputPath, callback);
}
private write(writeFile: Function, outputPath: string, writeCallback: (err: Error) => void) {
const maps = this.pub.maps;
(this.pub as any).maps = [];
for (const mapName in maps) {
if (maps[mapName] != null) (this.pub as any).maps.push(mapName);
}
const textures = this.pub.textures;
delete this.pub.textures;
const json = JSON.stringify(this.pub, null, 2);
this.pub.maps = maps;
this.pub.textures = textures;
async.series([
(callback) => { writeFile(path.join(outputPath, "sprite.json"), json, { encoding: "utf8" }, callback); },
(callback) => {
async.each(Object.keys(maps), (key, cb) => {
let value = maps[key];
if (value == null) { cb(); return; }
if (value instanceof ArrayBuffer) value = new Buffer(value);
writeFile(path.join(outputPath, `map-${key}.dat`), value, cb);
}, callback);
}
], writeCallback);
}
private unloadTextures() {
for (const textureName in this.pub.textures) this.pub.textures[textureName].dispose();
for (const key in this.mapObjectURLs) {
URL.revokeObjectURL(this.mapObjectURLs[key]);
delete this.mapObjectURLs[key];
}
}
private loadTextures() {
this.unloadTextures();
this.pub.textures = {};
Object.keys(this.pub.maps).forEach((key) => {
const buffer: any = this.pub.maps[key];
if (buffer == null || buffer.byteLength === 0) return;
let texture = this.pub.textures[key];
let image: HTMLImageElement = (texture != null) ? texture.image : null;
if (image == null) {
image = new Image;
texture = this.pub.textures[key] = new THREE.Texture(image);
if (this.pub.filtering === "pixelated") {
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestFilter;
}
if (this.pub.wrapping === "repeat") {
texture.wrapS = SupEngine.THREE.RepeatWrapping;
texture.wrapT = SupEngine.THREE.RepeatWrapping;
} else if (this.pub.wrapping === "mirroredRepeat") {
texture.wrapS = SupEngine.THREE.MirroredRepeatWrapping;
texture.wrapT = SupEngine.THREE.MirroredRepeatWrapping;
}
const typedArray = new Uint8Array(buffer);
const blob = new Blob([ typedArray ], { type: "image/*" });
image.src = this.mapObjectURLs[key] = URL.createObjectURL(blob);
}
if (!image.complete) {
image.addEventListener("load", () => {
// Three.js might resize our texture to make its dimensions power-of-twos
// because of WebGL limitations (see https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL#Non_power-of-two_textures)
// so we store its original, non-power-of-two size for later use
texture.size = { width: image.width, height: image.height };
texture.needsUpdate = true;
});
}
});
}
client_setProperty(path: string, value: any) {
super.client_setProperty(path, value);
switch (path) {
case "filtering":
for (const textureName in this.pub.textures) {
const texture = this.pub.textures[textureName];
if (this.pub.filtering === "pixelated") {
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestFilter;
} else {
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearMipMapLinearFilter;
}
texture.needsUpdate = true;
}
break;
case "wrapping":
for (const textureName in this.pub.textures) {
const texture = this.pub.textures[textureName];
if (value === "clampToEdge") {
texture.wrapS = SupEngine.THREE.ClampToEdgeWrapping;
texture.wrapT = SupEngine.THREE.ClampToEdgeWrapping;
} else if (value === "repeat") {
texture.wrapS = SupEngine.THREE.RepeatWrapping;
texture.wrapT = SupEngine.THREE.RepeatWrapping;
} else if (value === "mirroredRepeat") {
texture.wrapS = SupEngine.THREE.MirroredRepeatWrapping;
texture.wrapT = SupEngine.THREE.MirroredRepeatWrapping;
}
texture.needsUpdate = true;
}
break;
}
}
server_setMaps(client: SupCore.RemoteClient, maps: any, callback: SetMapsCallback) {
if (maps == null || typeof maps !== "object") { callback("Maps must be an object"); return; }
for (const key in maps) {
const value = maps[key];
if (this.pub.maps[key] == null) { callback(`The map ${key} doesn't exist`); return; }
if (value != null && !(value instanceof Buffer)) { callback(`Value for ${key} must be an ArrayBuffer or null`); return; }
}
for (const key in maps) this.pub.maps[key] = maps[key];
callback(null, null, maps);
this.emit("change");
}
client_setMaps(maps: any) {
for (const key in maps) this.pub.maps[key] = maps[key];
this.loadTextures();
}
server_newMap(client: SupCore.RemoteClient, name: string, callback: NewMapCallback) {
if (name == null || typeof name !== "string") { callback("Name of the map must be a string"); return; }
if (this.pub.maps[name] != null) { callback(`The map ${name} already exists`); return; }
this.pub.maps[name] = new Buffer(0);
callback(null, null, name);
this.emit("change");
}
client_newMap(name: string) {
this.pub.maps[name] = new Buffer(0);
}
server_deleteMap(client: SupCore.RemoteClient, name: string, callback: DeleteMapCallback) {
if (name == null || typeof name !== "string") { callback("Name of the map must be a string"); return; }
if (this.pub.maps[name] == null) { callback(`The map ${name} doesn't exist`); return; }
if (this.pub.mapSlots["map"] === name) { callback(`The main map can't be deleted`); return; }
this.client_deleteMap(name);
callback(null, null, name);
this.emit("change");
}
client_deleteMap(name: string) {
for (const slotName in this.pub.mapSlots) {
const map = this.pub.mapSlots[slotName];
if (map === name) this.pub.mapSlots[slotName] = null;
}
// NOTE: do not delete, the key must exist so the file can be deleted from the disk when the asset is saved
this.pub.maps[name] = null;
}
server_renameMap(client: SupCore.RemoteClient, oldName: string, newName: string, callback: RenameMapCallback) {
if (oldName == null || typeof oldName !== "string") { callback("Name of the map must be a string"); return; }
if (newName == null || typeof newName !== "string") { callback("New name of the map must be a string"); return; }
if (this.pub.maps[newName] != null) { callback(`The map ${newName} already exists`); return; }
this.client_renameMap(oldName, newName);
callback(null, null, oldName, newName);
this.emit("change");
}
client_renameMap(oldName: string, newName: string) {
this.pub.maps[newName] = this.pub.maps[oldName];
this.pub.maps[oldName] = null;
for (const slotName in this.pub.mapSlots) {
const map = this.pub.mapSlots[slotName];
if (map === oldName) this.pub.mapSlots[slotName] = newName;
}
}
server_setMapSlot(client: SupCore.RemoteClient, slot: string, map: string, callback: SetMapSlotCallback) {
if (slot == null || typeof slot !== "string") { callback("Name of the slot must be a string"); return; }
if (map != null && typeof map !== "string") { callback("Name of the map must be a string"); return; }
if (map != null && this.pub.maps[map] == null) { callback(`The map ${map} doesn't exist`); return; }
if (slot === "map" && map == null) { callback(`The main map can't be empty`); return; }
this.pub.mapSlots[slot] = map;
callback(null, null, slot, map);
this.emit("change");
}
client_setMapSlot(slot: string, map: string) {
this.pub.mapSlots[slot] = map;
}
server_newAnimation(client: SupCore.RemoteClient, name: string, callback: NewAnimationCallback) {
const animation: SpriteAnimationPub = { id: null, name, startFrameIndex: 0, endFrameIndex: 0, speed: 1 };
this.animations.add(animation, null, (err, actualIndex) => {
if (err != null) { callback(err); return; }
animation.name = SupCore.Data.ensureUniqueName(animation.id, animation.name, this.animations.pub);
callback(null, animation.id, animation, actualIndex);
this.emit("change");
});
}
client_newAnimation(animation: SpriteAnimationPub, actualIndex: number) {
this.animations.client_add(animation, actualIndex);
}
server_deleteAnimation(client: SupCore.RemoteClient, id: string, callback: DeleteAnimationCallback) {
this.animations.remove(id, (err) => {
if (err != null) { callback(err); return; }
callback(null, null, id);
this.emit("change");
});
}
client_deleteAnimation(id: string) {
this.animations.client_remove(id);
return;
}
server_moveAnimation(client: SupCore.RemoteClient, id: string, newIndex: number, callback: MoveAnimationCallback) {
this.animations.move(id, newIndex, (err, actualIndex) => {
if (err != null) { callback(err); return; }
callback(null, null, id, actualIndex);
this.emit("change");
});
}
client_moveAnimation(id: string, newIndex: number) {
this.animations.client_move(id, newIndex);
}
server_setAnimationProperty(client: SupCore.RemoteClient, id: string, key: string, value: any, callback: SetAnimationPropertyCallback) {
if (key === "name") {
if (typeof(value) !== "string") { callback("Invalid value"); return; }
value = value.trim();
if (SupCore.Data.hasDuplicateName(id, value, this.animations.pub)) {
callback("There's already an animation with this name");
return;
}
}
this.animations.setProperty(id, key, value, (err, actualValue) => {
if (err != null) { callback(err); return; }
callback(null, null, id, key, actualValue);
this.emit("change");
});
}
client_setAnimationProperty(id: string, key: string, actualValue: any) {
this.animations.client_setProperty(id, key, actualValue);
}
} | the_stack |
import { ILabelValue } from '../../interface/common';
import { IDirectoryLogCollectPath, IFileLogCollectPath, IKeyValue, ILogSliceRule, ILogCollectTask, ILogCollectTaskDetail } from '../../interface/collect';
import { judgeEmpty } from '../../lib/utils';
export const collectLogTypes = [{
label: '文件',
value: 'file',
}, {
label: '目录',
value: 'catalog',
}] as ILabelValue[];
export const codingFormatTypes = [{
label: 'UTF-8',
value: 'UTF-8',
}, {
label: 'ASCII',
value: 'ASCII',
}] as ILabelValue[];
export const contentFormItemLayout = {
labelCol: { span: 3 },
wrapperCol: { span: 20 },
};
export const clientFormItemLayout = {
labelCol: { span: 5 },
wrapperCol: { span: 15 },
};
export const collectLogFormItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 15 },
}
export const getParams = (obj: any, field: string, index: number) => {
for (let key in obj) {
if (key.includes(`step2_file_${field}_${index}`)) {
return judgeEmpty(obj[key]);
}
}
}
export const stepOneParams = (values: any) => {
let oldDataFilterType = '' as unknown;
let collectStartBusinessTime = 0 as number;
let collectEndBusinessTime = 0 as number;
if (values.step1_logCollectTaskType === 0) {
if (values.step1_openHistory) {
if (values.step1_historyFilter === 'current') {
oldDataFilterType = 1;
collectStartBusinessTime = (new Date()).getTime();
} else {
oldDataFilterType = 2;
collectStartBusinessTime = Date.parse(values.step1_collectStartBusinessTime);
}
} else {
oldDataFilterType = 0;
}
} else {
oldDataFilterType = 0;
// collectStartBusinessTime = Date.parse(values.step1_collectBusinessTime[0]);
// collectEndBusinessTime = Date.parse(values.step1_collectBusinessTime[1]);
}
let hostNames = [] as string[];
let filterSQL = '' as string;
if (values.step1_hostWhiteList === 'hostname') {
hostNames = values.step1_hostNames;
} else {
filterSQL = values.step1_filterSQL;
}
return {
oldDataFilterType,
collectStartBusinessTime,
collectEndBusinessTime,
filterSQL,
hostNames,
}
}
export const setIndexs = (values: any) => {
let indexs = [] as number[];
for (let key in values) {
if (key.includes('file_path')) {
const index = Number(key.substring(key.lastIndexOf("_") + 1));
indexs.push(index);
}
}
return indexs;
}
export const setValues = (values: any, str: string) => {
let data = [] as string[];
for (let key in values) {
if (key.includes(str)) {
data.push(values[key]);
}
}
return data;
}
export const stepTwoParams = (values: any) => {
let cataLogList = [] as IFileLogCollectPath[];
let fileList = [] as IDirectoryLogCollectPath[];
if (values.step2_collectionLogType === 'catalog') {
const paths = setValues(values, 'catalog_path')?.filter(Boolean);
const filterRuleChain = [
{ key: 0, value: values?.step2_catalog_collectwhitelist },
{ key: 1, value: values?.step2_catalog_collectblacklist },
] as IKeyValue[];
const logSliceRuleDTO = {
sliceType: values.step2_catalog_sliceType_, // 日志内容切片类型 0:时间戳切片 1:正则匹配切片
sliceTimestampPrefixStringIndex: values.step2_catalog_sliceTimestampPrefixStringIndex_, // 切片时间戳前缀字符串左起第几个,index计数从1开始
sliceTimestampPrefixString: values.step2_catalog_sliceTimestampPrefixString_, //切片时间戳前缀字符串
sliceTimestampFormat: values.step2_catalog_sliceTimestampFormat_, //切片 时间戳格式
sliceRegular: values.step2_catalog_sliceRegular_, // 正则匹配 ———— 切片正则
} as unknown as ILogSliceRule;
cataLogList = paths?.map(ele => {
return {
path: ele, // 路径 ———— 待采集路径
charset: values.step2_charset, // 编码格式 ———— 待采集文件字符集
maxBytesPerLogEvent: values.step2_catalog_maxBytesPerLogEvent_ * values.step2_catalog_flowunit_, // 单条日志大小上限 KB 1024 MB 1024 * 1024 ———— 单个日志切片最大大小 单位:字节 注:单个日志切片大小超过该值后,采集端将以该值进行截断采集
logSliceRuleDTO, // 日志切片规则
// fdOffsetExpirationTimeMs: values.step3_fdOffsetExpirationTimeMs, // 客户端offset(采集位点记录)清理 ———— 待采集文件 offset 有效期 单位:ms 注:待采集文件自最后一次写入时间 ~ 当前时间间隔 > fdOffset时,采集端将删除其维护的该文件对应 offset 信息,如此时,该文件仍存在于待采集目录下,将被重新采集
id: '', // 采集路径id 添加时不填,更新时必填
logCollectTaskId: '', // 采集路径关联的日志采集任务id
directoryCollectDepth: values.step2_catalog_directoryCollectDepth, // 采集深度 ———— 目录采集深度
filterRuleChain, // 采集文件黑/白名单 ———— 存储有序的文件筛选规则集。pair.key:表示黑/白名单类型,0:白名单,1:黑名单;pair.value:表示过滤规则表达式
} as unknown as IFileLogCollectPath;
});
} else {
let fileIndexs = setIndexs(values) as number[];
fileList = fileIndexs?.map((index: number) => {
const obj = {
// charset: values.step2_charset, // 编码格式 ———— 待采集文件字符集
path: getParams(values, 'path', index) || '', // 路径 ———— 待采集路径
// fdOffsetExpirationTimeMs: values.step3_fdOffsetExpirationTimeMs, // 客户端offset(采集位点记录)清理 ———— 待采集文件 offset 有效期 单位:ms 注:待采集文件自最后一次写入时间 ~ 当前时间间隔 > fdOffset时,采集端将删除其维护的该文件对应 offset 信息,如此时,该文件仍存在于待采集目录下,将被重新采集
// collectDelayThresholdMs: values.step3_collectDelayThresholdMs * 1 * 60 * 1000, // 采集延迟监控 ———— 该路径的日志对应采集延迟监控阈值 单位:ms,该阈值表示:该采集路径对应到所有待采集主机上正在采集的业务时间最小值 ~ 当前时间间隔
id: '', // 采集路径id 添加时不填,更新时必填
logCollectTaskId: '', // 采集路径关联的日志采集任务id
} as unknown as IDirectoryLogCollectPath;
return obj;
});
}
return {
cataLogList,
fileList,
}
}
// 处理新增传参
export const setStepParams = (values: any) => {
const stepOne = stepOneParams(values); // step1
const stepTwo = stepTwoParams(values); // step2
const params = {
id: '', // 日志采集任务id 添加时不填,更新时必填
// logCollectTaskRemark: values.step1_logCollectTaskRemark, // 日志采集任务备注
// directoryLogCollectPathList: stepTwo.cataLogList, // 目录类型采集路径集
logCollectTaskExecuteTimeoutMs: values.step3_logCollectTaskExecuteTimeoutMs || 0, // 采集完成时间限制 ———— 日志采集任务执行超时时间,注意:该字段仅在日志采集任务类型为类型"按指定时间范围采集"时才存在值
// >>>>>>>> Step1 <<<<<<<<<
logCollectTaskName: values.step1_logCollectTaskName, // 日志采集任务名 Yes
serviceIdList: [values.step1_serviceId], // 采集应用 ———— 采集服务集 Yes
logCollectTaskType: values.step1_logCollectTaskType || 0, // 采集模式 ———— 采集任务类型 0:常规流式采集 1:按指定时间范围采集 Yes
oldDataFilterType: stepOne.oldDataFilterType || 0, // 历史数据过滤 ———— 0:不过滤 1:从当前时间开始采集 2:从自定义时间开始采集,自定义时间取collectStartBusinessTime属性值
collectStartBusinessTime: stepOne.collectStartBusinessTime || 0, // 日志采集任务对应采集开始业务时间 注:针对 logCollectTaskType = 1 情况,该值必填;logCollectTaskType = 0 & oldDataFilterTyp = 2 时,该值必填
collectEndBusinessTime: stepOne.collectEndBusinessTime || 0, // 日志采集任务对应采集结束业务时间 注:针对 logCollectTaskType = 1 情况,该值必填;logCollectTaskType = 0 情况,该值不填
hostFilterRuleDTO: {
needHostFilterRule: values.step1_needHostFilterRule || 0, // 0否-全部 1是-部分 ———— 是否需要主机过滤规则 0:否 1:是
filterSQL: stepOne.filterSQL, // sql ———— 主机筛选命中sql,白名单
hostNames: stepOne.hostNames,
}, // 主机范围 ———— 主机过滤规则
// >>>>>>>> Step1 <<<<<<<<<
// >>>>>>>> Step2 <<<<<<<<<
fileLogCollectPathList: stepTwo.fileList, // 文件类型路径采集配置
maxBytesPerLogEvent: Number(values.step2_maxBytesPerLogEvent) * Number(values.step2_flowunit) || 2, //step2_maxBytesPerLogEvent 单条日志大小上限 ———— 单个日志切片最大大小 单位:字节 注:单个日志切片大小超过该值后,采集端将以该值进行截断采集
logContentFilterLogicDTO: {
logContentFilterExpression: values.step2_logContentFilterExpression, // 日志内容过滤表达式,needLogContentFilter为1时必填
logContentFilterType: values.step2_logContentFilterType, // 日志内容过滤类型 0:包含 1:不包含,needLogContentFilter为1时必填
needLogContentFilter: values.step2_needLogContentFilter || 0, // 是否需要对日志内容进行过滤 0:否 1:是
},// 日志过滤内容规则
fileNameSuffixMatchRuleDTO: {
// suffixSeparationCharacter: getParams(values, 'suffixSeparationCharacter', index) || '', // 文件名后缀分隔字符
// suffixMatchType: getParams(values, 'suffixMatchType', index), // 文件名后缀匹配类型 0:长度 1:正则
// suffixLength: getParams(values, 'suffixLength', index) || '', // 文件名后缀长度 suffixMatchType为0时必填
suffixMatchRegular: values.step2_file_suffixMatchRegular, //文件名后缀长度 suffixMatchType为1时必填
}, // 采集文件名后缀匹配规则
logSliceRuleDTO: {
// sliceType: getParams(values, 'sliceType', index), // 日志内容切片类型 0:时间戳切片 1:正则匹配切片
sliceTimestampPrefixStringIndex: values.step2_file_sliceTimestampPrefixStringIndex, // 切片时间戳前缀字符串左起第几个,index计数从1开始
sliceTimestampPrefixString: values.step2_file_sliceTimestampPrefixString || '', //切片时间戳前缀字符串
sliceTimestampFormat: values.step2_file_sliceTimestampFormat || '', //切片 时间戳格式
sliceRegular: values.step2_file_sliceRegular || '', // 正则匹配 ———— 切片正则
}, // 日志切片规则
// >>>>>>>> Step2 <<<<<<<<<
// >>>>>>>> Step3 <<<<<<<<<
kafkaClusterId: values.step4_kafkaClusterId, // kafka集群 ———— 采集任务采集的日志需要发往的对应Kafka集群信息id
kafkaProducerConfiguration: values.step3_productionSide || '',// kafka生产端属性
sendTopic: values.step4_sendTopic, // Topic ———— 采集任务采集的日志需要发往的topic名 (values.step3_collectDelayThresholdMs ?? 0) * 60 * 1000
opencollectDelay: values.step3_opencollectDelay, // 是否开启采集延时监控
collectDelayThresholdMs: (values?.step3_collectDelayThresholdMs) * 60 * 1000 || 3 * 60 * 1000, //采集延迟监控 ———— 该路径的日志对应采集延迟监控阈值 单位:ms,该阈值表示:该采集路径对应到所有待采集主机上正在采集的业务时间最小值 ~当前时间间隔
limitPriority: values.step3_limitPriority, // 采集任务限流保障优先级 0:高 1:中 2:低
advancedConfigurationJsonString: values.step4_advancedConfigurationJsonString, //高级配置信息 ———— 采集任务高级配置项集,为json形式字符串
// >>>>>>>> Step3 <<<<<<<<<
} as unknown as ILogCollectTask;
return params;
}
//处理编辑传参 EditStep3
export const setEditThreeParams = (objs: ILogCollectTaskDetail) => {
let step3_fdOffsetExpirationTimeMs = '' as unknown;
let step3_collectDelayThresholdMs = '' as unknown;
let step3_opencollectDelay = false
if (objs.directoryLogCollectPathList?.length) {
step3_fdOffsetExpirationTimeMs = objs.directoryLogCollectPathList[0]?.fdOffsetExpirationTimeMs;
} else {
step3_fdOffsetExpirationTimeMs = objs.fileLogCollectPathList[0]?.fdOffsetExpirationTimeMs;
step3_opencollectDelay = objs.collectDelayThresholdMs > 0 ? true : false
step3_collectDelayThresholdMs = objs.collectDelayThresholdMs * 1 / 60 / 1000;
}
return {
// step3_fdOffsetExpirationTimeMs, // 客户端offset(采集位点记录)清理
step3_collectDelayThresholdMs, // 采集延迟监控
step3_opencollectDelay, // 是否开启采集延迟监控
step3_productionSide: objs.kafkaProducerConfiguration,// kafka生产端属性
step3_logCollectTaskExecuteTimeoutMs: objs.logCollectTaskExecuteTimeoutMs || 0, // 采集完成时间限制
step3_limitPriority: objs.limitPriority, // 采集任务限流保障优先级 0:高 1:中 2:低
} as any;
}
//处理编辑传参 EditStep4
export const setEditFourParams = (objs: ILogCollectTaskDetail) => {
return {
step4_kafkaClusterId: objs.receiver.id, // Kafka集群
step4_sendTopic: objs.sendTopic, // 选择Topic
step4_advancedConfigurationJsonString: objs.advancedConfigurationJsonString, // 配置信息
} as any;
}
export const setList = (type: string, values: any) => {
let indexs = [] as number[];
for (let key in values) {
if (key.includes(`${type}`)) {
const index = Number(key.substring(key.lastIndexOf("_") + 1));
indexs.push(index);
}
}
return indexs;
} | the_stack |
import React, { Component } from 'react'
import { View } from '@instructure/ui-view'
import { testable } from '@instructure/ui-testable'
import { omitProps } from '@instructure/ui-react-utils'
import { uid } from '@instructure/uid'
import { hasVisibleChildren } from '@instructure/ui-a11y-utils'
import { findTabbable, getActiveElement } from '@instructure/ui-dom-utils'
import { withStyle, jsx } from '@instructure/emotion'
import { PaginationButton } from './PaginationButton'
import { PaginationArrowButton } from './PaginationArrowButton'
import { PaginationPageInput } from './PaginationPageInput'
import generateStyle from './styles'
import type { PaginationPageProps } from './PaginationButton/props'
import type { PaginationArrowDirections } from './PaginationArrowButton/props'
import { propTypes, allowedProps } from './props'
import type { PaginationProps, PaginationSnapshot } from './props'
/** This is an [].findIndex optimized to work on really big, but sparse, arrays */
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'arr' implicitly has an 'any' type.
const fastFindIndex = (arr, fn) =>
Number(Object.keys(arr).find((k) => fn(arr[Number(k)])))
const childrenArray = (props: PaginationProps) => {
const { children } = props
if (!children) {
return []
}
return Array.isArray(children)
? (children as React.ReactElement<PaginationPageProps>[])
: ([children] as React.ReactElement<PaginationPageProps>[])
}
function propsHaveCompactView(props: PaginationProps) {
return props.variant === 'compact' && childrenArray(props).length > 5
}
type ArrowConfig = {
pageIndex: number
label: string
shouldEnableIcon: boolean
handleButtonRef: (el: HTMLButtonElement) => void
}
/**
---
category: components
---
**/
@withStyle(generateStyle, null)
@testable()
class Pagination extends Component<PaginationProps> {
static readonly componentId = 'Pagination'
static propTypes = propTypes
static allowedProps = allowedProps
static defaultProps = {
children: null,
disabled: false,
withFirstAndLastButton: false,
showDisabledButtons: false,
variant: 'full',
as: 'div',
// @ts-expect-error ts-migrate(6133) FIXME: 'el' is declared but its value is never read.
elementRef: (el) => {},
labelNumberInput: (numberOfPages: number) => `of ${numberOfPages}`,
screenReaderLabelNumberInput: (
currentPage: number,
numberOfPages: number
) => `Select page (${currentPage} of ${numberOfPages})`,
shouldHandleFocus: true
}
static Page = PaginationButton
static Navigation = PaginationArrowButton
_labelId: string
ref: Element | null = null
_inputRef: Element | null = null
_firstButton: HTMLButtonElement | null = null
_prevButton: HTMLButtonElement | null = null
_nextButton: HTMLButtonElement | null = null
_lastButton: HTMLButtonElement | null = null
// @ts-expect-error ts-migrate(7019) FIXME: Rest parameter 'args' implicitly has an 'any[]' ty... Remove this comment to see the full error message
constructor(...args) {
// @ts-expect-error ts-migrate(2556) FIXME: Expected 1-2 arguments, but got 0 or more.
super(...args)
this._labelId = uid('Pagination')
}
get _root() {
console.warn(
'_root property is deprecated and will be removed in v9, please use ref instead'
)
return this.ref
}
get inputMode() {
return this.props.variant === 'input'
}
get childPages() {
return childrenArray(this.props)
}
get withFirstAndLastButton() {
return this.inputMode || this.props.withFirstAndLastButton
}
get showDisabledButtons() {
return this.inputMode || this.props.showDisabledButtons
}
getSnapshotBeforeUpdate(): PaginationSnapshot {
const activeElement = getActiveElement()
if (
activeElement === this._firstButton ||
activeElement === this._prevButton ||
activeElement === this._nextButton ||
activeElement === this._lastButton
) {
return { lastFocusedButton: activeElement as HTMLButtonElement }
} else {
return { lastFocusedButton: undefined }
}
}
componentDidMount() {
this.props.makeStyles?.()
}
componentDidUpdate(
prevProps: PaginationProps,
_prevState: unknown,
snapshot: PaginationSnapshot
) {
this.props.makeStyles?.()
if (
!this.props.shouldHandleFocus ||
(!propsHaveCompactView(prevProps) && !propsHaveCompactView(this.props))
) {
return
} else {
this.focusElementAfterUpdate(snapshot)
}
}
focusElementAfterUpdate(snapshot: PaginationSnapshot) {
const { lastFocusedButton } = snapshot
if (lastFocusedButton) {
const focusable = findTabbable(this.ref)
const direction = lastFocusedButton.dataset.direction
// By default we want to focus the previously focused button
let nextFocusElement: Element = lastFocusedButton
// In case the button is not focusable anymore
// (disabled or not in the DOM), we focus to the next available page
if (!focusable.includes(nextFocusElement)) {
if (direction === 'first' || direction === 'prev') {
nextFocusElement = focusable[0]
}
if (direction === 'next' || direction === 'last') {
nextFocusElement = focusable[focusable.length - 1]
}
}
;(nextFocusElement as HTMLElement).focus()
}
}
get compactView() {
return propsHaveCompactView(this.props)
}
transferDisabledPropToChildren(children: PaginationProps['children']) {
return children && this.props.disabled
? React.Children.map(children, (page) =>
React.cloneElement(page, { disabled: this.props.disabled })
)
: children
}
handleElementRef = (el: Element | null) => {
this.ref = el
if (el) {
if (typeof this.props.elementRef === 'function') {
this.props.elementRef(el)
}
}
}
handleInputRef = (el: Element | null) => {
this._inputRef = el
}
renderLabel() {
const display = this.props.variant === 'full' ? 'inline-block' : 'block'
const visibleLabel = hasVisibleChildren(this.props.label)
return (
<View
as="span"
padding={visibleLabel ? 'small' : '0'}
display={visibleLabel ? display : 'auto'}
id={this._labelId}
>
{this.props.label}
</View>
)
}
renderPageInput(currentPageIndex: number) {
return (
<PaginationPageInput
numberOfPages={this.childPages.length}
currentPageIndex={currentPageIndex}
onChange={this.handleInputChange.bind(this)}
screenReaderLabel={this.props.screenReaderLabelNumberInput!}
label={this.props.labelNumberInput}
disabled={this.props.disabled}
inputRef={this.handleInputRef}
/>
)
}
handleInputChange(
event:
| React.KeyboardEvent<HTMLInputElement>
| React.MouseEvent<HTMLButtonElement>
| React.FocusEvent<HTMLInputElement>,
pageIndex: number
) {
this.childPages[pageIndex].props.onClick?.(event)
}
renderPages(currentPageIndex: number) {
const allPages = this.childPages
let visiblePages = allPages
if (this.compactView) {
const firstIndex = 0
const lastIndex = allPages.length - 1
const sliceStart = Math.min(
lastIndex - 3,
Math.max(currentPageIndex - 1, firstIndex)
)
const sliceEnd = Math.min(currentPageIndex + 4, lastIndex)
visiblePages = allPages.slice(sliceStart, sliceEnd)
const firstPage = allPages[firstIndex]
const lastPage = allPages[lastIndex]
if (sliceStart - firstIndex > 1)
visiblePages.unshift(
<span key="first" aria-hidden="true">
…
</span>
)
if (sliceStart - firstIndex > 0) visiblePages.unshift(firstPage)
if (lastIndex - sliceEnd + 1 > 1)
visiblePages.push(
<span key="last" aria-hidden="true">
…
</span>
)
if (lastIndex - sliceEnd + 1 > 0) visiblePages.push(lastPage)
}
return (
<View display="inline-block">
{this.transferDisabledPropToChildren(visiblePages)}
</View>
)
}
getArrowVariant(
direction: PaginationArrowDirections,
currentPageIndex: number,
pagesCount: number
): ArrowConfig {
switch (direction) {
case 'first':
return {
pageIndex: 0,
label: this.props.labelFirst || 'First Page',
shouldEnableIcon: currentPageIndex > 1,
handleButtonRef: (el) => {
this._firstButton = el
}
}
case 'prev':
return {
pageIndex: currentPageIndex - 1,
label: this.props.labelPrev || 'Previous Page',
shouldEnableIcon: currentPageIndex > 0,
handleButtonRef: (el) => {
this._prevButton = el
}
}
case 'next':
return {
pageIndex: currentPageIndex + 1,
label: this.props.labelNext || 'Next Page',
shouldEnableIcon: currentPageIndex < pagesCount - 1,
handleButtonRef: (el) => {
this._nextButton = el
}
}
case 'last':
return {
pageIndex: pagesCount - 1,
label: this.props.labelLast || 'Last Page',
shouldEnableIcon: currentPageIndex < pagesCount - 2,
handleButtonRef: (el) => {
this._lastButton = el
}
}
}
}
renderArrowButton(
direction: PaginationArrowDirections,
currentPageIndex: number
) {
const { childPages } = this
// We don't display the arrows in "compact" variant under 6 items
if (!(propsHaveCompactView(this.props) || this.inputMode)) {
return null
}
if (
!this.withFirstAndLastButton &&
(direction === 'first' || direction === 'last')
) {
return null
}
const { pageIndex, label, shouldEnableIcon, handleButtonRef } =
this.getArrowVariant(direction, currentPageIndex, childPages.length)
const page = childPages[pageIndex]
const disabled =
page?.props?.disabled || this.props.disabled || !shouldEnableIcon
const onClick = page?.props?.onClick
return shouldEnableIcon || this.showDisabledButtons ? (
<PaginationArrowButton
direction={direction}
data-direction={direction}
label={label}
onClick={onClick}
disabled={disabled}
buttonRef={handleButtonRef}
/>
) : null
}
render() {
if (!this.props.children) return null
const currentPageIndex = fastFindIndex(
this.props.children,
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'p' implicitly has an 'any' type.
(p) => p && p.props && p.props.current
)
const passthroughProps = View.omitViewProps(
omitProps(this.props, Pagination.allowedProps),
Pagination
)
return (
<View
{...passthroughProps}
role="navigation"
as={this.props.as}
elementRef={this.handleElementRef}
margin={this.props.margin}
css={this.props.styles?.pagination}
aria-labelledby={this.props.label ? this._labelId : undefined}
>
{this.props.label && this.renderLabel()}
<View display="inline-block" css={this.props.styles?.pages}>
{this.renderArrowButton('first', currentPageIndex)}
{this.renderArrowButton('prev', currentPageIndex)}
{this.inputMode
? this.renderPageInput(currentPageIndex)
: this.renderPages(currentPageIndex)}
{this.renderArrowButton('next', currentPageIndex)}
{this.renderArrowButton('last', currentPageIndex)}
</View>
</View>
)
}
}
export default Pagination
export { Pagination, PaginationButton } | the_stack |
import { faHistory, faSync, faSearch } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Trans } from '@lingui/macro';
import {
Box,
Button,
ButtonGroup,
ButtonProps,
Collapse,
Container,
Divider,
Paper,
TextField,
Typography,
} from '@material-ui/core';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import SettingsIcon from '@material-ui/icons/Settings';
import { Autocomplete } from '@material-ui/lab';
import moment from 'moment';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import styled from 'styled-components';
import Criterion, { newCriterion } from './Criterion';
import LookbackMenu from './LookbackMenu';
import SearchBar from './SearchBar';
import TraceSummaryTable from './TraceSummaryTable';
import { Lookback, fixedLookbackMap, millisecondsToValue } from './lookback';
import { setAlert } from '../App/slice';
import { useUiConfig } from '../UiConfig';
import ExplainBox from '../common/ExplainBox';
import TraceSummary from '../../models/TraceSummary';
import { clearSearch, searchTraces } from '../../slices/tracesSlice';
import { RootState } from '../../store';
import { LoadingIndicator } from '../common/LoadingIndicator';
interface DiscoverPageContentProps {
autocompleteKeys: string[];
}
// Export for testing
export const useQueryParams = (autocompleteKeys: string[]) => {
const history = useHistory();
const location = useLocation();
const setQueryParams = useCallback(
(criteria: Criterion[], lookback: Lookback, limit: number) => {
const params = new URLSearchParams();
const annotationQuery: string[] = [];
criteria.forEach((criterion) => {
// If the key is 'tag' or a string included in autocompleteKeys,
// the criterion will be included in annotationQuery.
if (criterion.key === 'tagQuery') {
annotationQuery.push(criterion.value);
} else if (autocompleteKeys.includes(criterion.key)) {
if (criterion.value) {
annotationQuery.push(`${criterion.key}=${criterion.value}`);
} else {
annotationQuery.push(criterion.key);
}
} else {
params.set(criterion.key, criterion.value);
}
});
if (annotationQuery.length > 0) {
params.set('annotationQuery', annotationQuery.join(' and '));
}
switch (lookback.type) {
case 'fixed':
params.set('lookback', lookback.value);
params.set('endTs', lookback.endTime.valueOf().toString());
break;
case 'range':
params.set('lookback', 'range');
params.set('endTs', lookback.endTime.valueOf().toString());
params.set('startTs', lookback.startTime.valueOf().toString());
break;
case 'millis':
params.set('lookback', 'millis');
params.set('endTs', lookback.endTime.valueOf().toString());
params.set('millis', lookback.value.toString());
break;
default:
}
params.set('limit', limit.toString());
history.push({
pathname: location.pathname,
search: params.toString(),
});
},
[autocompleteKeys, history, location.pathname],
);
const criteria = useMemo(() => {
const ret: Criterion[] = [];
const params = new URLSearchParams(location.search);
params.forEach((value, key) => {
switch (key) {
case 'lookback':
case 'startTs':
case 'endTs':
case 'millis':
case 'limit':
break;
case 'annotationQuery': {
// Split annotationQuery into keys of autocompleteKeys and the others.
// If the autocompleteKeys is ['projectID', 'phase'] and the annotationQuery is
// 'projectID=projectA and phase=BETA and http.path=/api/v1/users and http.method=GET',
// criterion will be like the following.
// [
// { key: 'tagQuery', value: 'http.path=/api/v1/users and http.method=GET' },
// { key: 'projectID', value: 'projectA' },
// { key: 'phase', value: 'BETA' },
// ]
const tagQuery: string[] = [];
const exps = value.split(' and ');
exps.forEach((exp) => {
const strs = exp.split('=');
if (strs.length === 0) {
return;
}
const [key, value] = strs;
if (autocompleteKeys.includes(key)) {
ret.push(newCriterion(key, value || ''));
} else {
tagQuery.push(exp);
}
});
ret.push(newCriterion('tagQuery', tagQuery.join(' and ')));
break;
}
default:
ret.push(newCriterion(key, value));
break;
}
});
return ret;
}, [autocompleteKeys, location.search]);
const lookback = useMemo<Lookback | undefined>(() => {
const ps = new URLSearchParams(location.search);
const lookback = ps.get('lookback');
if (!lookback) {
return undefined;
}
switch (lookback) {
case 'range': {
const startTs = ps.get('startTs');
const endTs = ps.get('endTs');
if (!endTs || !startTs) {
return undefined;
}
const startTime = moment(parseInt(startTs, 10));
const endTime = moment(parseInt(endTs, 10));
return {
type: 'range',
startTime,
endTime,
};
}
case 'millis': {
const endTs = ps.get('endTs');
const valueStr = ps.get('millis');
if (!endTs || !valueStr) {
return undefined;
}
const endTime = moment(parseInt(endTs, 10));
const value = parseInt(valueStr, 10);
return {
type: 'millis',
endTime,
value,
};
}
default: {
// Otherwise lookback should be 1m, 5m 15m, ...
const data = fixedLookbackMap[lookback];
if (!data) {
return undefined;
}
const endTs = ps.get('endTs');
if (!endTs) {
return undefined;
}
return {
type: 'fixed',
value: data.value,
endTime: moment(parseInt(endTs, 10)),
};
}
}
}, [location.search]);
const limit = useMemo(() => {
const ps = new URLSearchParams(location.search);
const limit = ps.get('limit');
if (!limit) {
return undefined;
}
return parseInt(limit, 10);
}, [location.search]);
return {
setQueryParams,
criteria,
lookback,
limit,
};
};
// Export for testing
export const parseDuration = (duration: string) => {
const regex = /^(\d+)(s|ms|us)?$/;
const match = duration.match(regex);
if (!match || match.length < 2) {
return undefined;
}
if (match.length === 2 || typeof match[2] === 'undefined') {
return parseInt(match[1], 10);
}
switch (match[2]) {
case 's':
return parseInt(match[1], 10) * 1000 * 1000;
case 'ms':
return parseInt(match[1], 10) * 1000;
case 'us':
return parseInt(match[1], 10);
default:
return undefined;
}
};
// Export for testing
export const buildApiQuery = (
criteria: Criterion[],
lookback: Lookback,
limit: number,
autocompleteKeys: string[],
) => {
const params: { [key: string]: string } = {};
const annotationQuery: string[] = [];
criteria.forEach((criterion) => {
if (criterion.key === 'tagQuery') {
annotationQuery.push(criterion.value);
} else if (autocompleteKeys.includes(criterion.key)) {
if (criterion.value) {
annotationQuery.push(`${criterion.key}=${criterion.value}`);
} else {
annotationQuery.push(criterion.key);
}
} else if (
criterion.key === 'minDuration' ||
criterion.key === 'maxDuration'
) {
const duration = parseDuration(criterion.value);
if (duration) {
params[criterion.key] = duration.toString();
}
} else {
params[criterion.key] = criterion.value;
}
});
if (annotationQuery.length > 0) {
params.annotationQuery = annotationQuery.join(' and ');
}
params.endTs = lookback.endTime.valueOf().toString();
switch (lookback.type) {
case 'range': {
const lb = lookback.endTime.valueOf() - lookback.startTime.valueOf();
params.lookback = lb.toString();
break;
}
case 'millis': {
params.lookback = lookback.value.toString();
break;
}
case 'fixed': {
params.lookback = fixedLookbackMap[lookback.value].duration
.asMilliseconds()
.toString();
break;
}
default:
}
params.limit = limit.toString();
return params;
};
const useFetchTraces = (
autocompleteKeys: string[],
criteria: Criterion[],
lookback?: Lookback,
limit?: number,
) => {
const dispatch = useDispatch();
useEffect(() => {
// For searching, lookback and limit are always required.
// If it doesn't exist, clear trace summaries.
if (!lookback || !limit) {
dispatch(clearSearch());
return;
}
const params = buildApiQuery(criteria, lookback, limit, autocompleteKeys);
dispatch(searchTraces(params));
}, [autocompleteKeys, criteria, dispatch, limit, lookback]);
};
const initialLookback = (
lookback: Lookback | undefined,
defaultLookback: number,
): Lookback => {
if (lookback) {
return lookback;
}
const fixed = millisecondsToValue[defaultLookback];
if (fixed) {
return {
type: 'fixed',
value: fixed,
endTime: moment(),
};
}
return {
type: 'millis',
value: defaultLookback,
endTime: moment(),
};
};
const useFilters = (traceSummaries: TraceSummary[]) => {
const [filters, setFilters] = useState<string[]>([]);
const filterOptions = useMemo(
() =>
Array.from(
traceSummaries.reduce((set, traceSummary) => {
traceSummary.serviceSummaries.forEach((serviceSummary) => {
set.add(serviceSummary.serviceName);
});
return set;
}, new Set<string>()),
),
[traceSummaries],
);
const handleFiltersChange = useCallback((event: any, value: string[]) => {
setFilters(value);
}, []);
const toggleFilter = useCallback(
(serviceName: string) => {
if (filters.includes(serviceName)) {
setFilters(filters.filter((filter) => filter !== serviceName));
} else {
const newFilters = [...filters];
newFilters.push(serviceName);
setFilters(newFilters);
}
},
[filters],
);
return {
filters,
handleFiltersChange,
filterOptions,
toggleFilter,
};
};
const useTraceSummaryOpenState = (traceSummaries: TraceSummary[]) => {
const [traceSummaryOpenMap, setTraceSummaryOpenMap] = useState<{
[key: string]: boolean;
}>({});
const expandAll = useCallback(() => {
setTraceSummaryOpenMap(
traceSummaries.reduce((acc, cur) => {
acc[cur.traceId] = true;
return acc;
}, {} as { [key: string]: boolean }),
);
}, [traceSummaries]);
const collapseAll = useCallback(() => {
setTraceSummaryOpenMap({});
}, []);
const toggleTraceSummaryOpen = useCallback((traceId: string) => {
setTraceSummaryOpenMap((prev) => {
const newTraceSummaryOpenMap = { ...prev };
newTraceSummaryOpenMap[traceId] = !newTraceSummaryOpenMap[traceId];
return newTraceSummaryOpenMap;
});
}, []);
return {
traceSummaryOpenMap,
expandAll,
collapseAll,
toggleTraceSummaryOpen,
};
};
const DiscoverPageContent: React.FC<DiscoverPageContentProps> = ({
autocompleteKeys,
}) => {
// Retrieve search criteria from the URL query string and use them to search for traces.
const { setQueryParams, criteria, lookback, limit } = useQueryParams(
autocompleteKeys,
);
useFetchTraces(autocompleteKeys, criteria, lookback, limit);
// Temporary search criteria.
const [tempCriteria, setTempCriteria] = useState(criteria);
const { defaultLookback, queryLimit } = useUiConfig();
const [tempLookback, setTempLookback] = useState<Lookback>(
initialLookback(lookback, defaultLookback),
);
const [tempLimit, setTempLimit] = useState(limit || queryLimit);
const lookbackDisplay = useMemo<string>(() => {
switch (tempLookback.type) {
case 'fixed':
return fixedLookbackMap[tempLookback.value].display;
case 'range':
return `${tempLookback.startTime.format(
'MM/DD/YYYY HH:mm:ss',
)} - ${tempLookback.endTime.format('MM/DD/YYYY HH:mm:ss')}`;
case 'millis':
return `${tempLookback.value}ms`;
default:
return '';
}
}, [tempLookback]);
const handleLimitChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setTempLimit(parseInt(event.target.value, 10));
},
[],
);
const searchTraces = useCallback(() => {
const criteria = tempCriteria.filter((c) => !!c.key);
// If the lookback is fixed or millis, need to set the click time to endTime.
if (tempLookback.type === 'fixed' || tempLookback.type === 'millis') {
setQueryParams(
criteria,
{ ...tempLookback, endTime: moment() },
tempLimit,
);
} else {
setQueryParams(criteria, tempLookback, tempLimit);
}
}, [setQueryParams, tempCriteria, tempLookback, tempLimit]);
const { isLoading, traceSummaries, error } = useSelector(
(state: RootState) => state.traces.search,
);
const [isShowingLookbackMenu, setIsShowingLookbackMenu] = useState(false);
const toggleLookbackMenu = useCallback(() => {
setIsShowingLookbackMenu((prev) => !prev);
}, []);
const closeLookbackMenu = useCallback(() => {
setIsShowingLookbackMenu(false);
}, []);
const [isOpeningSettings, setIsOpeningSettings] = useState(false);
const handleSettingsButtonClick = useCallback(() => {
setIsOpeningSettings((prev) => !prev);
}, []);
const {
filters,
handleFiltersChange,
filterOptions,
toggleFilter,
} = useFilters(traceSummaries);
const {
traceSummaryOpenMap,
expandAll,
collapseAll,
toggleTraceSummaryOpen,
} = useTraceSummaryOpenState(traceSummaries);
const filteredTraceSummaries = useMemo(() => {
return traceSummaries.filter((traceSummary) => {
const serviceNameSet = new Set(
traceSummary.serviceSummaries.map(
(serviceSummary) => serviceSummary.serviceName,
),
);
return !filters.find((filter) => !serviceNameSet.has(filter));
});
}, [filters, traceSummaries]);
const dispatch = useDispatch();
// If there is a problem during the search, show it.
useEffect(() => {
if (error) {
let message = 'Failed to search';
if (error.message) {
message += `: ${error.message}`;
}
dispatch(
setAlert({
message,
severity: 'error',
}),
);
}
}, [dispatch, error]);
let content: JSX.Element | undefined;
if (isLoading) {
content = <LoadingIndicator />;
} else if (traceSummaries.length === 0) {
content = (
<ExplainBox
icon={faSearch}
headerText={<Trans>Search Traces</Trans>}
text={
<Trans>
Please select criteria in the search bar. Then, click the search
button.
</Trans>
}
/>
);
} else {
content = (
<Paper elevation={3}>
<TraceSummaryTable
traceSummaries={filteredTraceSummaries}
toggleFilter={toggleFilter}
traceSummaryOpenMap={traceSummaryOpenMap}
toggleTraceSummaryOpen={toggleTraceSummaryOpen}
/>
</Paper>
);
}
return (
<Box
width="100%"
height="calc(100vh - 64px)"
display="flex"
flexDirection="column"
>
<Box
bgcolor="background.paper"
boxShadow={3}
pt={2}
pb={1.5}
zIndex={1000}
>
<Container>
<Box display="flex">
<Box flexGrow={1} mr={1}>
<SearchBar
criteria={tempCriteria}
onChange={setTempCriteria}
searchTraces={searchTraces}
/>
</Box>
<SearchButton onClick={searchTraces}>Run Query</SearchButton>
<SettingsButton
onClick={handleSettingsButtonClick}
isOpening={isOpeningSettings}
data-testid="settings-button"
>
<SettingsIcon />
</SettingsButton>
</Box>
</Container>
<Collapse in={isOpeningSettings}>
<Box mt={1.5} mb={1.5}>
<Divider />
</Box>
<Container>
<Box
display="flex"
alignItems="center"
justifyContent="flex-end"
mt={1.75}
>
<TextField
label={<Trans>Limit</Trans>}
type="number"
variant="outlined"
value={tempLimit}
onChange={handleLimitChange}
size="small"
inputProps={{
'data-testid': 'query-limit',
}}
/>
<Box ml={1} position="relative">
<LookbackButton
onClick={toggleLookbackMenu}
isShowingLookbackMenu={isShowingLookbackMenu}
>
{lookbackDisplay}
</LookbackButton>
{isShowingLookbackMenu && (
<LookbackMenu
close={closeLookbackMenu}
onChange={setTempLookback}
lookback={tempLookback}
/>
)}
</Box>
</Box>
</Container>
</Collapse>
{traceSummaries.length > 0 && (
<>
<Box mt={1.5} mb={1.5}>
<Divider />
</Box>
<Container>
<Box
display="flex"
justifyContent="space-between"
alignItems="center"
>
<Typography variant="h6">
{filteredTraceSummaries.length === 1 ? (
<Trans>1 Result</Trans>
) : (
<Trans>{filteredTraceSummaries.length} Results</Trans>
)}
</Typography>
<Box display="flex">
<ButtonGroup>
<Button onClick={expandAll}>Expand All</Button>
<Button onClick={collapseAll}>Collapse All</Button>
</ButtonGroup>
<Box width={300} ml={2}>
<Autocomplete
multiple
value={filters}
options={filterOptions}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Service filters"
placeholder="Service filters"
size="small"
/>
)}
size="small"
onChange={handleFiltersChange}
/>
</Box>
</Box>
</Box>
</Container>
</>
)}
</Box>
<Box flexGrow={1} overflow="auto" pt={3} pb={3}>
<Container>{content}</Container>
</Box>
</Box>
);
};
export default DiscoverPageContent;
const LookbackButton = styled(
({
isShowingLookbackMenu,
...rest
}: { isShowingLookbackMenu: boolean } & ButtonProps) => (
<Button
variant="outlined"
startIcon={<FontAwesomeIcon icon={faHistory} />}
endIcon={isShowingLookbackMenu ? <ExpandLessIcon /> : <ExpandMoreIcon />}
{...rest}
/>
),
)`
/* Align LookbackButton height with the TextField height. */
padding-top: 7.5px;
padding-bottom: 7.5px;
`;
const SearchButton = styled(Button).attrs({
variant: 'contained',
color: 'primary',
startIcon: <FontAwesomeIcon icon={faSync} />,
})`
flex-shrink: 0;
height: 60px;
min-width: 60px;
color: ${({ theme }) => theme.palette.common.white};
`;
const SettingsButton = styled(
({ isOpening, ...rest }: { isOpening: boolean } & ButtonProps) => (
<Button
variant="outlined"
endIcon={isOpening ? <ExpandLessIcon /> : <ExpandMoreIcon />}
{...rest}
/>
),
)`
flex-shrink: 0;
height: 60px;
min-width: 0px;
margin-left: ${({ theme }) => theme.spacing(1)}px;
`; | the_stack |
import {InferenceHandler} from '../../backend';
import {Logger} from '../../instrument';
import {Tensor} from '../../tensor';
import {ShapeUtil} from '../../util';
import {createPackProgramInfoLoader} from './ops/pack';
import {createPackedReshape3DProgramInfoLoader, isReshapeCheap, processDims3D} from './ops/reshape-packed';
import {encodeAsUint8} from './ops/uint8-encode';
import {createUnpackProgramInfoLoader} from './ops/unpack';
import {WebGLSessionHandler} from './session-handler';
import {Encoder} from './texture-data-encoder';
import {calculateTextureWidthAndHeight, createTextureLayoutFromShape, createTextureLayoutFromTextureType} from './texture-layout';
import {Artifact, ProgramInfo, ProgramInfoLoader, TextureData, TextureLayout, TextureType} from './types';
const getProgramInfoUniqueKey =
(programInfo: ProgramInfo|ProgramInfoLoader, inputTextureDatas: TextureData[]): string => {
const inputs =
inputTextureDatas.map(texture => `${texture.unpackedShape.join(',')};${texture.width}x${texture.height}`)
.join('_');
let key = programInfo.name;
if (programInfo.cacheHint) {
key += '[' + programInfo.cacheHint + ']';
}
key += ':' + inputs;
return key;
};
export class WebGLInferenceHandler implements InferenceHandler {
private packedTextureDataCache: Map<Tensor.Id, TextureData>;
private unpackedTextureDataCache: Map<Tensor.Id, TextureData>;
constructor(public session: WebGLSessionHandler) {
this.packedTextureDataCache = new Map();
this.unpackedTextureDataCache = new Map();
}
/**
* @returns [width, height]
*/
calculateTextureWidthAndHeight(shape: readonly number[], textureType: TextureType): [number, number] {
return calculateTextureWidthAndHeight(this.session.layoutStrategy, shape, textureType);
}
executeProgram(program: ProgramInfo|ProgramInfoLoader, inputs: readonly Tensor[]): TextureData {
if (inputs.length < program.inputNames.length) {
throw new Error(`Input size mustn't be less than ${program.inputNames.length}.`);
}
if (program.inputNames.length !== program.inputTypes.length) {
throw new Error('input names size does not match input types');
}
// create texture info for input
const inputTextureDatas: TextureData[] = [];
for (let i = 0; i < program.inputNames.length; ++i) {
inputTextureDatas[i] = this.getOrCreateTextureData(inputs[i], program.inputTypes[i]);
}
const key = getProgramInfoUniqueKey(program, inputTextureDatas);
let artifact = this.session.programManager.getArtifact(key);
const programInfo = artifact ?
artifact.programInfo :
(typeof (program as ProgramInfoLoader).get === 'function' ? (program as ProgramInfoLoader).get() :
(program as ProgramInfo));
// create texture info for output
const outputTextureLayout = createTextureLayoutFromTextureType(
this.session.layoutStrategy, programInfo.output.dims, programInfo.output.textureType);
const outputTextureData = this.createTextureData(outputTextureLayout, programInfo.output.type);
if (!artifact) {
artifact = this.session.programManager.build(programInfo, inputTextureDatas, outputTextureData);
this.session.programManager.setArtifact(key, artifact);
}
this.runProgram(artifact, inputTextureDatas, outputTextureData);
return outputTextureData;
}
run(program: ProgramInfoLoader, inputs: readonly Tensor[]): Tensor {
const outputTextureData = this.executeProgram(program, inputs);
return outputTextureData.tensor;
}
private runProgram(artifact: Artifact, inputs: TextureData[], output: TextureData): void {
// input should match
for (let i = 0; i < inputs.length; ++i) {
if (!!inputs[i].isPacked !== (artifact.programInfo.inputTypes[i] === TextureType.packed)) {
throw new Error(`input[${i}] property packed inconsistent`);
}
}
// output should match
if (!!output.isPacked !== (artifact.programInfo.output.textureType === TextureType.packed)) {
throw new Error('output property packed inconsistent');
}
this.session.programManager.run(artifact, inputs, output);
}
/**
* Create a TextureData object from a tensor.
* Usage = Encoder.Usage.UploadOnly.
* If a related texture data is found in cache, returns it;
* Otherwise:
* Creates a new texture layout if not provided;
* Creates WebGLTexture with the layout;
* Upload tensor data to the texture;
* Creates a texture data object associated with the given tensor.
* @param tensor the tensor with data to upload
*/
private getOrCreateTextureData(tensor: Tensor, textureType: TextureType) {
let td = this.getTextureData(tensor.dataId, textureType === TextureType.packed);
if (!td) {
// check if we have texture data in different type
td = this.getTextureData(tensor.dataId, textureType !== TextureType.packed);
if (td) {
if (textureType === TextureType.packed) {
return this.pack(td);
} else {
return this.unpack(td);
}
}
}
if (!td) {
const layout = createTextureLayoutFromTextureType(this.session.layoutStrategy, tensor.dims, textureType);
if (textureType === TextureType.packedLastDimension) {
const group = 1;
const channels = 4;
const shape = tensor.dims;
if (shape.length === 4) {
// pre-processing for kernel data of Conv.
//
// TODO: currently this is a hacking to overwrite Conv's weight. The correct way to do this should be:
// 1. implement texture based const-folding
// 2. create a WebGL program "preprocessConvWeight" to do the same work as below
// 3. run the program before dotProduct.
//
const adjustedKernelShape = [shape[0], Math.ceil((shape[1] * shape[2] * shape[3]) / channels)];
const adjustedLayout =
createTextureLayoutFromTextureType(this.session.layoutStrategy, adjustedKernelShape, textureType);
let buffer = tensor.numberData;
if (shape[1] * shape[2] * shape[3] % channels !== 0) {
const numFeatureMaps = shape[0];
const oldRowSize = shape[1] * shape[2] * shape[3];
const newRowSize = Math.ceil(oldRowSize * group / channels) * channels;
const newSize = numFeatureMaps * newRowSize;
buffer = new Float32Array(newSize);
for (let f = 0; f < numFeatureMaps; ++f) {
const oldOffset = f * oldRowSize;
const newOffset = f * newRowSize + f % group * oldRowSize;
buffer.set(tensor.numberData.subarray(oldOffset, oldOffset + oldRowSize), newOffset);
}
}
return this.createTextureData(adjustedLayout, tensor.type, buffer, tensor, Encoder.Usage.UploadOnly);
}
}
if (textureType === TextureType.packed) {
const unpackedTextureLayout =
createTextureLayoutFromShape(this.session.layoutStrategy, tensor.dims, 1, [], {reverseWH: true});
const unpackedTextureData = this.createTextureData(
unpackedTextureLayout, tensor.type, tensor.numberData, tensor, Encoder.Usage.UploadOnly);
td = this.pack(unpackedTextureData);
} else {
td = this.createTextureData(layout, tensor.type, tensor.numberData, tensor, Encoder.Usage.UploadOnly);
}
}
return td;
}
/**
* Create a TextureData object using the given data and bind to the given tensor.
* Usage = Encoder.Usage.UploadOnly.
* NOTE: this function is a hack for Conv implementation. should remove this function, after rewriting Conv
* implementation by Graph.Transformer
* @param dataType the tensor data type
* @param data the actual data to upload
* @param tensor the tensor to bind. tensor's data is ignored.
*/
createTextureDataFromLayoutBindTensor(
layout: TextureLayout, dataType: Tensor.DataType, data: Tensor.NumberType, tensor: Tensor): TextureData {
return this.createTextureData(layout, dataType, data, tensor, Encoder.Usage.UploadOnly);
}
private createTextureData(
layout: TextureLayout, dataType: Tensor.DataType, data?: Tensor.NumberType, tensor?: Tensor,
usage?: Encoder.Usage): TextureData {
Logger.verbose('InferenceHandler', `Creating TextureData: layout:[${JSON.stringify(layout)}]`);
const texture = this.session.textureManager.createTextureFromLayout(dataType, layout, data, usage);
return this.createTextureDataFromTexture(layout, dataType, texture, tensor);
}
reshapeUnpacked(input: Tensor, reshapedDims: readonly number[]): Tensor {
const inputTD = this.getOrCreateTextureData(input, TextureType.unpacked);
const newTextureLayout: TextureLayout = {
channels: inputTD.channels,
height: inputTD.height,
width: inputTD.width,
// handle reshaping into scalar Tensors
shape: reshapedDims.length !== 0 ? reshapedDims : [1],
strides: ShapeUtil.computeStrides(reshapedDims),
unpackedShape: reshapedDims,
};
const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
return newTextureData.tensor;
}
reshapePacked(input: Tensor, reshapedDims: readonly number[]): Tensor {
const inputTD = this.getOrCreateTextureData(input, TextureType.packed);
// check if the reshape is 'cheap'
if (isReshapeCheap(input.dims, reshapedDims)) {
const newTextureLayout: TextureLayout = {
channels: inputTD.channels,
height: inputTD.height,
width: inputTD.width,
// handle reshaping into scalar Tensors
shape: reshapedDims.length !== 0 ? reshapedDims : [1],
strides: ShapeUtil.computeStrides(reshapedDims),
unpackedShape: reshapedDims,
isPacked: true
};
const newTextureData = this.createTextureDataFromTexture(newTextureLayout, input.type, inputTD.texture);
return newTextureData.tensor;
}
const squeezedInputShape = processDims3D(input.dims);
const squeezedOutputShape = processDims3D(reshapedDims);
const squeezedInputTensor = this.reshapePacked(input, squeezedInputShape);
const squeezedOutputTensor = this.run(
createPackedReshape3DProgramInfoLoader(this, squeezedInputTensor, squeezedOutputShape), [squeezedInputTensor]);
const outputTensor = this.reshapePacked(squeezedOutputTensor, reshapedDims);
return outputTensor;
}
cast(input: Tensor, type: Tensor.DataType): Tensor {
const inputTD = this.getOrCreateTextureData(input, TextureType.unpacked);
const newTextureData = this.createTextureDataFromTexture(inputTD as TextureLayout, type, inputTD.texture);
return newTextureData.tensor;
}
private createTextureDataFromTexture(
layout: TextureLayout, dataType: Tensor.DataType, texture: WebGLTexture, tensor?: Tensor, tensorId?: Tensor.Id) {
const textureData: TextureData = {
...layout,
tensor: tensor ||
new Tensor(
layout.unpackedShape, dataType, (_id: Tensor.Id) => this.readTexture(textureData),
async (_id: Tensor.Id) => this.readTextureAsync(textureData), undefined, tensorId),
texture
};
this.setTextureData(textureData.tensor.dataId, textureData, layout.isPacked);
return textureData;
}
private getTextureData(tensorId: Tensor.Id, isPacked = false): TextureData|undefined {
return this.session.isInitializer(tensorId) ? this.session.getTextureData(tensorId, isPacked) :
isPacked ? this.packedTextureDataCache.get(tensorId) :
this.unpackedTextureDataCache.get(tensorId);
}
setTextureData(tensorId: Tensor.Id, td: TextureData, isPacked = false): void {
if (this.session.isInitializer(tensorId)) {
this.session.setTextureData(tensorId, td, isPacked);
} else {
(isPacked ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(tensorId, td);
}
}
isTextureLayoutCached(tensor: Tensor, isPacked = false): boolean {
return !!this.getTextureData(tensor.dataId, isPacked);
}
dispose(): void {
this.session.textureManager.clearActiveTextures();
this.packedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
this.packedTextureDataCache = new Map();
this.unpackedTextureDataCache.forEach(td => this.session.textureManager.releaseTexture(td));
this.unpackedTextureDataCache = new Map();
}
readTexture(textureData: TextureData): Tensor.NumberType {
if (textureData.isPacked) {
return this.readTexture(this.unpack(textureData));
}
if (!this.session.backend.glContext.isFloat32DownloadSupported) {
return this.session.textureManager.readUint8TextureAsFloat(encodeAsUint8(this, textureData));
}
return this.session.textureManager.readTexture(textureData, textureData.tensor.type, textureData.channels);
}
async readTextureAsync(textureData: TextureData): Promise<Tensor.NumberType> {
if (textureData.isPacked) {
return this.readTextureAsync(this.unpack(textureData));
}
if (!this.session.backend.glContext.isFloat32DownloadSupported) {
return this.session.textureManager.readUint8TextureAsFloat(encodeAsUint8(this, textureData));
}
return this.session.textureManager.readTextureAsync(textureData, textureData.tensor.type, textureData.channels);
}
pack(input: TextureData): TextureData {
const outputTextureData = this.executeProgram(createPackProgramInfoLoader(this, input.tensor), [input.tensor]);
return outputTextureData;
}
unpack(input: TextureData): TextureData {
const outputTextureData = this.executeProgram(createUnpackProgramInfoLoader(this, input.tensor), [input.tensor]);
return outputTextureData;
}
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
AssociateTrackerConsumerCommand,
AssociateTrackerConsumerCommandInput,
AssociateTrackerConsumerCommandOutput,
} from "./commands/AssociateTrackerConsumerCommand";
import {
BatchDeleteDevicePositionHistoryCommand,
BatchDeleteDevicePositionHistoryCommandInput,
BatchDeleteDevicePositionHistoryCommandOutput,
} from "./commands/BatchDeleteDevicePositionHistoryCommand";
import {
BatchDeleteGeofenceCommand,
BatchDeleteGeofenceCommandInput,
BatchDeleteGeofenceCommandOutput,
} from "./commands/BatchDeleteGeofenceCommand";
import {
BatchEvaluateGeofencesCommand,
BatchEvaluateGeofencesCommandInput,
BatchEvaluateGeofencesCommandOutput,
} from "./commands/BatchEvaluateGeofencesCommand";
import {
BatchGetDevicePositionCommand,
BatchGetDevicePositionCommandInput,
BatchGetDevicePositionCommandOutput,
} from "./commands/BatchGetDevicePositionCommand";
import {
BatchPutGeofenceCommand,
BatchPutGeofenceCommandInput,
BatchPutGeofenceCommandOutput,
} from "./commands/BatchPutGeofenceCommand";
import {
BatchUpdateDevicePositionCommand,
BatchUpdateDevicePositionCommandInput,
BatchUpdateDevicePositionCommandOutput,
} from "./commands/BatchUpdateDevicePositionCommand";
import {
CalculateRouteCommand,
CalculateRouteCommandInput,
CalculateRouteCommandOutput,
} from "./commands/CalculateRouteCommand";
import {
CreateGeofenceCollectionCommand,
CreateGeofenceCollectionCommandInput,
CreateGeofenceCollectionCommandOutput,
} from "./commands/CreateGeofenceCollectionCommand";
import { CreateMapCommand, CreateMapCommandInput, CreateMapCommandOutput } from "./commands/CreateMapCommand";
import {
CreatePlaceIndexCommand,
CreatePlaceIndexCommandInput,
CreatePlaceIndexCommandOutput,
} from "./commands/CreatePlaceIndexCommand";
import {
CreateRouteCalculatorCommand,
CreateRouteCalculatorCommandInput,
CreateRouteCalculatorCommandOutput,
} from "./commands/CreateRouteCalculatorCommand";
import {
CreateTrackerCommand,
CreateTrackerCommandInput,
CreateTrackerCommandOutput,
} from "./commands/CreateTrackerCommand";
import {
DeleteGeofenceCollectionCommand,
DeleteGeofenceCollectionCommandInput,
DeleteGeofenceCollectionCommandOutput,
} from "./commands/DeleteGeofenceCollectionCommand";
import { DeleteMapCommand, DeleteMapCommandInput, DeleteMapCommandOutput } from "./commands/DeleteMapCommand";
import {
DeletePlaceIndexCommand,
DeletePlaceIndexCommandInput,
DeletePlaceIndexCommandOutput,
} from "./commands/DeletePlaceIndexCommand";
import {
DeleteRouteCalculatorCommand,
DeleteRouteCalculatorCommandInput,
DeleteRouteCalculatorCommandOutput,
} from "./commands/DeleteRouteCalculatorCommand";
import {
DeleteTrackerCommand,
DeleteTrackerCommandInput,
DeleteTrackerCommandOutput,
} from "./commands/DeleteTrackerCommand";
import {
DescribeGeofenceCollectionCommand,
DescribeGeofenceCollectionCommandInput,
DescribeGeofenceCollectionCommandOutput,
} from "./commands/DescribeGeofenceCollectionCommand";
import { DescribeMapCommand, DescribeMapCommandInput, DescribeMapCommandOutput } from "./commands/DescribeMapCommand";
import {
DescribePlaceIndexCommand,
DescribePlaceIndexCommandInput,
DescribePlaceIndexCommandOutput,
} from "./commands/DescribePlaceIndexCommand";
import {
DescribeRouteCalculatorCommand,
DescribeRouteCalculatorCommandInput,
DescribeRouteCalculatorCommandOutput,
} from "./commands/DescribeRouteCalculatorCommand";
import {
DescribeTrackerCommand,
DescribeTrackerCommandInput,
DescribeTrackerCommandOutput,
} from "./commands/DescribeTrackerCommand";
import {
DisassociateTrackerConsumerCommand,
DisassociateTrackerConsumerCommandInput,
DisassociateTrackerConsumerCommandOutput,
} from "./commands/DisassociateTrackerConsumerCommand";
import {
GetDevicePositionCommand,
GetDevicePositionCommandInput,
GetDevicePositionCommandOutput,
} from "./commands/GetDevicePositionCommand";
import {
GetDevicePositionHistoryCommand,
GetDevicePositionHistoryCommandInput,
GetDevicePositionHistoryCommandOutput,
} from "./commands/GetDevicePositionHistoryCommand";
import { GetGeofenceCommand, GetGeofenceCommandInput, GetGeofenceCommandOutput } from "./commands/GetGeofenceCommand";
import {
GetMapGlyphsCommand,
GetMapGlyphsCommandInput,
GetMapGlyphsCommandOutput,
} from "./commands/GetMapGlyphsCommand";
import {
GetMapSpritesCommand,
GetMapSpritesCommandInput,
GetMapSpritesCommandOutput,
} from "./commands/GetMapSpritesCommand";
import {
GetMapStyleDescriptorCommand,
GetMapStyleDescriptorCommandInput,
GetMapStyleDescriptorCommandOutput,
} from "./commands/GetMapStyleDescriptorCommand";
import { GetMapTileCommand, GetMapTileCommandInput, GetMapTileCommandOutput } from "./commands/GetMapTileCommand";
import {
ListDevicePositionsCommand,
ListDevicePositionsCommandInput,
ListDevicePositionsCommandOutput,
} from "./commands/ListDevicePositionsCommand";
import {
ListGeofenceCollectionsCommand,
ListGeofenceCollectionsCommandInput,
ListGeofenceCollectionsCommandOutput,
} from "./commands/ListGeofenceCollectionsCommand";
import {
ListGeofencesCommand,
ListGeofencesCommandInput,
ListGeofencesCommandOutput,
} from "./commands/ListGeofencesCommand";
import { ListMapsCommand, ListMapsCommandInput, ListMapsCommandOutput } from "./commands/ListMapsCommand";
import {
ListPlaceIndexesCommand,
ListPlaceIndexesCommandInput,
ListPlaceIndexesCommandOutput,
} from "./commands/ListPlaceIndexesCommand";
import {
ListRouteCalculatorsCommand,
ListRouteCalculatorsCommandInput,
ListRouteCalculatorsCommandOutput,
} from "./commands/ListRouteCalculatorsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ListTrackerConsumersCommand,
ListTrackerConsumersCommandInput,
ListTrackerConsumersCommandOutput,
} from "./commands/ListTrackerConsumersCommand";
import {
ListTrackersCommand,
ListTrackersCommandInput,
ListTrackersCommandOutput,
} from "./commands/ListTrackersCommand";
import { PutGeofenceCommand, PutGeofenceCommandInput, PutGeofenceCommandOutput } from "./commands/PutGeofenceCommand";
import {
SearchPlaceIndexForPositionCommand,
SearchPlaceIndexForPositionCommandInput,
SearchPlaceIndexForPositionCommandOutput,
} from "./commands/SearchPlaceIndexForPositionCommand";
import {
SearchPlaceIndexForTextCommand,
SearchPlaceIndexForTextCommandInput,
SearchPlaceIndexForTextCommandOutput,
} from "./commands/SearchPlaceIndexForTextCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateGeofenceCollectionCommand,
UpdateGeofenceCollectionCommandInput,
UpdateGeofenceCollectionCommandOutput,
} from "./commands/UpdateGeofenceCollectionCommand";
import { UpdateMapCommand, UpdateMapCommandInput, UpdateMapCommandOutput } from "./commands/UpdateMapCommand";
import {
UpdatePlaceIndexCommand,
UpdatePlaceIndexCommandInput,
UpdatePlaceIndexCommandOutput,
} from "./commands/UpdatePlaceIndexCommand";
import {
UpdateRouteCalculatorCommand,
UpdateRouteCalculatorCommandInput,
UpdateRouteCalculatorCommandOutput,
} from "./commands/UpdateRouteCalculatorCommand";
import {
UpdateTrackerCommand,
UpdateTrackerCommandInput,
UpdateTrackerCommandOutput,
} from "./commands/UpdateTrackerCommand";
import { LocationClient } from "./LocationClient";
/**
* Suite of geospatial services including Maps, Places, Routes, Tracking, and Geofencing
*/
export class Location extends LocationClient {
/**
* <p>Creates an association between a geofence collection and a tracker resource. This
* allows the tracker resource to communicate location data to the linked geofence
* collection. </p>
* <p>You can associate up to five geofence collections to each tracker resource.</p>
* <note>
* <p>Currently not supported — Cross-account configurations, such as creating associations between a tracker resource in one account and a geofence collection in another account.</p>
* </note>
*/
public associateTrackerConsumer(
args: AssociateTrackerConsumerCommandInput,
options?: __HttpHandlerOptions
): Promise<AssociateTrackerConsumerCommandOutput>;
public associateTrackerConsumer(
args: AssociateTrackerConsumerCommandInput,
cb: (err: any, data?: AssociateTrackerConsumerCommandOutput) => void
): void;
public associateTrackerConsumer(
args: AssociateTrackerConsumerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AssociateTrackerConsumerCommandOutput) => void
): void;
public associateTrackerConsumer(
args: AssociateTrackerConsumerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AssociateTrackerConsumerCommandOutput) => void),
cb?: (err: any, data?: AssociateTrackerConsumerCommandOutput) => void
): Promise<AssociateTrackerConsumerCommandOutput> | void {
const command = new AssociateTrackerConsumerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the position history of one or more devices from a tracker resource.</p>
*/
public batchDeleteDevicePositionHistory(
args: BatchDeleteDevicePositionHistoryCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchDeleteDevicePositionHistoryCommandOutput>;
public batchDeleteDevicePositionHistory(
args: BatchDeleteDevicePositionHistoryCommandInput,
cb: (err: any, data?: BatchDeleteDevicePositionHistoryCommandOutput) => void
): void;
public batchDeleteDevicePositionHistory(
args: BatchDeleteDevicePositionHistoryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchDeleteDevicePositionHistoryCommandOutput) => void
): void;
public batchDeleteDevicePositionHistory(
args: BatchDeleteDevicePositionHistoryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchDeleteDevicePositionHistoryCommandOutput) => void),
cb?: (err: any, data?: BatchDeleteDevicePositionHistoryCommandOutput) => void
): Promise<BatchDeleteDevicePositionHistoryCommandOutput> | void {
const command = new BatchDeleteDevicePositionHistoryCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a batch of geofences from a geofence collection.</p>
* <note>
* <p>This operation deletes the resource permanently.</p>
* </note>
*/
public batchDeleteGeofence(
args: BatchDeleteGeofenceCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchDeleteGeofenceCommandOutput>;
public batchDeleteGeofence(
args: BatchDeleteGeofenceCommandInput,
cb: (err: any, data?: BatchDeleteGeofenceCommandOutput) => void
): void;
public batchDeleteGeofence(
args: BatchDeleteGeofenceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchDeleteGeofenceCommandOutput) => void
): void;
public batchDeleteGeofence(
args: BatchDeleteGeofenceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchDeleteGeofenceCommandOutput) => void),
cb?: (err: any, data?: BatchDeleteGeofenceCommandOutput) => void
): Promise<BatchDeleteGeofenceCommandOutput> | void {
const command = new BatchDeleteGeofenceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Evaluates device positions against the geofence geometries from a given geofence
* collection.</p>
* <p>This operation always returns an empty response because geofences are asynchronously
* evaluated. The evaluation determines if the device has entered or exited a geofenced
* area, and then publishes one of the following events to Amazon EventBridge:</p>
* <ul>
* <li>
* <p>
* <code>ENTER</code> if Amazon Location determines that the tracked device has entered
* a geofenced area.</p>
* </li>
* <li>
* <p>
* <code>EXIT</code> if Amazon Location determines that the tracked device has exited a
* geofenced area.</p>
* </li>
* </ul>
* <note>
* <p>The last geofence that a device was observed within is tracked for 30 days after
* the most recent device position update.</p>
* </note>
*/
public batchEvaluateGeofences(
args: BatchEvaluateGeofencesCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchEvaluateGeofencesCommandOutput>;
public batchEvaluateGeofences(
args: BatchEvaluateGeofencesCommandInput,
cb: (err: any, data?: BatchEvaluateGeofencesCommandOutput) => void
): void;
public batchEvaluateGeofences(
args: BatchEvaluateGeofencesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchEvaluateGeofencesCommandOutput) => void
): void;
public batchEvaluateGeofences(
args: BatchEvaluateGeofencesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchEvaluateGeofencesCommandOutput) => void),
cb?: (err: any, data?: BatchEvaluateGeofencesCommandOutput) => void
): Promise<BatchEvaluateGeofencesCommandOutput> | void {
const command = new BatchEvaluateGeofencesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the latest device positions for requested devices.</p>
*/
public batchGetDevicePosition(
args: BatchGetDevicePositionCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchGetDevicePositionCommandOutput>;
public batchGetDevicePosition(
args: BatchGetDevicePositionCommandInput,
cb: (err: any, data?: BatchGetDevicePositionCommandOutput) => void
): void;
public batchGetDevicePosition(
args: BatchGetDevicePositionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchGetDevicePositionCommandOutput) => void
): void;
public batchGetDevicePosition(
args: BatchGetDevicePositionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchGetDevicePositionCommandOutput) => void),
cb?: (err: any, data?: BatchGetDevicePositionCommandOutput) => void
): Promise<BatchGetDevicePositionCommandOutput> | void {
const command = new BatchGetDevicePositionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>A batch request for storing geofence geometries into a given geofence collection, or
* updates the geometry of an existing geofence if a geofence ID is included in the request.</p>
*/
public batchPutGeofence(
args: BatchPutGeofenceCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchPutGeofenceCommandOutput>;
public batchPutGeofence(
args: BatchPutGeofenceCommandInput,
cb: (err: any, data?: BatchPutGeofenceCommandOutput) => void
): void;
public batchPutGeofence(
args: BatchPutGeofenceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchPutGeofenceCommandOutput) => void
): void;
public batchPutGeofence(
args: BatchPutGeofenceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchPutGeofenceCommandOutput) => void),
cb?: (err: any, data?: BatchPutGeofenceCommandOutput) => void
): Promise<BatchPutGeofenceCommandOutput> | void {
const command = new BatchPutGeofenceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Uploads position update data for one or more devices to a tracker resource. Amazon Location
* uses the data when it reports the last known device position and position history. Amazon Location retains location data for 30
* days.</p>
* <note>
* <p>Position updates are handled based on the <code>PositionFiltering</code> property of the tracker.
* When <code>PositionFiltering</code> is set to <code>TimeBased</code>, updates are evaluated against linked geofence collections,
* and location data is stored at a maximum of one position per 30 second interval. If your update frequency is more often than
* every 30 seconds, only one update per 30 seconds is stored for each unique device ID.
* When <code>PositionFiltering</code> is set to <code>DistanceBased</code> filtering, location data is stored and evaluated against linked geofence
* collections only if the device has moved more than 30 m (98.4 ft).</p>
* </note>
*/
public batchUpdateDevicePosition(
args: BatchUpdateDevicePositionCommandInput,
options?: __HttpHandlerOptions
): Promise<BatchUpdateDevicePositionCommandOutput>;
public batchUpdateDevicePosition(
args: BatchUpdateDevicePositionCommandInput,
cb: (err: any, data?: BatchUpdateDevicePositionCommandOutput) => void
): void;
public batchUpdateDevicePosition(
args: BatchUpdateDevicePositionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: BatchUpdateDevicePositionCommandOutput) => void
): void;
public batchUpdateDevicePosition(
args: BatchUpdateDevicePositionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchUpdateDevicePositionCommandOutput) => void),
cb?: (err: any, data?: BatchUpdateDevicePositionCommandOutput) => void
): Promise<BatchUpdateDevicePositionCommandOutput> | void {
const command = new BatchUpdateDevicePositionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* <a href="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html">Calculates a route</a> given the following required parameters:
* <code>DeparturePostiton</code> and <code>DestinationPosition</code>. Requires that
* you first <a href="https://docs.aws.amazon.com/location-routes/latest/APIReference/API_CreateRouteCalculator.html">create a
* route calculator resource</a>
* </p>
* <p>By default, a request that doesn't specify a departure time uses the best time of day
* to travel with the best traffic conditions when calculating the route.</p>
* <p>Additional options include:</p>
* <ul>
* <li>
* <p>
* <a href="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#departure-time">Specifying a departure time</a> using either <code>DepartureTime</code> or
* <code>DepartureNow</code>. This calculates a route based on predictive
* traffic data at the given time. </p>
* <note>
* <p>You can't specify both <code>DepartureTime</code> and
* <code>DepartureNow</code> in a single request. Specifying both
* parameters returns an error message.</p>
* </note>
* </li>
* <li>
* <p>
* <a href="https://docs.aws.amazon.com/location/latest/developerguide/calculate-route.html#travel-mode">Specifying a travel mode</a> using TravelMode. This lets you specify an
* additional route preference such as <code>CarModeOptions</code> if traveling by
* <code>Car</code>, or <code>TruckModeOptions</code> if traveling by
* <code>Truck</code>.</p>
* </li>
* </ul>
* <p>
* </p>
*/
public calculateRoute(
args: CalculateRouteCommandInput,
options?: __HttpHandlerOptions
): Promise<CalculateRouteCommandOutput>;
public calculateRoute(
args: CalculateRouteCommandInput,
cb: (err: any, data?: CalculateRouteCommandOutput) => void
): void;
public calculateRoute(
args: CalculateRouteCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CalculateRouteCommandOutput) => void
): void;
public calculateRoute(
args: CalculateRouteCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CalculateRouteCommandOutput) => void),
cb?: (err: any, data?: CalculateRouteCommandOutput) => void
): Promise<CalculateRouteCommandOutput> | void {
const command = new CalculateRouteCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a geofence collection, which manages and stores geofences.</p>
*/
public createGeofenceCollection(
args: CreateGeofenceCollectionCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateGeofenceCollectionCommandOutput>;
public createGeofenceCollection(
args: CreateGeofenceCollectionCommandInput,
cb: (err: any, data?: CreateGeofenceCollectionCommandOutput) => void
): void;
public createGeofenceCollection(
args: CreateGeofenceCollectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateGeofenceCollectionCommandOutput) => void
): void;
public createGeofenceCollection(
args: CreateGeofenceCollectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateGeofenceCollectionCommandOutput) => void),
cb?: (err: any, data?: CreateGeofenceCollectionCommandOutput) => void
): Promise<CreateGeofenceCollectionCommandOutput> | void {
const command = new CreateGeofenceCollectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a map resource in your AWS account, which provides map tiles of different
* styles sourced from global location data providers.</p>
*/
public createMap(args: CreateMapCommandInput, options?: __HttpHandlerOptions): Promise<CreateMapCommandOutput>;
public createMap(args: CreateMapCommandInput, cb: (err: any, data?: CreateMapCommandOutput) => void): void;
public createMap(
args: CreateMapCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateMapCommandOutput) => void
): void;
public createMap(
args: CreateMapCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateMapCommandOutput) => void),
cb?: (err: any, data?: CreateMapCommandOutput) => void
): Promise<CreateMapCommandOutput> | void {
const command = new CreateMapCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a place index resource in your AWS account, which supports functions with
* geospatial data sourced from your chosen data provider.</p>
*/
public createPlaceIndex(
args: CreatePlaceIndexCommandInput,
options?: __HttpHandlerOptions
): Promise<CreatePlaceIndexCommandOutput>;
public createPlaceIndex(
args: CreatePlaceIndexCommandInput,
cb: (err: any, data?: CreatePlaceIndexCommandOutput) => void
): void;
public createPlaceIndex(
args: CreatePlaceIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreatePlaceIndexCommandOutput) => void
): void;
public createPlaceIndex(
args: CreatePlaceIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreatePlaceIndexCommandOutput) => void),
cb?: (err: any, data?: CreatePlaceIndexCommandOutput) => void
): Promise<CreatePlaceIndexCommandOutput> | void {
const command = new CreatePlaceIndexCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a route calculator resource in your AWS account.</p>
* <p>You can send requests to a route calculator resource to estimate travel time,
* distance, and get directions. A route calculator sources traffic and road network data
* from your chosen data provider.</p>
*/
public createRouteCalculator(
args: CreateRouteCalculatorCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateRouteCalculatorCommandOutput>;
public createRouteCalculator(
args: CreateRouteCalculatorCommandInput,
cb: (err: any, data?: CreateRouteCalculatorCommandOutput) => void
): void;
public createRouteCalculator(
args: CreateRouteCalculatorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateRouteCalculatorCommandOutput) => void
): void;
public createRouteCalculator(
args: CreateRouteCalculatorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateRouteCalculatorCommandOutput) => void),
cb?: (err: any, data?: CreateRouteCalculatorCommandOutput) => void
): Promise<CreateRouteCalculatorCommandOutput> | void {
const command = new CreateRouteCalculatorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a tracker resource in your AWS account, which lets you retrieve current and
* historical location of devices.</p>
*/
public createTracker(
args: CreateTrackerCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateTrackerCommandOutput>;
public createTracker(
args: CreateTrackerCommandInput,
cb: (err: any, data?: CreateTrackerCommandOutput) => void
): void;
public createTracker(
args: CreateTrackerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateTrackerCommandOutput) => void
): void;
public createTracker(
args: CreateTrackerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTrackerCommandOutput) => void),
cb?: (err: any, data?: CreateTrackerCommandOutput) => void
): Promise<CreateTrackerCommandOutput> | void {
const command = new CreateTrackerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a geofence collection from your AWS account.</p>
* <note>
* <p>This operation deletes the resource permanently. If the geofence collection is the
* target of a tracker resource, the devices will no longer be monitored.</p>
* </note>
*/
public deleteGeofenceCollection(
args: DeleteGeofenceCollectionCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteGeofenceCollectionCommandOutput>;
public deleteGeofenceCollection(
args: DeleteGeofenceCollectionCommandInput,
cb: (err: any, data?: DeleteGeofenceCollectionCommandOutput) => void
): void;
public deleteGeofenceCollection(
args: DeleteGeofenceCollectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteGeofenceCollectionCommandOutput) => void
): void;
public deleteGeofenceCollection(
args: DeleteGeofenceCollectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteGeofenceCollectionCommandOutput) => void),
cb?: (err: any, data?: DeleteGeofenceCollectionCommandOutput) => void
): Promise<DeleteGeofenceCollectionCommandOutput> | void {
const command = new DeleteGeofenceCollectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a map resource from your AWS account.</p>
* <note>
* <p>This operation deletes the resource permanently. If the map is being used in an application,
* the map may not render.</p>
* </note>
*/
public deleteMap(args: DeleteMapCommandInput, options?: __HttpHandlerOptions): Promise<DeleteMapCommandOutput>;
public deleteMap(args: DeleteMapCommandInput, cb: (err: any, data?: DeleteMapCommandOutput) => void): void;
public deleteMap(
args: DeleteMapCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteMapCommandOutput) => void
): void;
public deleteMap(
args: DeleteMapCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteMapCommandOutput) => void),
cb?: (err: any, data?: DeleteMapCommandOutput) => void
): Promise<DeleteMapCommandOutput> | void {
const command = new DeleteMapCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a place index resource from your AWS account.</p>
* <note>
* <p>This operation deletes the resource permanently.</p>
* </note>
*/
public deletePlaceIndex(
args: DeletePlaceIndexCommandInput,
options?: __HttpHandlerOptions
): Promise<DeletePlaceIndexCommandOutput>;
public deletePlaceIndex(
args: DeletePlaceIndexCommandInput,
cb: (err: any, data?: DeletePlaceIndexCommandOutput) => void
): void;
public deletePlaceIndex(
args: DeletePlaceIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeletePlaceIndexCommandOutput) => void
): void;
public deletePlaceIndex(
args: DeletePlaceIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePlaceIndexCommandOutput) => void),
cb?: (err: any, data?: DeletePlaceIndexCommandOutput) => void
): Promise<DeletePlaceIndexCommandOutput> | void {
const command = new DeletePlaceIndexCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a route calculator resource from your AWS account.</p>
* <note>
* <p>This operation deletes the resource permanently.</p>
* </note>
*/
public deleteRouteCalculator(
args: DeleteRouteCalculatorCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteRouteCalculatorCommandOutput>;
public deleteRouteCalculator(
args: DeleteRouteCalculatorCommandInput,
cb: (err: any, data?: DeleteRouteCalculatorCommandOutput) => void
): void;
public deleteRouteCalculator(
args: DeleteRouteCalculatorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteRouteCalculatorCommandOutput) => void
): void;
public deleteRouteCalculator(
args: DeleteRouteCalculatorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteRouteCalculatorCommandOutput) => void),
cb?: (err: any, data?: DeleteRouteCalculatorCommandOutput) => void
): Promise<DeleteRouteCalculatorCommandOutput> | void {
const command = new DeleteRouteCalculatorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a tracker resource from your AWS account.</p>
* <note>
* <p>This operation deletes the resource permanently. If the tracker resource is in use, you may
* encounter an error. Make sure that the target resource isn't a dependency for your
* applications.</p>
* </note>
*/
public deleteTracker(
args: DeleteTrackerCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteTrackerCommandOutput>;
public deleteTracker(
args: DeleteTrackerCommandInput,
cb: (err: any, data?: DeleteTrackerCommandOutput) => void
): void;
public deleteTracker(
args: DeleteTrackerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteTrackerCommandOutput) => void
): void;
public deleteTracker(
args: DeleteTrackerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTrackerCommandOutput) => void),
cb?: (err: any, data?: DeleteTrackerCommandOutput) => void
): Promise<DeleteTrackerCommandOutput> | void {
const command = new DeleteTrackerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the geofence collection details.</p>
*/
public describeGeofenceCollection(
args: DescribeGeofenceCollectionCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeGeofenceCollectionCommandOutput>;
public describeGeofenceCollection(
args: DescribeGeofenceCollectionCommandInput,
cb: (err: any, data?: DescribeGeofenceCollectionCommandOutput) => void
): void;
public describeGeofenceCollection(
args: DescribeGeofenceCollectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeGeofenceCollectionCommandOutput) => void
): void;
public describeGeofenceCollection(
args: DescribeGeofenceCollectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeGeofenceCollectionCommandOutput) => void),
cb?: (err: any, data?: DescribeGeofenceCollectionCommandOutput) => void
): Promise<DescribeGeofenceCollectionCommandOutput> | void {
const command = new DescribeGeofenceCollectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the map resource details.</p>
*/
public describeMap(args: DescribeMapCommandInput, options?: __HttpHandlerOptions): Promise<DescribeMapCommandOutput>;
public describeMap(args: DescribeMapCommandInput, cb: (err: any, data?: DescribeMapCommandOutput) => void): void;
public describeMap(
args: DescribeMapCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeMapCommandOutput) => void
): void;
public describeMap(
args: DescribeMapCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeMapCommandOutput) => void),
cb?: (err: any, data?: DescribeMapCommandOutput) => void
): Promise<DescribeMapCommandOutput> | void {
const command = new DescribeMapCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the place index resource details.</p>
*/
public describePlaceIndex(
args: DescribePlaceIndexCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribePlaceIndexCommandOutput>;
public describePlaceIndex(
args: DescribePlaceIndexCommandInput,
cb: (err: any, data?: DescribePlaceIndexCommandOutput) => void
): void;
public describePlaceIndex(
args: DescribePlaceIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribePlaceIndexCommandOutput) => void
): void;
public describePlaceIndex(
args: DescribePlaceIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePlaceIndexCommandOutput) => void),
cb?: (err: any, data?: DescribePlaceIndexCommandOutput) => void
): Promise<DescribePlaceIndexCommandOutput> | void {
const command = new DescribePlaceIndexCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the route calculator resource details.</p>
*/
public describeRouteCalculator(
args: DescribeRouteCalculatorCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeRouteCalculatorCommandOutput>;
public describeRouteCalculator(
args: DescribeRouteCalculatorCommandInput,
cb: (err: any, data?: DescribeRouteCalculatorCommandOutput) => void
): void;
public describeRouteCalculator(
args: DescribeRouteCalculatorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeRouteCalculatorCommandOutput) => void
): void;
public describeRouteCalculator(
args: DescribeRouteCalculatorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRouteCalculatorCommandOutput) => void),
cb?: (err: any, data?: DescribeRouteCalculatorCommandOutput) => void
): Promise<DescribeRouteCalculatorCommandOutput> | void {
const command = new DescribeRouteCalculatorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the tracker resource details.</p>
*/
public describeTracker(
args: DescribeTrackerCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeTrackerCommandOutput>;
public describeTracker(
args: DescribeTrackerCommandInput,
cb: (err: any, data?: DescribeTrackerCommandOutput) => void
): void;
public describeTracker(
args: DescribeTrackerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeTrackerCommandOutput) => void
): void;
public describeTracker(
args: DescribeTrackerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeTrackerCommandOutput) => void),
cb?: (err: any, data?: DescribeTrackerCommandOutput) => void
): Promise<DescribeTrackerCommandOutput> | void {
const command = new DescribeTrackerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes the association between a tracker resource and a geofence collection.</p>
* <note>
* <p>Once you unlink a tracker resource from a geofence collection, the tracker
* positions will no longer be automatically evaluated against geofences.</p>
* </note>
*/
public disassociateTrackerConsumer(
args: DisassociateTrackerConsumerCommandInput,
options?: __HttpHandlerOptions
): Promise<DisassociateTrackerConsumerCommandOutput>;
public disassociateTrackerConsumer(
args: DisassociateTrackerConsumerCommandInput,
cb: (err: any, data?: DisassociateTrackerConsumerCommandOutput) => void
): void;
public disassociateTrackerConsumer(
args: DisassociateTrackerConsumerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisassociateTrackerConsumerCommandOutput) => void
): void;
public disassociateTrackerConsumer(
args: DisassociateTrackerConsumerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateTrackerConsumerCommandOutput) => void),
cb?: (err: any, data?: DisassociateTrackerConsumerCommandOutput) => void
): Promise<DisassociateTrackerConsumerCommandOutput> | void {
const command = new DisassociateTrackerConsumerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves a device's most recent position according to its sample time.</p>
* <note>
* <p>Device positions are deleted after 30 days.</p>
* </note>
*/
public getDevicePosition(
args: GetDevicePositionCommandInput,
options?: __HttpHandlerOptions
): Promise<GetDevicePositionCommandOutput>;
public getDevicePosition(
args: GetDevicePositionCommandInput,
cb: (err: any, data?: GetDevicePositionCommandOutput) => void
): void;
public getDevicePosition(
args: GetDevicePositionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetDevicePositionCommandOutput) => void
): void;
public getDevicePosition(
args: GetDevicePositionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDevicePositionCommandOutput) => void),
cb?: (err: any, data?: GetDevicePositionCommandOutput) => void
): Promise<GetDevicePositionCommandOutput> | void {
const command = new GetDevicePositionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the device position history from a tracker resource within a specified range
* of time.</p>
* <note>
* <p>Device positions are deleted after 30 days.</p>
* </note>
*/
public getDevicePositionHistory(
args: GetDevicePositionHistoryCommandInput,
options?: __HttpHandlerOptions
): Promise<GetDevicePositionHistoryCommandOutput>;
public getDevicePositionHistory(
args: GetDevicePositionHistoryCommandInput,
cb: (err: any, data?: GetDevicePositionHistoryCommandOutput) => void
): void;
public getDevicePositionHistory(
args: GetDevicePositionHistoryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetDevicePositionHistoryCommandOutput) => void
): void;
public getDevicePositionHistory(
args: GetDevicePositionHistoryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDevicePositionHistoryCommandOutput) => void),
cb?: (err: any, data?: GetDevicePositionHistoryCommandOutput) => void
): Promise<GetDevicePositionHistoryCommandOutput> | void {
const command = new GetDevicePositionHistoryCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the geofence details from a geofence collection.</p>
*/
public getGeofence(args: GetGeofenceCommandInput, options?: __HttpHandlerOptions): Promise<GetGeofenceCommandOutput>;
public getGeofence(args: GetGeofenceCommandInput, cb: (err: any, data?: GetGeofenceCommandOutput) => void): void;
public getGeofence(
args: GetGeofenceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetGeofenceCommandOutput) => void
): void;
public getGeofence(
args: GetGeofenceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetGeofenceCommandOutput) => void),
cb?: (err: any, data?: GetGeofenceCommandOutput) => void
): Promise<GetGeofenceCommandOutput> | void {
const command = new GetGeofenceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves glyphs used to display labels on a map.</p>
*/
public getMapGlyphs(
args: GetMapGlyphsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetMapGlyphsCommandOutput>;
public getMapGlyphs(args: GetMapGlyphsCommandInput, cb: (err: any, data?: GetMapGlyphsCommandOutput) => void): void;
public getMapGlyphs(
args: GetMapGlyphsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMapGlyphsCommandOutput) => void
): void;
public getMapGlyphs(
args: GetMapGlyphsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMapGlyphsCommandOutput) => void),
cb?: (err: any, data?: GetMapGlyphsCommandOutput) => void
): Promise<GetMapGlyphsCommandOutput> | void {
const command = new GetMapGlyphsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the sprite sheet corresponding to a map resource. The sprite sheet is a PNG
* image paired with a JSON document describing the offsets of individual icons that will
* be displayed on a rendered map.</p>
*/
public getMapSprites(
args: GetMapSpritesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetMapSpritesCommandOutput>;
public getMapSprites(
args: GetMapSpritesCommandInput,
cb: (err: any, data?: GetMapSpritesCommandOutput) => void
): void;
public getMapSprites(
args: GetMapSpritesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMapSpritesCommandOutput) => void
): void;
public getMapSprites(
args: GetMapSpritesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMapSpritesCommandOutput) => void),
cb?: (err: any, data?: GetMapSpritesCommandOutput) => void
): Promise<GetMapSpritesCommandOutput> | void {
const command = new GetMapSpritesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves the map style descriptor from a map resource. </p>
* <p>The style descriptor contains specifications on how features render on a map. For
* example, what data to display, what order to display the data in, and the style for the
* data. Style descriptors follow the Mapbox Style Specification.</p>
*/
public getMapStyleDescriptor(
args: GetMapStyleDescriptorCommandInput,
options?: __HttpHandlerOptions
): Promise<GetMapStyleDescriptorCommandOutput>;
public getMapStyleDescriptor(
args: GetMapStyleDescriptorCommandInput,
cb: (err: any, data?: GetMapStyleDescriptorCommandOutput) => void
): void;
public getMapStyleDescriptor(
args: GetMapStyleDescriptorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMapStyleDescriptorCommandOutput) => void
): void;
public getMapStyleDescriptor(
args: GetMapStyleDescriptorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMapStyleDescriptorCommandOutput) => void),
cb?: (err: any, data?: GetMapStyleDescriptorCommandOutput) => void
): Promise<GetMapStyleDescriptorCommandOutput> | void {
const command = new GetMapStyleDescriptorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Retrieves a vector data tile from the map resource. Map tiles are used by clients to
* render a map. they're addressed using a grid arrangement with an X coordinate, Y
* coordinate, and Z (zoom) level. </p>
* <p>The origin (0, 0) is the top left of the map. Increasing the zoom level by 1 doubles
* both the X and Y dimensions, so a tile containing data for the entire world at (0/0/0)
* will be split into 4 tiles at zoom 1 (1/0/0, 1/0/1, 1/1/0, 1/1/1).</p>
*/
public getMapTile(args: GetMapTileCommandInput, options?: __HttpHandlerOptions): Promise<GetMapTileCommandOutput>;
public getMapTile(args: GetMapTileCommandInput, cb: (err: any, data?: GetMapTileCommandOutput) => void): void;
public getMapTile(
args: GetMapTileCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMapTileCommandOutput) => void
): void;
public getMapTile(
args: GetMapTileCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMapTileCommandOutput) => void),
cb?: (err: any, data?: GetMapTileCommandOutput) => void
): Promise<GetMapTileCommandOutput> | void {
const command = new GetMapTileCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>A batch request to retrieve all device positions.</p>
*/
public listDevicePositions(
args: ListDevicePositionsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListDevicePositionsCommandOutput>;
public listDevicePositions(
args: ListDevicePositionsCommandInput,
cb: (err: any, data?: ListDevicePositionsCommandOutput) => void
): void;
public listDevicePositions(
args: ListDevicePositionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDevicePositionsCommandOutput) => void
): void;
public listDevicePositions(
args: ListDevicePositionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDevicePositionsCommandOutput) => void),
cb?: (err: any, data?: ListDevicePositionsCommandOutput) => void
): Promise<ListDevicePositionsCommandOutput> | void {
const command = new ListDevicePositionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists geofence collections in your AWS account.</p>
*/
public listGeofenceCollections(
args: ListGeofenceCollectionsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListGeofenceCollectionsCommandOutput>;
public listGeofenceCollections(
args: ListGeofenceCollectionsCommandInput,
cb: (err: any, data?: ListGeofenceCollectionsCommandOutput) => void
): void;
public listGeofenceCollections(
args: ListGeofenceCollectionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListGeofenceCollectionsCommandOutput) => void
): void;
public listGeofenceCollections(
args: ListGeofenceCollectionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListGeofenceCollectionsCommandOutput) => void),
cb?: (err: any, data?: ListGeofenceCollectionsCommandOutput) => void
): Promise<ListGeofenceCollectionsCommandOutput> | void {
const command = new ListGeofenceCollectionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists geofences stored in a given geofence collection.</p>
*/
public listGeofences(
args: ListGeofencesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListGeofencesCommandOutput>;
public listGeofences(
args: ListGeofencesCommandInput,
cb: (err: any, data?: ListGeofencesCommandOutput) => void
): void;
public listGeofences(
args: ListGeofencesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListGeofencesCommandOutput) => void
): void;
public listGeofences(
args: ListGeofencesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListGeofencesCommandOutput) => void),
cb?: (err: any, data?: ListGeofencesCommandOutput) => void
): Promise<ListGeofencesCommandOutput> | void {
const command = new ListGeofencesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists map resources in your AWS account.</p>
*/
public listMaps(args: ListMapsCommandInput, options?: __HttpHandlerOptions): Promise<ListMapsCommandOutput>;
public listMaps(args: ListMapsCommandInput, cb: (err: any, data?: ListMapsCommandOutput) => void): void;
public listMaps(
args: ListMapsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListMapsCommandOutput) => void
): void;
public listMaps(
args: ListMapsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListMapsCommandOutput) => void),
cb?: (err: any, data?: ListMapsCommandOutput) => void
): Promise<ListMapsCommandOutput> | void {
const command = new ListMapsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists place index resources in your AWS account.</p>
*/
public listPlaceIndexes(
args: ListPlaceIndexesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListPlaceIndexesCommandOutput>;
public listPlaceIndexes(
args: ListPlaceIndexesCommandInput,
cb: (err: any, data?: ListPlaceIndexesCommandOutput) => void
): void;
public listPlaceIndexes(
args: ListPlaceIndexesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListPlaceIndexesCommandOutput) => void
): void;
public listPlaceIndexes(
args: ListPlaceIndexesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPlaceIndexesCommandOutput) => void),
cb?: (err: any, data?: ListPlaceIndexesCommandOutput) => void
): Promise<ListPlaceIndexesCommandOutput> | void {
const command = new ListPlaceIndexesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists route calculator resources in your AWS account.</p>
*/
public listRouteCalculators(
args: ListRouteCalculatorsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListRouteCalculatorsCommandOutput>;
public listRouteCalculators(
args: ListRouteCalculatorsCommandInput,
cb: (err: any, data?: ListRouteCalculatorsCommandOutput) => void
): void;
public listRouteCalculators(
args: ListRouteCalculatorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRouteCalculatorsCommandOutput) => void
): void;
public listRouteCalculators(
args: ListRouteCalculatorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRouteCalculatorsCommandOutput) => void),
cb?: (err: any, data?: ListRouteCalculatorsCommandOutput) => void
): Promise<ListRouteCalculatorsCommandOutput> | void {
const command = new ListRouteCalculatorsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns a list of tags that are applied to the specified Amazon Location resource.</p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists geofence collections currently associated to the given tracker resource.</p>
*/
public listTrackerConsumers(
args: ListTrackerConsumersCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTrackerConsumersCommandOutput>;
public listTrackerConsumers(
args: ListTrackerConsumersCommandInput,
cb: (err: any, data?: ListTrackerConsumersCommandOutput) => void
): void;
public listTrackerConsumers(
args: ListTrackerConsumersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTrackerConsumersCommandOutput) => void
): void;
public listTrackerConsumers(
args: ListTrackerConsumersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTrackerConsumersCommandOutput) => void),
cb?: (err: any, data?: ListTrackerConsumersCommandOutput) => void
): Promise<ListTrackerConsumersCommandOutput> | void {
const command = new ListTrackerConsumersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists tracker resources in your AWS account.</p>
*/
public listTrackers(
args: ListTrackersCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTrackersCommandOutput>;
public listTrackers(args: ListTrackersCommandInput, cb: (err: any, data?: ListTrackersCommandOutput) => void): void;
public listTrackers(
args: ListTrackersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTrackersCommandOutput) => void
): void;
public listTrackers(
args: ListTrackersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTrackersCommandOutput) => void),
cb?: (err: any, data?: ListTrackersCommandOutput) => void
): Promise<ListTrackersCommandOutput> | void {
const command = new ListTrackersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Stores a geofence geometry in a given geofence collection, or updates the geometry of
* an existing geofence if a geofence ID is included in the request. </p>
*/
public putGeofence(args: PutGeofenceCommandInput, options?: __HttpHandlerOptions): Promise<PutGeofenceCommandOutput>;
public putGeofence(args: PutGeofenceCommandInput, cb: (err: any, data?: PutGeofenceCommandOutput) => void): void;
public putGeofence(
args: PutGeofenceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutGeofenceCommandOutput) => void
): void;
public putGeofence(
args: PutGeofenceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutGeofenceCommandOutput) => void),
cb?: (err: any, data?: PutGeofenceCommandOutput) => void
): Promise<PutGeofenceCommandOutput> | void {
const command = new PutGeofenceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Reverse geocodes a given coordinate and returns a legible address. Allows you to search
* for Places or points of interest near a given position.</p>
*/
public searchPlaceIndexForPosition(
args: SearchPlaceIndexForPositionCommandInput,
options?: __HttpHandlerOptions
): Promise<SearchPlaceIndexForPositionCommandOutput>;
public searchPlaceIndexForPosition(
args: SearchPlaceIndexForPositionCommandInput,
cb: (err: any, data?: SearchPlaceIndexForPositionCommandOutput) => void
): void;
public searchPlaceIndexForPosition(
args: SearchPlaceIndexForPositionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SearchPlaceIndexForPositionCommandOutput) => void
): void;
public searchPlaceIndexForPosition(
args: SearchPlaceIndexForPositionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SearchPlaceIndexForPositionCommandOutput) => void),
cb?: (err: any, data?: SearchPlaceIndexForPositionCommandOutput) => void
): Promise<SearchPlaceIndexForPositionCommandOutput> | void {
const command = new SearchPlaceIndexForPositionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Geocodes free-form text, such as an address, name, city, or region to allow you to
* search for Places or points of interest. </p>
* <p>Includes the option to apply additional parameters to narrow your list of
* results.</p>
* <note>
* <p>You can search for places near a given position using <code>BiasPosition</code>, or
* filter results within a bounding box using <code>FilterBBox</code>. Providing both
* parameters simultaneously returns an error.</p>
* </note>
*/
public searchPlaceIndexForText(
args: SearchPlaceIndexForTextCommandInput,
options?: __HttpHandlerOptions
): Promise<SearchPlaceIndexForTextCommandOutput>;
public searchPlaceIndexForText(
args: SearchPlaceIndexForTextCommandInput,
cb: (err: any, data?: SearchPlaceIndexForTextCommandOutput) => void
): void;
public searchPlaceIndexForText(
args: SearchPlaceIndexForTextCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SearchPlaceIndexForTextCommandOutput) => void
): void;
public searchPlaceIndexForText(
args: SearchPlaceIndexForTextCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SearchPlaceIndexForTextCommandOutput) => void),
cb?: (err: any, data?: SearchPlaceIndexForTextCommandOutput) => void
): Promise<SearchPlaceIndexForTextCommandOutput> | void {
const command = new SearchPlaceIndexForTextCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Assigns one or more tags (key-value pairs) to the specified Amazon
* Location Service resource.</p>
*
* <p>Tags can help you organize and categorize your resources.
* You can also use them to scope user permissions, by granting a user
* permission to access or change only resources with certain tag values.</p>
*
* <p>You can use the <code>TagResource</code> operation with an Amazon Location Service
* resource that already has tags. If you specify a new tag key for the resource, this tag
* is appended to the tags already associated with the resource. If you specify a tag key
* that's already associated with the resource, the new tag value that you specify replaces
* the previous value for that tag. </p>
*
* <p>You can associate up to 50 tags with a resource.</p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes one or more tags from the specified Amazon Location resource.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified properties of a given geofence collection.</p>
*/
public updateGeofenceCollection(
args: UpdateGeofenceCollectionCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateGeofenceCollectionCommandOutput>;
public updateGeofenceCollection(
args: UpdateGeofenceCollectionCommandInput,
cb: (err: any, data?: UpdateGeofenceCollectionCommandOutput) => void
): void;
public updateGeofenceCollection(
args: UpdateGeofenceCollectionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateGeofenceCollectionCommandOutput) => void
): void;
public updateGeofenceCollection(
args: UpdateGeofenceCollectionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateGeofenceCollectionCommandOutput) => void),
cb?: (err: any, data?: UpdateGeofenceCollectionCommandOutput) => void
): Promise<UpdateGeofenceCollectionCommandOutput> | void {
const command = new UpdateGeofenceCollectionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified properties of a given map resource.</p>
*/
public updateMap(args: UpdateMapCommandInput, options?: __HttpHandlerOptions): Promise<UpdateMapCommandOutput>;
public updateMap(args: UpdateMapCommandInput, cb: (err: any, data?: UpdateMapCommandOutput) => void): void;
public updateMap(
args: UpdateMapCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateMapCommandOutput) => void
): void;
public updateMap(
args: UpdateMapCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateMapCommandOutput) => void),
cb?: (err: any, data?: UpdateMapCommandOutput) => void
): Promise<UpdateMapCommandOutput> | void {
const command = new UpdateMapCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified properties of a given place index resource.</p>
*/
public updatePlaceIndex(
args: UpdatePlaceIndexCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdatePlaceIndexCommandOutput>;
public updatePlaceIndex(
args: UpdatePlaceIndexCommandInput,
cb: (err: any, data?: UpdatePlaceIndexCommandOutput) => void
): void;
public updatePlaceIndex(
args: UpdatePlaceIndexCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdatePlaceIndexCommandOutput) => void
): void;
public updatePlaceIndex(
args: UpdatePlaceIndexCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdatePlaceIndexCommandOutput) => void),
cb?: (err: any, data?: UpdatePlaceIndexCommandOutput) => void
): Promise<UpdatePlaceIndexCommandOutput> | void {
const command = new UpdatePlaceIndexCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified properties for a given route calculator resource.</p>
*/
public updateRouteCalculator(
args: UpdateRouteCalculatorCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateRouteCalculatorCommandOutput>;
public updateRouteCalculator(
args: UpdateRouteCalculatorCommandInput,
cb: (err: any, data?: UpdateRouteCalculatorCommandOutput) => void
): void;
public updateRouteCalculator(
args: UpdateRouteCalculatorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateRouteCalculatorCommandOutput) => void
): void;
public updateRouteCalculator(
args: UpdateRouteCalculatorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateRouteCalculatorCommandOutput) => void),
cb?: (err: any, data?: UpdateRouteCalculatorCommandOutput) => void
): Promise<UpdateRouteCalculatorCommandOutput> | void {
const command = new UpdateRouteCalculatorCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the specified properties of a given tracker resource.</p>
*/
public updateTracker(
args: UpdateTrackerCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateTrackerCommandOutput>;
public updateTracker(
args: UpdateTrackerCommandInput,
cb: (err: any, data?: UpdateTrackerCommandOutput) => void
): void;
public updateTracker(
args: UpdateTrackerCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateTrackerCommandOutput) => void
): void;
public updateTracker(
args: UpdateTrackerCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateTrackerCommandOutput) => void),
cb?: (err: any, data?: UpdateTrackerCommandOutput) => void
): Promise<UpdateTrackerCommandOutput> | void {
const command = new UpdateTrackerCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import { NoomiError } from "./errorfactory";
import { RedisFactory } from "./redisfactory";
import { Util } from "./util";
import { App } from "./application";
/**
* cache item类型,用于cache操作参数传递
*/
interface ICacheItem{
/**
* 键
*/
key:string;
/**
* 子键,当key对应值为map时,存取操作需要设置
*/
subKey?:string;
/**
* 键对应值
*/
value:any;
/**
* 超时时间(秒),为0或不设置,则表示不超时
*/
timeout?:number;
}
/**
* cache配置类型,初始化cache时使用
*/
interface ICacheCfg{
/**
* cache 名
*/
name:string;
/**
* 存储类型 0内存,1redis,默认0,如果应用设置为集群部署,则设置无效(强制为1)
*/
saveType:number;
/**
* redis名,如果saveType=1,则必须设置,默认default
*/
redis?:string;
/**
* 最大空间,默认为0(表示不限制),如果saveType=1,设置无效
*/
maxSize?:number;
}
/**
* Cache类
* @remarks
* 用于处理缓存,支持内存cache和redis cache
*/
export class NCache{
/**
* redis名,saveType为1时存在
*/
redis:string;
/**
* 内存cache对象,saveType=0时存在
*/
memoryCache:MemoryCache;
/**
* cache名字,全局唯一
*/
name:string;
/**
* 存储类型 0内存 1redis
*/
saveType:number;
/**
* @exclude
* redis存储的cache size名字前缀
*/
redisSizeName:string = 'NCACHE_SIZE_';
/**
* @exclude
* redis存储前缀
*/
redisPreName:string = 'NCACHE_';
/**
* @exclude
* timeout redis 前缀
*/
redisTimeout:string = 'NCACHE_TIMEOUT_';
/**
* 构造器
* @param cfg cache初始化参数
*/
constructor(cfg:ICacheCfg){
//如果为App为集群,则saveType为1,否则为设置值
if(App.isCluster){
this.saveType = 1;
}else{
this.saveType = cfg.saveType || 0;
}
this.name = App.appName + '_' + cfg.name;
this.redis = cfg.redis;
if(this.saveType === 0){
this.memoryCache = new MemoryCache(cfg)
}else{
this.redisPreName += this.name + '_';
this.redisTimeout += this.name + '_';
}
}
/**
* 添加值到cache
* @param key 键
* @param value 值
* @param extra 附加信息
* @param timeout 超时时间(秒)
*/
async set(item:ICacheItem,timeout?:number){
//清除undefined和null属性值
let value = item.value;
Object.getOwnPropertyNames(value).forEach((p)=>{
if(value[p] === undefined || value[p] === null){
delete value[p];
}
});
if(this.saveType === 0){ //数据存到内存
this.memoryCache.set(item,timeout);
}else{//数据存到redis
await this.addToRedis(item,timeout);
}
}
/**
* 获取值
* @param key 键
* @param changeExpire 是否更新过期时间
* @returns value或null
*/
async get(key:string,subKey?:string,changeExpire?:boolean):Promise<any>{
let ci:ICacheItem = null;
if(this.saveType === 0){
return this.memoryCache.get(key,subKey,changeExpire);
}else{
return await this.getFromRedis(key,subKey,changeExpire);
}
}
/**
* 获取map,当key对应的存储对象为map时,则获取map,否则为null
* @param key 键
* @param changeExpire 是否更新过期时间
* @return object或null
*/
async getMap(key:string,changeExpire?:boolean):Promise<any>{
let ci:ICacheItem = null;
if(this.saveType === 0){
return this.memoryCache.getMap(key,changeExpire);
}else{
return await this.getMapFromRedis(key,changeExpire);
}
}
/**
* 删除键
* @param key 键
* @param subKey 子键
*/
async del(key:string,subKey?:string){
if(this.saveType === 0){
this.memoryCache.del(key,subKey);
}else{
await RedisFactory.del(this.redis,this.redisPreName + key,subKey);
}
}
/**
* 获取键数组
* @param key 键,可以带通配符
* @returns 键名组成的数组
*/
async getKeys(key:string):Promise<Array<string>>{
if(this.saveType === 0){
return this.memoryCache.getKeys(key);
}else{
let client = RedisFactory.getClient(this.redis);
if(client === null){
throw new NoomiError("2601",this.redis);
}
let arr = client.keys(this.redisPreName + key);
//把前缀去掉
arr.forEach((item,i)=>{
arr[i] = item.substr(this.redisPreName.length);
})
return arr;
}
}
/**
* 是否拥有key
* @param key 键
* @returns 如果存在则返回true,否则返回false
*/
async has(key:string):Promise<boolean>{
if(this.saveType === 0){
return this.memoryCache.has(key);
}else{
return await RedisFactory.has(this.redis,this.redisPreName + key);
}
}
/**
* 从redis获取值
* @param key 键
* @param subKey 子键
* @param changeExpire 是否修改expire
* @returns 键对应的值
*/
private async getFromRedis(key:string,subKey?:string,changeExpire?:boolean):Promise<any>{
let timeout:number = 0;
if(changeExpire){
let ts:string = await RedisFactory.get(this.redis,{
pre:this.redisTimeout,
key:key
});
if(ts !== null){
timeout = parseInt(ts);
}
}
let value = await RedisFactory.get(this.redis,{
pre:this.redisPreName,
key:key,
subKey:subKey,
timeout:timeout
});
return value||null;
}
/**
* 从redis获取map
* @param key 键
* @apram subKey 子键
* @param changeExpire 是否修改expire
* @returns object或null
*/
private async getMapFromRedis(key:string,changeExpire?:boolean):Promise<any>{
let timeout:number = 0;
//超时修改expire
if(changeExpire){
let ts:string = await RedisFactory.get(this.redis,{
pre:this.redisTimeout,
key:key
});
if(ts !== null){
timeout = parseInt(ts);
}
}
let value = await RedisFactory.getMap(this.redis,{
key:key,
pre:this.redisPreName,
timeout:timeout
});
return value||null;
}
/**
* 存到值redis
* @param item cache item
* @param timeout 超时时间
*/
private async addToRedis(item:ICacheItem,timeout?:number){
//存储timeout
if(typeof timeout==='number' && timeout>0){
await RedisFactory.set(
this.redis,
{
pre:this.redisTimeout,
key:item.key,
value:timeout
}
);
}
//存储值
await RedisFactory.set(
this.redis,
{
pre:this.redisPreName,
key:item.key,
subKey:item.subKey,
value:item.value,
timeout:timeout
}
);
}
}
/**
* @exclude
* 内存存储项类
*/
class MemoryItem{
/**
* 键
*/
key:string;
/**
* 类型0 字符串 1 map
*/
type:number;
/**
* 创建时间
*/
createTime:number;
/**
* 超时时间(秒)
*/
timeout:number;
/**
* 过期时间
*/
expire:number;
/**
* 使用记录,用于LRU置换,记录最近5次访问时间
*/
useRcds:Array<any>;
/**
* 最近最久使用值,值越大越不淘汰
*/
LRU:number;
/**
* 值
*/
value:any;
/**
* 存储空间
*/
size:number;
/**
* 构造器
* @param timeout 超时时间
*/
constructor(timeout?:number){
this.createTime = new Date().getTime();
if(timeout && typeof timeout === 'number'){
this.timeout = timeout*1000;
this.expire = this.createTime + this.timeout;
}
this.size = 0;
this.useRcds = [];
this.LRU = 1;
}
}
/**
* @exclude
* 内存cache类
* 用于管理内存存储相关对象
*/
class MemoryCache{
/**
* 缓存最大size
*/
maxSize:number;
/**
* 附加size(对象)
*/
extraSize:number;
/**
* 存储总map
*/
storeMap:Map<string,any>;
/**
* 当前使用大小
*/
size:number;
/**
* 构造器
* @param cfg
*/
constructor(cfg:ICacheCfg){
this.storeMap = new Map();
this.maxSize = cfg.maxSize;
this.size = 0;
}
/**
* 往缓存中存值
* @param item cache item
* @param timeout 超时时间
*/
set(item:ICacheItem,timeout?:number){
//检查空间并清理
this.checkAndClean(item);
let ci:MemoryItem = this.storeMap.get(item.key);
if(ci === undefined){
ci = new MemoryItem(timeout);
this.storeMap.set(item.key,ci);
}
if(item.subKey){//子键
if(ci.value){
//如果key的value不是对象,不能设置subkey
if(typeof ci.value !== 'object'){
throw new NoomiError("3010");
}
}else{
ci.value = Object.create(null);
}
let v:string;
//转字符串
if(typeof item.value === 'object'){
v = JSON.stringify(item.value);
}else{
v = item.value + '';
}
//保留原size
let si:number = ci.size;
if(ci.value[item.subKey]){
ci.size -= this.getRealSize(ci.value[item.subKey]);
}
ci.value[item.subKey] = v;
ci.size += this.getRealSize(item.value);
//更新cache size
this.size += ci.size - si;
}else{
let size:number = this.getRealSize(item.value);
if(typeof item.value === 'object'){
ci.size = size;
//新建value object
if(!ci.value){
ci.value = Object.create(null);
}
//追加属性
for(let k of Object.getOwnPropertyNames(item.value)){
ci.value[k] = item.value[k];
}
this.size += size;
}else{
let si:number = 0;
if(ci){
//保留原size
si = ci.size;
}else{
ci = new MemoryItem(timeout);
this.storeMap.set(item.key,ci);
}
ci.size += size - si;
ci.value = item.value;
this.size += size-si;
}
}
}
/**
* 从cache取值
* @param key 键
* @param subKey 子键
* @param changeExpire 是否更新超时时间
*/
get(key:string,subKey?:string,changeExpire?:boolean){
if(!this.storeMap.has(key)){
return null;
}
let mi:MemoryItem = this.storeMap.get(key);
const ct:number = new Date().getTime();
if(mi.expire > 0 && mi.expire < ct){
this.storeMap.delete(key);
this.size -= mi.size;
mi = null;
return null;
}
this.changeLastUse(mi);
if(subKey){
if(typeof mi.value === 'object'){
return mi.value[subKey]||null;
}
return null;
}else{
return mi.value;
}
}
/**
* 获取map
* @param key 键
* @param changeExpire 是否更新过期时间
* @return object或null
*/
getMap(key:string,changeExpire?:boolean):Promise<any>{
if(!this.storeMap.has(key)){
return null;
}
let mi:MemoryItem = this.storeMap.get(key);
if(typeof mi.value !== 'object'){
return null;
}
const ct:number = new Date().getTime();
if(mi.expire > 0 && mi.expire < ct){
this.storeMap.delete(key);
this.size -= mi.size;
mi = null;
return null;
}
this.changeLastUse(mi);
return mi.value;
}
/**
* 获取键数组
* @param key 键,可以带通配符
* @returns 键名数组
*/
getKeys(key:string):Array<string>{
let keys = this.storeMap.keys();
let reg:RegExp = Util.toReg(key);
let k:string;
let arr:Array<string> = [];
for(let k of keys){
if(reg.test(k)){
arr.push(k);
}
}
return arr;
}
/**
* 删除键
* @param key 键
* @param subKey 子键
*/
del(key:string,subKey?:string){
let mi:MemoryItem = this.storeMap.get(key);
if(!mi){
return;
}
if(!subKey){
this.size -= mi.size;
this.storeMap.delete(key);
mi = null;
}else{ //删除子键
let v = mi.value[subKey];
if(v){
mi.size -= this.getRealSize(v);
delete mi.value[subKey];
}
}
}
/**
* 是否存在键
* @param key 键
* @return 存在则返回true,否则返回false
*/
has(key:string):boolean{
return this.storeMap.has(key);
}
/**
* 修改最后使用状态
* @param item memory item
* @param changeExpire 释放修改expire
*/
changeLastUse(item:MemoryItem,changeExpire?:boolean){
let ct:number = new Date().getTime();
//修改过期时间
if(changeExpire && item.timeout){
item.expire = ct + item.timeout * 1000;
}
//最大长度为5
if(item.useRcds.length===5){
item.useRcds.shift();
}
item.useRcds.push(ct);
//计算lru
this.cacLRU(item);
}
/**
* 获取值实际所占size
* @param value 待检测值
* @return 值所占空间大小
*/
getRealSize(value:any):number{
let tp = typeof value;
switch(tp){
case 'string':
return Buffer.byteLength(value);
case 'number':
return 8;
case 'boolean':
return 2;
case 'object':
let len:number = 0;
for(let p of Object.getOwnPropertyNames(value)){
len += this.getRealSize(value[p]);
}
return len;
default:
return 4;
}
}
/**
* 清理缓存
* @param size 清理大小,为0仅清除超时元素
*/
cleanup(size:number){
//无可清理对象
if(this.storeMap.size === 0){
return;
}
let ct = new Date().getTime();
//清理超时的
for(let item of this.storeMap){
let key:string = item[0];
let mi:MemoryItem = item[1];
if(mi.expire>0 && mi.expire<ct){
this.storeMap.delete(key);
this.size -= mi.size;
size -= mi.size;
mi = null;
}
}
//重复清理直到size符合要求
while(size>0){
size -= this.clearByLRU();
}
}
/**
* 通过lru进行清理
* @return 清理的尺寸
*/
clearByLRU(){
//随机取m个,删除其中lru最小的n个
let delArr:Array<any> = [];
let keys = this.storeMap.keys();
//避免 m > stormap.size
const m = this.storeMap.size>=10?10:this.storeMap.size;
const n = 3;
//10个随机位置
let indexes=[];
for(let i=0;i<m;i++){
indexes.push(this.storeMap.size * Math.random()|0);
}
//遍历,找到m个存储键
for(let i=0;i<this.storeMap.size;i++){
let k = keys.next();
let ind;
if((ind = indexes.indexOf(i)) !== -1){
let d = this.storeMap.get(k.value);
delArr.push({
key:k.value,
lru:d.LRU,
size:d.size
});
indexes.splice(ind,1);
if(indexes.length===0){
break;
}
}
}
//降序排序
delArr.sort((a,b)=>{
return b.lru - a.lru;
});
//释放前n个
let size:number = 0;
for(let i=0;i<n;i++){
size += delArr[i].size;
this.storeMap.delete(delArr[i].key);
}
return size;
}
/**
* 检查和清理空间
* @param item cacheitem
*/
checkAndClean(item:ICacheItem){
let size:number = this.getRealSize(item.value);
if(this.maxSize>0 && size + this.size>this.maxSize){
this.cleanup(size + this.size - this.maxSize);
if(size + this.size > this.maxSize){
throw new NoomiError("3002");
}
}
}
/**
* 计算LRU
* timeout 的权重为5(先保证timeout由时间去清理)
* right = sum(1-(当前时间-使用记录)/当前时间) + timeout?5:0
* @param item 待计算的内存 item
*/
cacLRU(item:MemoryItem){
let ct = new Date().getTime();
let right:number = item.timeout>0?5:0;
for(let i=0;i<item.useRcds.length;i++){
right += 1-(ct-item.useRcds[i])/ct;
}
item.LRU = right;
}
} | the_stack |
import Color from '../style-spec/util/color';
import type Context from './context';
import type {
BlendFuncType,
BlendEquationType,
ColorMaskType,
DepthRangeType,
DepthMaskType,
StencilFuncType,
StencilOpType,
DepthFuncType,
TextureUnitType,
ViewportType,
CullFaceModeType,
FrontFaceType,
} from './types';
export interface Value<T> {
current: T;
default: T;
dirty: boolean;
get(): T;
setDefault(): void;
set(value: T): void;
}
class BaseValue<T> implements Value<T> {
gl: WebGLRenderingContext;
current: T;
default: T;
dirty: boolean;
constructor(context: Context) {
this.gl = context.gl;
this.default = this.getDefault();
this.current = this.default;
this.dirty = false;
}
get(): T {
return this.current;
}
set(value: T) { // eslint-disable-line
// overridden in child classes;
}
getDefault(): T {
return this.default; // overriden in child classes
}
setDefault() {
this.set(this.default);
}
}
export class ClearColor extends BaseValue<Color> {
getDefault(): Color {
return Color.transparent;
}
set(v: Color) {
const c = this.current;
if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;
this.gl.clearColor(v.r, v.g, v.b, v.a);
this.current = v;
this.dirty = false;
}
}
export class ClearDepth extends BaseValue<number> {
getDefault(): number {
return 1;
}
set(v: number) {
if (v === this.current && !this.dirty) return;
this.gl.clearDepth(v);
this.current = v;
this.dirty = false;
}
}
export class ClearStencil extends BaseValue<number> {
getDefault(): number {
return 0;
}
set(v: number) {
if (v === this.current && !this.dirty) return;
this.gl.clearStencil(v);
this.current = v;
this.dirty = false;
}
}
export class ColorMask extends BaseValue<ColorMaskType> {
getDefault(): ColorMaskType {
return [true, true, true, true];
}
set(v: ColorMaskType) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;
this.gl.colorMask(v[0], v[1], v[2], v[3]);
this.current = v;
this.dirty = false;
}
}
export class DepthMask extends BaseValue<DepthMaskType> {
getDefault(): DepthMaskType {
return true;
}
set(v: DepthMaskType): void {
if (v === this.current && !this.dirty) return;
this.gl.depthMask(v);
this.current = v;
this.dirty = false;
}
}
export class StencilMask extends BaseValue<number> {
getDefault(): number {
return 0xFF;
}
set(v: number): void {
if (v === this.current && !this.dirty) return;
this.gl.stencilMask(v);
this.current = v;
this.dirty = false;
}
}
export class StencilFunc extends BaseValue<StencilFuncType> {
getDefault(): StencilFuncType {
return {
func: this.gl.ALWAYS,
ref: 0,
mask: 0xFF
};
}
set(v: StencilFuncType): void {
const c = this.current;
if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) return;
this.gl.stencilFunc(v.func, v.ref, v.mask);
this.current = v;
this.dirty = false;
}
}
export class StencilOp extends BaseValue<StencilOpType> {
getDefault(): StencilOpType {
const gl = this.gl;
return [gl.KEEP, gl.KEEP, gl.KEEP];
}
set(v: StencilOpType) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) return;
this.gl.stencilOp(v[0], v[1], v[2]);
this.current = v;
this.dirty = false;
}
}
export class StencilTest extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) {
gl.enable(gl.STENCIL_TEST);
} else {
gl.disable(gl.STENCIL_TEST);
}
this.current = v;
this.dirty = false;
}
}
export class DepthRange extends BaseValue<DepthRangeType> {
getDefault(): DepthRangeType {
return [0, 1];
}
set(v: DepthRangeType) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;
this.gl.depthRange(v[0], v[1]);
this.current = v;
this.dirty = false;
}
}
export class DepthTest extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) {
gl.enable(gl.DEPTH_TEST);
} else {
gl.disable(gl.DEPTH_TEST);
}
this.current = v;
this.dirty = false;
}
}
export class DepthFunc extends BaseValue<DepthFuncType> {
getDefault(): DepthFuncType {
return this.gl.LESS;
}
set(v: DepthFuncType) {
if (v === this.current && !this.dirty) return;
this.gl.depthFunc(v);
this.current = v;
this.dirty = false;
}
}
export class Blend extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) {
gl.enable(gl.BLEND);
} else {
gl.disable(gl.BLEND);
}
this.current = v;
this.dirty = false;
}
}
export class BlendFunc extends BaseValue<BlendFuncType> {
getDefault(): BlendFuncType {
const gl = this.gl;
return [gl.ONE, gl.ZERO];
}
set(v: BlendFuncType) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;
this.gl.blendFunc(v[0], v[1]);
this.current = v;
this.dirty = false;
}
}
export class BlendColor extends BaseValue<Color> {
getDefault(): Color {
return Color.transparent;
}
set(v: Color) {
const c = this.current;
if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;
this.gl.blendColor(v.r, v.g, v.b, v.a);
this.current = v;
this.dirty = false;
}
}
export class BlendEquation extends BaseValue<BlendEquationType> {
getDefault(): BlendEquationType {
return this.gl.FUNC_ADD;
}
set(v: BlendEquationType) {
if (v === this.current && !this.dirty) return;
this.gl.blendEquation(v);
this.current = v;
this.dirty = false;
}
}
export class CullFace extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) {
gl.enable(gl.CULL_FACE);
} else {
gl.disable(gl.CULL_FACE);
}
this.current = v;
this.dirty = false;
}
}
export class CullFaceSide extends BaseValue<CullFaceModeType> {
getDefault(): CullFaceModeType {
return this.gl.BACK;
}
set(v: CullFaceModeType) {
if (v === this.current && !this.dirty) return;
this.gl.cullFace(v);
this.current = v;
this.dirty = false;
}
}
export class FrontFace extends BaseValue<FrontFaceType> {
getDefault(): FrontFaceType {
return this.gl.CCW;
}
set(v: FrontFaceType) {
if (v === this.current && !this.dirty) return;
this.gl.frontFace(v);
this.current = v;
this.dirty = false;
}
}
export class Program extends BaseValue<WebGLProgram> {
getDefault(): WebGLProgram {
return null;
}
set(v?: WebGLProgram | null) {
if (v === this.current && !this.dirty) return;
this.gl.useProgram(v);
this.current = v;
this.dirty = false;
}
}
export class ActiveTextureUnit extends BaseValue<TextureUnitType> {
getDefault(): TextureUnitType {
return this.gl.TEXTURE0;
}
set(v: TextureUnitType) {
if (v === this.current && !this.dirty) return;
this.gl.activeTexture(v);
this.current = v;
this.dirty = false;
}
}
export class Viewport extends BaseValue<ViewportType> {
getDefault(): ViewportType {
const gl = this.gl;
return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight];
}
set(v: ViewportType) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;
this.gl.viewport(v[0], v[1], v[2], v[3]);
this.current = v;
this.dirty = false;
}
}
export class BindFramebuffer extends BaseValue<WebGLFramebuffer> {
getDefault(): WebGLFramebuffer {
return null;
}
set(v?: WebGLFramebuffer | null) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, v);
this.current = v;
this.dirty = false;
}
}
export class BindRenderbuffer extends BaseValue<WebGLRenderbuffer> {
getDefault(): WebGLRenderbuffer {
return null;
}
set(v?: WebGLRenderbuffer | null) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindRenderbuffer(gl.RENDERBUFFER, v);
this.current = v;
this.dirty = false;
}
}
export class BindTexture extends BaseValue<WebGLTexture> {
getDefault(): WebGLTexture {
return null;
}
set(v?: WebGLTexture | null) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, v);
this.current = v;
this.dirty = false;
}
}
export class BindVertexBuffer extends BaseValue<WebGLBuffer> {
getDefault(): WebGLBuffer {
return null;
}
set(v?: WebGLBuffer | null) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, v);
this.current = v;
this.dirty = false;
}
}
export class BindElementBuffer extends BaseValue<WebGLBuffer> {
getDefault(): WebGLBuffer {
return null;
}
set(v?: WebGLBuffer | null) {
// Always rebind
const gl = this.gl;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);
this.current = v;
this.dirty = false;
}
}
export class BindVertexArrayOES extends BaseValue<any> {
vao: any;
constructor(context: Context) {
super(context);
this.vao = context.extVertexArrayObject;
}
getDefault(): any {
return null;
}
set(v: any) {
if (!this.vao || v === this.current && !this.dirty) return;
this.vao.bindVertexArrayOES(v);
this.current = v;
this.dirty = false;
}
}
export class PixelStoreUnpack extends BaseValue<number> {
getDefault(): number {
return 4;
}
set(v: number) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);
this.current = v;
this.dirty = false;
}
}
export class PixelStoreUnpackPremultiplyAlpha extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean): void {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, ((v as any)));
this.current = v;
this.dirty = false;
}
}
export class PixelStoreUnpackFlipY extends BaseValue<boolean> {
getDefault(): boolean {
return false;
}
set(v: boolean): void {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, ((v as any)));
this.current = v;
this.dirty = false;
}
}
class FramebufferAttachment<T> extends BaseValue<T> {
parent: WebGLFramebuffer;
context: Context;
constructor(context: Context, parent: WebGLFramebuffer) {
super(context);
this.context = context;
this.parent = parent;
}
getDefault() {
return null;
}
}
export class ColorAttachment extends FramebufferAttachment<WebGLTexture> {
setDirty() {
this.dirty = true;
}
set(v?: WebGLTexture | null): void {
if (v === this.current && !this.dirty) return;
this.context.bindFramebuffer.set(this.parent);
// note: it's possible to attach a renderbuffer to the color
// attachment point, but thus far MBGL only uses textures for color
const gl = this.gl;
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);
this.current = v;
this.dirty = false;
}
}
export class DepthAttachment extends FramebufferAttachment<WebGLRenderbuffer> {
set(v?: WebGLRenderbuffer | null): void {
if (v === this.current && !this.dirty) return;
this.context.bindFramebuffer.set(this.parent);
// note: it's possible to attach a texture to the depth attachment
// point, but thus far MBGL only uses renderbuffers for depth
const gl = this.gl;
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v);
this.current = v;
this.dirty = false;
}
} | the_stack |
import nock from 'nock';
import Resolution, {
ResolutionError,
ResolutionErrorCode,
UnclaimedDomainResponse,
} from '../index';
import {
BlockchainType,
DnsRecordType,
JsonRpcPayload,
NamingServiceName,
} from '../types/publicTypes';
import {JsonRpcProvider, InfuraProvider} from '@ethersproject/providers';
import Web3HttpProvider from 'web3-providers-http';
import Web3WsProvider from 'web3-providers-ws';
import Web3V027Provider from 'web3-0.20.7/lib/web3/httpprovider';
import {
expectResolutionErrorCode,
expectSpyToBeCalled,
mockAsyncMethods,
protocolLink,
ProviderProtocol,
caseMock,
mockAsyncMethod,
CryptoDomainWithTwitterVerification,
skipItInLive,
isLive,
CryptoDomainWithUsdtMultiChainRecords,
expectConfigurationErrorCode,
CryptoDomainWithAllRecords,
} from './helpers';
import {RpcProviderTestCases} from './providerMockData';
import fetch, {FetchError} from 'node-fetch';
import Uns from '../Uns';
import Zns from '../Zns';
import Ens from '../Ens';
import FetchProvider from '../FetchProvider';
import {ConfigurationErrorCode} from '../errors/configurationError';
import {HTTPProvider} from '@zilliqa-js/core';
import {Eip1993Factories as Eip1193Factories} from '../utils/Eip1993Factories';
import UnsConfig from '../config/uns-config.json';
import EthereumContract from '../contracts/EthereumContract';
let resolution: Resolution;
let uns: Uns;
let zns: Zns;
let ens: Ens;
beforeEach(() => {
nock.cleanAll();
jest.restoreAllMocks();
resolution = new Resolution({
sourceConfig: {
uns: {url: protocolLink(), network: 'rinkeby'},
ens: {url: protocolLink(), network: 'rinkeby'},
zns: {network: 'testnet'},
},
});
uns = resolution.serviceMap[NamingServiceName.UNS] as unknown as Uns;
ens = resolution.serviceMap[NamingServiceName.ENS] as unknown as Ens;
zns = resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns;
});
describe('Resolution', () => {
describe('.Basic setup', () => {
it('should work with autonetwork url configuration', async () => {
const rinkebyUrl = protocolLink();
const goerliUrl = rinkebyUrl.replace('rinkeby', 'goerli');
// mocking getNetworkConfigs because no access to inner provider.request
const UnsGetNetworkOriginal = Uns.autoNetwork;
const EnsGetNetworkOriginal = Ens.autoNetwork;
if (!isLive()) {
Uns.autoNetwork = jest.fn().mockReturnValue(
new Uns({
network: 'rinkeby',
provider: new FetchProvider(NamingServiceName.UNS, rinkebyUrl),
}),
);
Ens.autoNetwork = jest.fn().mockReturnValue(
new Ens({
network: 'goerli',
provider: new FetchProvider(NamingServiceName.ENS, goerliUrl),
}),
);
}
const resolution = await Resolution.autoNetwork({
uns: {url: rinkebyUrl},
ens: {url: goerliUrl},
});
// We need to manually restore the function as jest.restoreAllMocks and simillar works only with spyOn
Uns.autoNetwork = UnsGetNetworkOriginal;
Ens.autoNetwork = EnsGetNetworkOriginal;
expect(
(resolution.serviceMap[NamingServiceName.UNS] as unknown as Uns)
.network,
).toBe(4);
expect(
(resolution.serviceMap[NamingServiceName.ENS] as unknown as Ens)
.network,
).toBe(5);
});
it('should not work with invalid proxyReader configuration', async () => {
const mainnetUrl = protocolLink();
const customNetwork = 'goerli';
const goerliUrl = mainnetUrl.replace('mainnet', customNetwork);
expectConfigurationErrorCode(() => {
new Uns({
network: customNetwork,
url: goerliUrl,
proxyReaderAddress: '0x012312931293',
});
}, ConfigurationErrorCode.InvalidConfigurationField);
});
it('should work with proxyReader configuration', async () => {
const mainnetUrl = protocolLink();
const customNetwork = 'goerli';
const goerliUrl = mainnetUrl.replace('mainnet', customNetwork);
const uns = new Uns({
network: customNetwork,
url: goerliUrl,
proxyReaderAddress: '0xe7474D07fD2FA286e7e0aa23cd107F8379025037',
});
expect(uns).toBeDefined();
});
it('should not work with invalid proxyReader configuration 2', async () => {
const mainnetUrl = protocolLink();
const customNetwork = 'goerli';
const provider = new FetchProvider(NamingServiceName.UNS, mainnetUrl);
expectConfigurationErrorCode(() => {
new Uns({
network: customNetwork,
provider,
proxyReaderAddress: '0x012312931293',
});
}, ConfigurationErrorCode.InvalidConfigurationField);
});
it('should work with custom network configuration with provider', async () => {
const mainnetUrl = protocolLink();
const customNetwork = 'goerli';
const provider = new FetchProvider(NamingServiceName.UNS, mainnetUrl);
const uns = new Uns({
network: customNetwork,
provider,
proxyReaderAddress: '0xe7447Fdd52FA286e7e0aa23cd107F83790250897',
});
expect(uns).toBeDefined();
});
it('should work with autonetwork provider configuration', async () => {
const provider = new FetchProvider(
'UDAPI',
protocolLink().replace('rinkeby', 'mainnet'),
);
const spy = mockAsyncMethod(provider, 'request', '1');
const resolution = await Resolution.autoNetwork({
uns: {provider},
ens: {provider},
});
expect(spy).toBeCalledTimes(2);
expect(
(resolution.serviceMap[NamingServiceName.UNS] as unknown as Uns)
.network,
).toBe(1);
expect(
(resolution.serviceMap[NamingServiceName.ENS] as unknown as Ens)
.network,
).toBe(1);
});
it('should fail because provided url failled net_version call', async () => {
const mockedProvider = new FetchProvider(
NamingServiceName.UNS,
'https://google.com',
);
const providerSpy = mockAsyncMethod(
mockedProvider,
'request',
new ResolutionError(ResolutionErrorCode.ServiceProviderError, {
providerMessage:
'Request to https://google.com failed with responce status 405',
}),
);
const factorySpy = mockAsyncMethod(
FetchProvider,
'factory',
() => mockedProvider,
);
try {
await Resolution.autoNetwork({
uns: {url: 'https://google.com'},
});
} catch (error) {
expect(error).toBeInstanceOf(ResolutionError);
expect(error.message).toBe(
'< Request to https://google.com failed with responce status 405 >',
);
}
expectSpyToBeCalled([factorySpy, providerSpy]);
});
it('should fail because provided provider failed to make a net_version call', async () => {
const mockedProvider = new FetchProvider(
NamingServiceName.ENS,
'http://unstoppabledomains.com',
);
const providerSpy = mockAsyncMethod(
mockedProvider,
'request',
new FetchError(
'invalid json response body at https://unstoppabledomains.com/ reason: Unexpected token < in JSON at position 0',
'invalid_json',
),
);
try {
await Resolution.autoNetwork({
ens: {provider: mockedProvider},
});
} catch (error) {
expect(error).toBeInstanceOf(FetchError);
expect(error.message).toBe(
'invalid json response body at https://unstoppabledomains.com/ reason: Unexpected token < in JSON at position 0',
);
}
expect(providerSpy).toBeCalled();
});
it('should fail because of unsupported test network for uns', async () => {
const blockchainUrl = protocolLink().replace('rinkeby', 'ropsten');
const mockedProvider = new FetchProvider(
NamingServiceName.UNS,
blockchainUrl,
);
mockAsyncMethod(mockedProvider, 'request', () => '3');
mockAsyncMethod(FetchProvider, 'factory', () => mockedProvider);
await expectConfigurationErrorCode(
Resolution.autoNetwork({
uns: {url: blockchainUrl},
}),
ConfigurationErrorCode.UnsupportedNetwork,
);
});
skipItInLive('should fail in test development', async () => {
try {
await fetch('https://pokeres.bastionbot.org/images/pokemon/10.png');
} catch (err) {
// nock should prevent all outgoing traffic
expect(err).toBeInstanceOf(FetchError);
return;
}
fail('nock is not configured correctly!');
});
it('should get a valid resolution instance', async () => {
const resolution = Resolution.infura('api-key', {
uns: {network: 'rinkeby'},
ens: {network: 'rinkeby'},
});
uns = resolution.serviceMap[NamingServiceName.UNS] as unknown as Uns;
ens = resolution.serviceMap[NamingServiceName.ENS] as unknown as Ens;
expect(uns.url).toBe(`https://rinkeby.infura.io/v3/api-key`);
expect(ens.url).toBe(`https://rinkeby.infura.io/v3/api-key`);
});
it('should throw on unspecified network', async () => {
const zilliqaProvider = new HTTPProvider('https://api.zilliqa.com');
const provider = Eip1193Factories.fromZilliqaProvider(zilliqaProvider);
expect(() =>
Resolution.fromResolutionProvider(provider, {}),
).toThrowError('< Must specify network for ens, uns, or zns >');
});
it('should create resolution instance from Zilliqa provider', async () => {
const zilliqaProvider = new HTTPProvider('https://api.zilliqa.com');
const provider = Eip1193Factories.fromZilliqaProvider(zilliqaProvider);
const resolutionFromZilliqaProvider =
Resolution.fromZilliqaProvider(provider);
const resolution = new Resolution({
sourceConfig: {
zns: {url: 'https://api.zilliqa.com', network: 'mainnet'},
},
});
expect(
(
resolutionFromZilliqaProvider.serviceMap[
NamingServiceName.ZNS
] as unknown as Zns
).url,
).toEqual(
(resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns).url,
);
expect(
(
resolutionFromZilliqaProvider.serviceMap[
NamingServiceName.ZNS
] as unknown as Zns
).network,
).toEqual(
(resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns)
.network,
);
expect(
(
resolutionFromZilliqaProvider.serviceMap[
NamingServiceName.ZNS
] as unknown as Zns
).registryAddr,
).toEqual(
(resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns)
.registryAddr,
);
});
it('should retrieve record using resolution instance created from Zilliqa provider', async () => {
const zilliqaProvider = new HTTPProvider('https://api.zilliqa.com');
const provider = Eip1193Factories.fromZilliqaProvider(zilliqaProvider);
const resolution = Resolution.fromZilliqaProvider(provider);
zns = resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns;
const spies = mockAsyncMethods(zns, {
allRecords: {
'crypto.ETH.address': '0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
},
});
const ethAddress = await resolution.addr('brad.zil', 'ETH');
expectSpyToBeCalled(spies);
expect(ethAddress).toBe('0x45b31e01AA6f42F0549aD482BE81635ED3149abb');
});
it('provides empty response constant', async () => {
const response = UnclaimedDomainResponse;
expect(response.addresses).toEqual({});
expect(response.meta.owner).toEqual(null);
});
describe('.ServiceName', () => {
it('checks ens service name', () => {
const resolution = new Resolution();
const serviceName = resolution.serviceName('domain.eth');
expect(serviceName).toBe('ENS');
});
it('should resolve gundb chat id', async () => {
const eyes = mockAsyncMethods(uns, {
get: {
resolver: '0x878bC2f3f717766ab69C0A5f9A6144931E61AEd3',
records: {
['gundb.username.value']:
'0x47992daf742acc24082842752fdc9c875c87c56864fee59d8b779a91933b159e48961566eec6bd6ce3ea2441c6cb4f112d0eb8e8855cc9cf7647f0d9c82f00831c',
},
},
});
const gundb = await resolution.chatId('homecakes.crypto');
expectSpyToBeCalled(eyes);
expect(gundb).toBe(
'0x47992daf742acc24082842752fdc9c875c87c56864fee59d8b779a91933b159e48961566eec6bd6ce3ea2441c6cb4f112d0eb8e8855cc9cf7647f0d9c82f00831c',
);
});
describe('.ipfsHash', () => {
skipItInLive(
'should prioritize new keys over depricated ones',
async () => {
const spies = mockAsyncMethods(uns, {
get: {
resolver: '0xA1cAc442Be6673C49f8E74FFC7c4fD746f3cBD0D',
records: {
['dweb.ipfs.hash']: 'new record Ipfs hash',
['ipfs.html.value']: 'old record Ipfs hash',
},
},
});
const hash = await resolution.ipfsHash(CryptoDomainWithAllRecords);
expectSpyToBeCalled(spies);
expect(hash).toBe('new record Ipfs hash');
},
);
skipItInLive(
'should prioritize browser record key over ipfs.redirect_url one',
async () => {
const spies = mockAsyncMethods(uns, {
get: {
resolver: '0xA1cAc442Be6673C49f8E74FFC7c4fD746f3cBD0D',
records: {
['browser.redirect_url']: 'new record redirect url',
['ipfs.redirect_domain.value']: 'old record redirect url',
},
},
});
const redirectUrl = await resolution.httpUrl(
CryptoDomainWithAllRecords,
);
expectSpyToBeCalled(spies);
expect(redirectUrl).toBe('new record redirect url');
},
);
});
describe('serviceName', () => {
it('checks ens service name', () => {
const resolution = new Resolution();
const serviceName = resolution.serviceName('domain.eth');
expect(serviceName).toBe('ENS');
});
it('checks zns service name', () => {
const resolution = new Resolution();
const serviceName = resolution.serviceName('domain.zil');
expect(serviceName).toBe('ZNS');
});
it('checks uns service name', () => {
const resolution = new Resolution();
const serviceName = resolution.serviceName('domain.crypto');
expect(serviceName).toBe('UNS');
});
});
});
describe('.Errors', () => {
it('checks Resolution#addr error #1', async () => {
const resolution = new Resolution();
zns = resolution.serviceMap[NamingServiceName.ZNS] as unknown as Zns;
const spy = mockAsyncMethods(zns, {
getRecordsAddresses: undefined,
});
await expectResolutionErrorCode(
resolution.addr('sdncdoncvdinvcsdncs.zil', 'ZIL'),
ResolutionErrorCode.UnregisteredDomain,
);
expectSpyToBeCalled(spy);
});
it('checks error for email on brad.zil', async () => {
const spies = mockAsyncMethods(zns, {
allRecords: {
'crypto.ETH.address': '0xc101679df8e2d6092da6d7ca9bced5bfeeb5abd8',
'crypto.ZIL.address': 'zil1k78e8zkh79lc47mrpcwqyhdrdkz7ptumk7ud90',
},
});
await expectResolutionErrorCode(
resolution.email('merenkov.zil'),
ResolutionErrorCode.RecordNotFound,
);
expectSpyToBeCalled(spies);
});
describe('.Namehash errors', () => {
it('should be invalid domain', async () => {
const unsInvalidDomain = 'hello..crypto';
const ensInvalidDomain = 'hello..eth';
const znsInvalidDomain = 'hello..zil';
await expectResolutionErrorCode(
() => resolution.namehash(unsInvalidDomain),
ResolutionErrorCode.UnsupportedDomain,
);
await expectResolutionErrorCode(
() => resolution.namehash(ensInvalidDomain),
ResolutionErrorCode.UnsupportedDomain,
);
await expectResolutionErrorCode(
() => resolution.namehash(znsInvalidDomain),
ResolutionErrorCode.UnsupportedDomain,
);
});
});
});
describe('.Records', () => {
describe('.DNS', () => {
skipItInLive('getting dns get', async () => {
const spies = mockAsyncMethods(uns, {
get: {
resolver: '0xBD5F5ec7ed5f19b53726344540296C02584A5237',
records: {
'dns.ttl': '128',
'dns.A': '["10.0.0.1","10.0.0.2"]',
'dns.A.ttl': '90',
'dns.AAAA': '["10.0.0.120"]',
},
},
});
const dnsRecords = await resolution.dns('someTestDomain.crypto', [
DnsRecordType.A,
DnsRecordType.AAAA,
]);
expectSpyToBeCalled(spies);
expect(dnsRecords).toStrictEqual([
{TTL: 90, data: '10.0.0.1', type: 'A'},
{TTL: 90, data: '10.0.0.2', type: 'A'},
{TTL: 128, data: '10.0.0.120', type: 'AAAA'},
]);
});
skipItInLive('should work with others records', async () => {
const spies = mockAsyncMethods(uns, {
get: {
resolver: '0xBD5F5ec7ed5f19b53726344540296C02584A5237',
records: {
'dns.ttl': '128',
'dns.A': '["10.0.0.1","10.0.0.2"]',
'dns.A.ttl': '90',
'dns.AAAA': '["10.0.0.120"]',
['crypto.ETH.address']:
'0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
['crypto.ADA.address']:
'0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
['crypto.ARK.address']:
'0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
},
},
});
const dnsRecords = await resolution.dns('someTestDomain.crypto', [
DnsRecordType.A,
DnsRecordType.AAAA,
]);
expectSpyToBeCalled(spies);
expect(dnsRecords).toStrictEqual([
{TTL: 90, data: '10.0.0.1', type: 'A'},
{TTL: 90, data: '10.0.0.2', type: 'A'},
{TTL: 128, data: '10.0.0.120', type: 'AAAA'},
]);
});
});
describe('.Metadata', () => {
it('checks return of email for testing.zil', async () => {
const spies = mockAsyncMethods(zns, {
allRecords: {
'ipfs.html.hash':
'QmefehFs5n8yQcGCVJnBMY3Hr6aMRHtsoniAhsM1KsHMSe',
'ipfs.html.value':
'QmVaAtQbi3EtsfpKoLzALm6vXphdi2KjMgxEDKeGg6wHu',
'ipfs.redirect_domain.value': 'www.unstoppabledomains.com',
'whois.email.value': 'derainberk@gmail.com',
'whois.for_sale.value': 'true',
},
});
const email = await resolution.email('testing.zil');
expectSpyToBeCalled(spies);
expect(email).toBe('derainberk@gmail.com');
});
});
describe('.Crypto', () => {
it(`domains "brad.crypto" and "Brad.crypto" should return the same results`, async () => {
const eyes = mockAsyncMethods(uns, {
get: {
resolver: '0xBD5F5ec7ed5f19b53726344540296C02584A5237',
records: {
['crypto.ETH.address']:
'0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
},
},
});
const capital = await resolution.addr('Brad.crypto', 'eth');
const lower = await resolution.addr('brad.crypto', 'eth');
expectSpyToBeCalled(eyes, 2);
expect(capital).toStrictEqual(lower);
});
describe('.multichain', () => {
it('should work with usdt on different erc20', async () => {
const erc20Spy = mockAsyncMethod(uns, 'get', {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
records: {
['crypto.USDT.version.ERC20.address']:
'0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
},
});
const erc20 = await resolution.multiChainAddr(
CryptoDomainWithUsdtMultiChainRecords,
'usdt',
'erc20',
);
expect(erc20).toBe('0xe7474D07fD2FA286e7e0aa23cd107F8379085037');
expect(erc20Spy).toBeCalled();
});
it('should work with usdt tron chain', async () => {
const tronSpy = mockAsyncMethod(uns, 'get', {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
records: {
['crypto.USDT.version.TRON.address']:
'TNemhXhpX7MwzZJa3oXvfCjo5pEeXrfN2h',
},
});
const tron = await resolution.multiChainAddr(
CryptoDomainWithUsdtMultiChainRecords,
'usdt',
'tron',
);
expect(tron).toBe('TNemhXhpX7MwzZJa3oXvfCjo5pEeXrfN2h');
expect(tronSpy).toBeCalled();
});
it('should work with usdt omni chain', async () => {
const omniSpy = mockAsyncMethod(uns, 'get', {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
records: {
['crypto.USDT.version.OMNI.address']:
'19o6LvAdCPkjLi83VsjrCsmvQZUirT4KXJ',
},
});
const omni = await resolution.multiChainAddr(
CryptoDomainWithUsdtMultiChainRecords,
'usdt',
'omni',
);
expect(omni).toBe('19o6LvAdCPkjLi83VsjrCsmvQZUirT4KXJ');
expect(omniSpy).toBeCalled();
});
it('should work with usdt eos chain', async () => {
const eosSpy = mockAsyncMethod(uns, 'get', {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
records: {
['crypto.USDT.version.EOS.address']: 'letsminesome',
},
});
const eos = await resolution.multiChainAddr(
CryptoDomainWithUsdtMultiChainRecords,
'usdt',
'eos',
);
expect(eosSpy).toBeCalled();
expect(eos).toBe('letsminesome');
});
});
});
describe('.Providers', () => {
it('should work with web3HttpProvider', async () => {
// web3-providers-http has problems with type definitions
// We still prefer everything to be statically typed on our end for better mocking
const provider = new (Web3HttpProvider as any)(
protocolLink(),
) as Web3HttpProvider.HttpProvider;
// mock the send function with different implementations (each should call callback right away with different answers)
const eye = mockAsyncMethod(
provider,
'send',
(payload: JsonRpcPayload, callback) => {
const result = caseMock(
payload.params?.[0],
RpcProviderTestCases,
);
callback &&
callback(null, {
jsonrpc: '2.0',
id: 1,
result,
});
},
);
const resolution = Resolution.fromWeb3Version1Provider(provider, {
uns: {network: 'rinkeby'},
});
const ethAddress = await resolution.addr('brad.crypto', 'ETH');
// expect each mock to be called at least once.
expectSpyToBeCalled([eye]);
expect(ethAddress).toBe('0x8aaD44321A86b170879d7A244c1e8d360c99DdA8');
});
it('should work with webSocketProvider', async () => {
// web3-providers-ws has problems with type definitions
// We still prefer everything to be statically typed on our end for better mocking
const provider = new (Web3WsProvider as any)(
protocolLink(ProviderProtocol.wss),
) as Web3WsProvider.WebsocketProvider;
const eye = mockAsyncMethod(provider, 'send', (payload, callback) => {
const result = caseMock(payload.params?.[0], RpcProviderTestCases);
callback(null, {
jsonrpc: '2.0',
id: 1,
result,
});
});
const resolution = Resolution.fromWeb3Version1Provider(provider, {
uns: {network: 'rinkeby'},
});
const ethAddress = await resolution.addr('brad.crypto', 'ETH');
provider.disconnect(1000, 'end of test');
expectSpyToBeCalled([eye]);
expect(ethAddress).toBe('0x8aaD44321A86b170879d7A244c1e8d360c99DdA8');
});
it('should work for ethers jsonrpc provider', async () => {
const provider = new JsonRpcProvider(
protocolLink(ProviderProtocol.http),
'rinkeby',
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'rinkeby'},
});
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const ethAddress = await resolution.addr('brad.crypto', 'ETH');
expectSpyToBeCalled([eye]);
expect(ethAddress).toBe('0x8aaD44321A86b170879d7A244c1e8d360c99DdA8');
});
it('should work with ethers default provider', async () => {
const provider = new InfuraProvider(
'rinkeby',
'213fff28936343858ca9c5115eff1419',
);
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'rinkeby'},
});
const ethAddress = await resolution.addr('brad.crypto', 'eth');
expectSpyToBeCalled([eye]);
expect(ethAddress).toBe('0x8aaD44321A86b170879d7A244c1e8d360c99DdA8');
});
it('should work with web3@0.20.7 provider', async () => {
const provider = new Web3V027Provider(
protocolLink(ProviderProtocol.http),
5000,
null,
null,
null,
);
const eye = mockAsyncMethod(
provider,
'sendAsync',
(payload: JsonRpcPayload, callback: any) => {
const result = caseMock(
payload.params?.[0],
RpcProviderTestCases,
);
callback(undefined, {
jsonrpc: '2.0',
id: 1,
result,
});
},
);
const resolution = Resolution.fromWeb3Version0Provider(provider, {
uns: {network: 'rinkeby'},
});
const ethAddress = await resolution.addr('brad.crypto', 'eth');
expectSpyToBeCalled([eye]);
expect(ethAddress).toBe('0x8aaD44321A86b170879d7A244c1e8d360c99DdA8');
});
describe('.All-get', () => {
it('should be able to get logs with ethers default provider', async () => {
const provider = new InfuraProvider(
'rinkeby',
'213fff28936343858ca9c5115eff1419',
);
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const eye2 = mockAsyncMethod(provider, 'getLogs', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'rinkeby'},
});
const resp = await resolution.allRecords('brad.crypto');
expectSpyToBeCalled([eye], 2);
expectSpyToBeCalled([eye2], 2);
expect(resp).toMatchObject({
'gundb.username.value':
'0x8912623832e174f2eb1f59cc3b587444d619376ad5bf10070e937e0dc22b9ffb2e3ae059e6ebf729f87746b2f71e5d88ec99c1fb3c7c49b8617e2520d474c48e1c',
'ipfs.html.value':
'QmdyBw5oTgCtTLQ18PbDvPL8iaLoEPhSyzD91q9XmgmAjb',
'ipfs.redirect_domain.value':
'https://abbfe6z95qov3d40hf6j30g7auo7afhp.mypinata.cloud/ipfs/Qme54oEzRkgooJbCDr78vzKAWcv6DDEZqRhhDyDtzgrZP6',
'crypto.ETH.address':
'0x8aaD44321A86b170879d7A244c1e8d360c99DdA8',
'gundb.public_key.value':
'pqeBHabDQdCHhbdivgNEc74QO-x8CPGXq4PKWgfIzhY.7WJR5cZFuSyh1bFwx0GWzjmrim0T5Y6Bp0SSK0im3nI',
'crypto.BTC.address':
'bc1q359khn0phg58xgezyqsuuaha28zkwx047c0c3y',
});
});
it('should be able to get logs with jsonProvider', async () => {
const provider = new JsonRpcProvider(
protocolLink(ProviderProtocol.http),
'rinkeby',
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'rinkeby'},
});
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const eye2 = mockAsyncMethod(provider, 'getLogs', (params) => {
// console.log({params, response: caseMock(params, RpcProviderTestCases)});
return Promise.resolve(caseMock(params, RpcProviderTestCases));
});
const resp = await resolution.allRecords('brad.crypto');
expectSpyToBeCalled([eye], 2);
expectSpyToBeCalled([eye2], 2);
expect(resp).toMatchObject({
'gundb.username.value':
'0x8912623832e174f2eb1f59cc3b587444d619376ad5bf10070e937e0dc22b9ffb2e3ae059e6ebf729f87746b2f71e5d88ec99c1fb3c7c49b8617e2520d474c48e1c',
'ipfs.html.value':
'QmdyBw5oTgCtTLQ18PbDvPL8iaLoEPhSyzD91q9XmgmAjb',
'ipfs.redirect_domain.value':
'https://abbfe6z95qov3d40hf6j30g7auo7afhp.mypinata.cloud/ipfs/Qme54oEzRkgooJbCDr78vzKAWcv6DDEZqRhhDyDtzgrZP6',
'crypto.ETH.address':
'0x8aaD44321A86b170879d7A244c1e8d360c99DdA8',
'gundb.public_key.value':
'pqeBHabDQdCHhbdivgNEc74QO-x8CPGXq4PKWgfIzhY.7WJR5cZFuSyh1bFwx0GWzjmrim0T5Y6Bp0SSK0im3nI',
'crypto.BTC.address':
'bc1q359khn0phg58xgezyqsuuaha28zkwx047c0c3y',
});
});
it('should return allNonEmptyRecords', async () => {
const provider = new JsonRpcProvider(
protocolLink(ProviderProtocol.http),
'rinkeby',
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'rinkeby'},
});
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const eye2 = mockAsyncMethod(provider, 'getLogs', (params) => {
return Promise.resolve(caseMock(params, RpcProviderTestCases));
});
// udtestdev-emptyrecords.crypto have 1 empty record and 1 record with value
const response = await resolution.allNonEmptyRecords(
'udtestdev-emptyrecords.crypto',
);
expectSpyToBeCalled([eye], 2);
expectSpyToBeCalled([eye2], 2);
expect(Object.keys(response).length).toBe(1);
});
it('should get standard keys from legacy resolver', async () => {
// There are no legacy providers on testnet
const provider = new InfuraProvider(
'mainnet',
'213fff28936343858ca9c5115eff1419',
);
const eye = mockAsyncMethod(provider, 'call', (params) =>
Promise.resolve(caseMock(params, RpcProviderTestCases)),
);
const resolution = Resolution.fromEthersProvider(provider, {
uns: {network: 'mainnet'},
});
const resp = await resolution.allRecords('monmouthcounty.crypto');
expectSpyToBeCalled([eye], 2);
expect(resp).toMatchObject({
'crypto.BTC.address': '3NwuV8nVT2VKbtCs8evChdiW6kHTHcVpdn',
'crypto.ETH.address':
'0x1C42088b82f6Fa5fB883A14240C4E066dDFf1517',
'crypto.LTC.address': 'MTnTNwKikiMi97Teq8XQRabL9SZ4HjnKNB',
'crypto.ADA.address':
'DdzFFzCqrhsfc3MQvjsLr9BHkaFYeE7BotyTATdETRoSPj6QPiotK4xpcFZk66KVmtr87tvUFTcbTHZRkcdbMR5Ss6jCfzCVtFRMB7WE',
'ipfs.html.value':
'QmYqX8D8SkaF5YcpaWMyi5xM43UEteFiSNKYsjLcdvCWud',
'ipfs.redirect_domain.value':
'https://abbfe6z95qov3d40hf6j30g7auo7afhp.mypinata.cloud/ipfs/QmYqX8D8SkaF5YcpaWMyi5xM43UEteFiSNKYsjLcdvCWud',
});
});
});
it('should get all records using custom networks', async () => {
const resolution = new Resolution({
sourceConfig: {
uns: {
network: 'custom',
proxyReaderAddress:
'0xa6E7cEf2EDDEA66352Fd68E5915b60BDbb7309f5',
url: 'https://mainnet.infura.io/v3/c4bb906ed6904c42b19c95825fe55f39',
},
zns: {
network: 'custom',
registryAddress: 'zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz',
url: 'https://api.zilliqa.com',
},
},
});
const uns = resolution.serviceMap['UNS'] as unknown as Uns;
const zns = resolution.serviceMap['ZNS'] as unknown as Zns;
const unsAllRecordsMock = mockAsyncMethods(uns, {
getStartingBlock: undefined,
resolver: '0x878bC2f3f717766ab69C0A5f9A6144931E61AEd3',
getStandardRecords: {
'crypto.ETH.address':
'0x8aaD44321A86b170879d7A244c1e8d360c99DdA8',
},
});
const unsGetNewKeyMock = mockAsyncMethod(uns, 'getNewKeyEvents', []);
const znsAllRecordsMock = mockAsyncMethods(zns, {
resolver: 'zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz',
getResolverRecords: {
'crypto.ZIL.address':
'zil1yu5u4hegy9v3xgluweg4en54zm8f8auwxu0xxj',
},
});
const znsRecords = await resolution.allRecords('brad.zil');
const unsRecords = await resolution.allRecords('brad.crypto');
expectSpyToBeCalled(znsAllRecordsMock);
expectSpyToBeCalled(unsAllRecordsMock);
expect(unsRecords['crypto.ETH.address']).toEqual(
'0x8aaD44321A86b170879d7A244c1e8d360c99DdA8',
);
expect(znsRecords['crypto.ZIL.address']).toEqual(
'zil1yu5u4hegy9v3xgluweg4en54zm8f8auwxu0xxj',
);
if (isLive()) {
expect(unsGetNewKeyMock).toBeCalledWith(
expect.any(EthereumContract),
resolution.namehash('brad.crypto'),
'0x99a587',
);
} else {
expect(unsGetNewKeyMock).toBeCalledWith(
expect.any(EthereumContract),
resolution.namehash('brad.crypto'),
'earliest',
);
}
});
});
describe('.Dweb', () => {
describe('.IPFS', () => {
it('checks return of IPFS hash for brad.zil', async () => {
const spies = mockAsyncMethods(zns, {
allRecords: {
'ipfs.html.value':
'QmVaAtQbi3EtsfpKoLzALm6vXphdi2KjMgxEDKeGg6wHuK',
'whois.email.value': 'derainberk@gmail.com',
'crypto.BCH.address':
'qrq4sk49ayvepqz7j7ep8x4km2qp8lauvcnzhveyu6',
'crypto.BTC.address': '1EVt92qQnaLDcmVFtHivRJaunG2mf2C3mB',
'crypto.ETH.address':
'0x45b31e01AA6f42F0549aD482BE81635ED3149abb',
'crypto.LTC.address': 'LetmswTW3b7dgJ46mXuiXMUY17XbK29UmL',
'crypto.XMR.address':
'447d7TVFkoQ57k3jm3wGKoEAkfEym59mK96Xw5yWamDNFGaLKW5wL2qK5RMTDKGSvYfQYVN7dLSrLdkwtKH3hwbSCQCu26d',
'crypto.ZEC.address': 't1h7ttmQvWCSH1wfrcmvT4mZJfGw2DgCSqV',
'crypto.ZIL.address':
'zil1yu5u4hegy9v3xgluweg4en54zm8f8auwxu0xxj',
'crypto.DASH.address': 'XnixreEBqFuSLnDSLNbfqMH1GsZk7cgW4j',
'ipfs.redirect_domain.value': 'www.unstoppabledomains.com',
'crypto.USDT.version.ERC20.address':
'0x8aaD44321A86b170879d7A244c1e8d360c99DdA8',
},
});
const hash = await resolution.ipfsHash('testing.zil');
expectSpyToBeCalled(spies);
expect(hash).toBe('QmVaAtQbi3EtsfpKoLzALm6vXphdi2KjMgxEDKeGg6wHuK');
});
});
describe('.Gundb', () => {
it('should resolve gundb chat id', async () => {
const eyes = mockAsyncMethods(uns, {
get: {
resolver: '0x878bC2f3f717766ab69C0A5f9A6144931E61AEd3',
records: {
['gundb.username.value']:
'0x47992daf742acc24082842752fdc9c875c87c56864fee59d8b779a91933b159e48961566eec6bd6ce3ea2441c6cb4f112d0eb8e8855cc9cf7647f0d9c82f00831c',
},
},
});
const gundb = await resolution.chatId('homecakes.crypto');
expectSpyToBeCalled(eyes);
expect(gundb).toBe(
'0x47992daf742acc24082842752fdc9c875c87c56864fee59d8b779a91933b159e48961566eec6bd6ce3ea2441c6cb4f112d0eb8e8855cc9cf7647f0d9c82f00831c',
);
});
});
});
describe('.Verifications', () => {
describe('.Twitter', () => {
it('should return verified twitter handle', async () => {
const readerSpies = mockAsyncMethods(uns, {
get: {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0x499dd6d875787869670900a2130223d85d4f6aa7',
records: {
['validation.social.twitter.username']:
'0x01882395ce631866b76f43535843451444ef4a8ff44db0a9432d5d00658a510512c7519a87c78ba9cad7553e26262ada55c254434a1a3784cd98d06fb4946cfb1b',
['social.twitter.username']: 'Marlene12Bob',
},
},
});
const twitterHandle = await resolution.twitter(
CryptoDomainWithTwitterVerification,
);
expectSpyToBeCalled(readerSpies);
expect(twitterHandle).toBe('Marlene12Bob');
});
it('should throw unsupported method', async () => {
const resolution = new Resolution();
await expectResolutionErrorCode(
resolution.twitter('ryan.zil'),
ResolutionErrorCode.UnsupportedMethod,
);
});
});
});
});
});
describe('.registryAddress', () => {
it('should return zns mainnet registry address', async () => {
const registryAddress = await resolution.registryAddress('testi.zil');
expect(registryAddress).toBe(
'zil1hyj6m5w4atcn7s806s69r0uh5g4t84e8gp6nps',
);
});
it('should return cns mainnet registry address #1', async () => {
const spies = mockAsyncMethods(uns, {
registryAddress: UnsConfig.networks[4].contracts.CNSRegistry.address,
});
const registryAddress = await resolution.registryAddress(
'udtestdev-crewe.crypto',
);
expectSpyToBeCalled(spies);
expect(registryAddress).toBe(
UnsConfig.networks[4].contracts.CNSRegistry.address,
);
});
it('should return uns mainnet registry address', async () => {
const spies = mockAsyncMethods(uns, {
registryAddress: UnsConfig.networks[4].contracts.UNSRegistry.address,
});
const registryAddress = await resolution.registryAddress(
'udtestdev-check.wallet',
);
expectSpyToBeCalled(spies);
expect(registryAddress).toBe(
UnsConfig.networks[4].contracts.UNSRegistry.address,
);
});
});
describe('.records', () => {
it('works', async () => {
const eyes = mockAsyncMethods(uns, {
get: {
owner: '0x6EC0DEeD30605Bcd19342f3c30201DB263291589',
resolver: '0x878bC2f3f717766ab69C0A5f9A6144931E61AEd3',
records: {
'crypto.ADA.address':
'DdzFFzCqrhssjmxkChyAHE9MdHJkEc4zsZe7jgum6RtGzKLkUanN1kPZ1ipVPBLwVq2TWrhmPsAvArcr47Pp1VNKmZTh6jv8ctAFVCkj',
'crypto.ETH.address': '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
},
},
});
expect(
await resolution.records(CryptoDomainWithAllRecords, [
'crypto.ADA.address',
'crypto.ETH.address',
]),
).toEqual({
'crypto.ADA.address':
'DdzFFzCqrhssjmxkChyAHE9MdHJkEc4zsZe7jgum6RtGzKLkUanN1kPZ1ipVPBLwVq2TWrhmPsAvArcr47Pp1VNKmZTh6jv8ctAFVCkj',
'crypto.ETH.address': '0xe7474D07fD2FA286e7e0aa23cd107F8379085037',
});
expectSpyToBeCalled([...eyes]);
});
});
describe('.isRegistered', () => {
it('should return true', async () => {
const spies = mockAsyncMethods(uns, {
get: {
owner: '0x58cA45E932a88b2E7D0130712B3AA9fB7c5781e2',
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
records: {
['ipfs.html.value']:
'QmQ38zzQHVfqMoLWq2VeiMLHHYki9XktzXxLYTWXt8cydu',
},
},
});
const isRegistered = await resolution.isRegistered('brad.crypto');
expectSpyToBeCalled(spies);
expect(isRegistered).toBe(true);
});
it('should return false', async () => {
const spies = mockAsyncMethods(uns, {
get: {
owner: '',
resolver: '',
records: {},
},
});
const isRegistered = await resolution.isRegistered(
'thisdomainisdefinitelynotregistered123.crypto',
);
expectSpyToBeCalled(spies);
expect(isRegistered).toBe(false);
});
it('should return true', async () => {
const spies = mockAsyncMethods(zns, {
getRecordsAddresses: ['zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz'],
});
const isRegistered = await resolution.isRegistered('testing.zil');
expectSpyToBeCalled(spies);
expect(isRegistered).toBe(true);
});
it('should return false', async () => {
const spies = mockAsyncMethods(zns, {
getRecordsAddresses: [''],
});
const isRegistered = await resolution.isRegistered(
'thisdomainisdefinitelynotregistered123.zil',
);
expectSpyToBeCalled(spies);
expect(isRegistered).toBe(false);
});
});
describe('.isAvailable', () => {
it('should return false', async () => {
const spies = mockAsyncMethods(uns, {
get: {
owner: '0x58cA45E932a88b2E7D0130712B3AA9fB7c5781e2',
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
records: {
['ipfs.html.value']:
'QmQ38zzQHVfqMoLWq2VeiMLHHYki9XktzXxLYTWXt8cydu',
},
},
});
const isAvailable = await resolution.isAvailable('brad.crypto');
expectSpyToBeCalled(spies);
expect(isAvailable).toBe(false);
});
it('should return true', async () => {
const spies = mockAsyncMethods(uns, {
get: {
owner: '',
resolver: '',
records: {},
},
});
const isAvailable = await resolution.isAvailable(
'qwdqwdjkqhdkqdqwjd.crypto',
);
expectSpyToBeCalled(spies);
expect(isAvailable).toBe(true);
});
it('should return false', async () => {
const spies = mockAsyncMethods(zns, {
getRecordsAddresses: ['zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz'],
});
const isAvailable = await resolution.isAvailable('testing.zil');
expectSpyToBeCalled(spies);
expect(isAvailable).toBe(false);
});
it('should return true', async () => {
const spies = mockAsyncMethods(zns, {
getRecordsAddresses: [''],
});
const isAvailable = await resolution.isAvailable('ryan.zil');
expectSpyToBeCalled(spies);
expect(isAvailable).toBe(true);
});
});
describe('.namehash', () => {
it('brad.crypto', () => {
const expectedNamehash =
'0x756e4e998dbffd803c21d23b06cd855cdc7a4b57706c95964a37e24b47c10fc9';
const namehash = resolution.namehash('brad.crypto');
expect(namehash).toEqual(expectedNamehash);
});
it('brad.zil', () => {
const expectedNamehash =
'0x5fc604da00f502da70bfbc618088c0ce468ec9d18d05540935ae4118e8f50787';
const namehash = resolution.namehash('brad.zil');
expect(namehash).toEqual(expectedNamehash);
});
it('brad.eth', () => {
const expectedNamehash =
'0xe2cb672a04d6270338f15a428216ca714514dc01fdbdd76e97038a8d4080e01c';
const namehash = resolution.namehash('brad.eth');
expect(namehash).toEqual(expectedNamehash);
});
});
describe('.childhash', () => {
it('brad.crypto', () => {
const expectedNamehash =
'0x756e4e998dbffd803c21d23b06cd855cdc7a4b57706c95964a37e24b47c10fc9';
const namehash = resolution.childhash(
'0x0f4a10a4f46c288cea365fcf45cccf0e9d901b945b9829ccdb54c10dc3cb7a6f',
'brad',
NamingServiceName.UNS,
);
expect(namehash).toEqual(expectedNamehash);
});
it('brad.zil', () => {
const expectedNamehash =
'0x5fc604da00f502da70bfbc618088c0ce468ec9d18d05540935ae4118e8f50787';
const namehash = resolution.childhash(
'0x9915d0456b878862e822e2361da37232f626a2e47505c8795134a95d36138ed3',
'brad',
NamingServiceName.ZNS,
);
expect(namehash).toEqual(expectedNamehash);
});
it('brad.eth', () => {
const expectedNamehash =
'0x96a270260d2f9e37845776c17a47ae9b8b7e7e576b2365afd2e7f30f43e9bb49';
const namehash = resolution.childhash(
'0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae',
'beresnev',
NamingServiceName.ENS,
);
expect(namehash).toEqual(expectedNamehash);
});
it('should throw error if service is not supported', () => {
expect(() =>
resolution.childhash(
'0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae',
'beresnev',
'COM' as NamingServiceName,
),
).toThrowError('Naming service COM is not supported');
});
});
describe('.location', () => {
it('should get location for .crypto domains', async () => {
const mockValues = {
registryAddress: '0xAad76bea7CFEc82927239415BB18D2e93518ecBB',
get: {
resolver: '0x95AE1515367aa64C462c71e87157771165B1287A',
owner: '0x499dD6D875787869670900a2130223D85d4F6Aa7',
},
};
mockAsyncMethods(uns, mockValues);
const location = await resolution.location('brad.crypto');
expect(location).toEqual({
registry: mockValues.registryAddress,
resolver: mockValues.get.resolver,
networkId: 4,
blockchain: BlockchainType.ETH,
owner: mockValues.get.owner,
});
});
it('should get location for uns domains', async () => {
const mockValues = {
registryAddress: '0x7fb83000B8eD59D3eAD22f0D584Df3a85fBC0086',
get: {
resolver: '0x7fb83000B8eD59D3eAD22f0D584Df3a85fBC0086',
owner: '0x0e43F36e4B986dfbE1a75cacfA60cA2bD44Ae962',
},
};
mockAsyncMethods(uns, mockValues);
const location = await resolution.location('udtestdev-check.wallet');
expect(location).toEqual({
registry: mockValues.registryAddress,
resolver: mockValues.get.resolver,
networkId: 4,
blockchain: BlockchainType.ETH,
owner: mockValues.get.owner,
});
});
it('should get location for zns domains', async () => {
const mockValues = {
registryAddress: 'zil1hyj6m5w4atcn7s806s69r0uh5g4t84e8gp6nps',
resolver: '0x02621c64a57e1424adfe122569f2356145f05d4f',
owner: 'zil1qqlrehlvat5kalsq07qedgd3k804glhwhv8ppa',
};
mockAsyncMethods(zns, mockValues);
const location = await resolution.location('testing.zil');
expect(location).toEqual({
registry: mockValues.registryAddress,
resolver: mockValues.resolver,
networkId: 333,
blockchain: BlockchainType.ZIL,
owner: mockValues.owner,
});
});
});
}); | the_stack |
import {app} from './common/module-require';
import '@uirouter/angular';
import 'kylo-services';
import './main/IndexController';
import './main/HomeController';
import './main/AccessDeniedController';
import {AccessControlService} from './services/AccessControlService';
import LoginNotificationService from "./services/LoginNotificationService";
import {KyloRouterService} from "./services/kylo-router.service";
import {Lazy} from './kylo-utils/LazyLoadUtil';
'use strict';
class Route {
// app: ng.IModule;
constructor() {
// this.app = app;
/*this.*/
app.config(["$ocLazyLoadProvider", "$stateProvider", "$urlRouterProvider", this.configFn.bind(this)]);
/*this.*/
app.run(['$rootScope', '$state', '$location', "$transitions", "$timeout", "$q", "$uiRouter", "AccessControlService", "AngularModuleExtensionService", "LoginNotificationService","KyloRouterService","$ocLazyLoad",
this.runFn.bind(this)]);
}
//var app = angular.module("", ["ngRoute"]);
configFn($ocLazyLoadProvider: any, $stateProvider: any, $urlRouterProvider: any) {
function onOtherwise(AngularModuleExtensionService: any, $state: any, url: any) {
var stateData = AngularModuleExtensionService.stateAndParamsForUrl(url);
if (stateData.valid) {
$state.go(stateData.state, stateData.params);
}
else {
$state.go('home')
}
}
$urlRouterProvider.otherwise(($injector: any, $location: any) => {
var $state = $injector.get('$state');
var svc = $injector.get('AngularModuleExtensionService');
var url = $location.url();
if (svc != null) {
if (svc.isInitialized()) {
onOtherwise(svc, $state, url)
return true;
}
else {
$injector.invoke(($window: any, $state: any, AngularModuleExtensionService: any) => {
AngularModuleExtensionService.registerModules().then(() => {
onOtherwise(AngularModuleExtensionService, $state, url)
return true;
});
});
return true;
}
}
else {
$location.url("/home")
}
});
$stateProvider
.state('home', {
url: '/home',
views: {
"content": {
component: 'homeController',
}
},
lazyLoad: ($transition$: any) => {
const $ocLazyLoad = $transition$.injector().get("$ocLazyLoad");
return import(/* webpackChunkName: "home.module" */ './main/HomeController')
.then(mod => {
$ocLazyLoad.load(mod);
})
.catch(err => {
throw new Error("Failed to load home controller, " + err);
});
}
});
//Feed Manager
$stateProvider.state({
name: 'feeds.**',
url: '/feeds',
lazyLoad: ($transition$: any) => {
const $ocLazyLoad = $transition$.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "feedmgr.feeds.module" */ "./feed-mgr/feeds/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "feeds"));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'import-feed.**',
url: '/import-feed',
params: {},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
return import(/* webpackChunkName: "feedmgr.import-feed.module" */ "./feed-mgr/feeds/define-feed/module")
.then(mod => {
$ocLazyLoad.load({name: mod.default.module.name}).then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('import-feed', transition.params());
return args;
}, function error(err: any) {
console.error("Error loading import-feed ", err);
return err;
});
})
.catch(err => {
throw new Error("Failed to load feed-mgr/feeds/define-feed/module, " + err);
});
}
});
$stateProvider.state({
name: 'categories.**',
url: '/categories',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "feedmgr.categories.module" */ "./feed-mgr/categories/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "categories", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'category-details.**',
url: '/category-details/{categoryId}',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "feedmgr.categories.module" */ "./feed-mgr/categories/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "category-details", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state('registered-templates.**', {
url: '/registered-templates',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
return import(/* webpackChunkName: "admin.registered-templates.module" */ "././feed-mgr/templates/module")
.then(mod => {
return $ocLazyLoad.load({name: mod.default.module.name}).then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('registered-templates')
return args;
}, function error(err: any) {
console.error("Error loading registered-templates ", err);
return err;
});
})
.catch(err => {
throw new Error("Failed to load ././feed-mgr/templates/module, " + err);
});
}
});
$stateProvider.state('register-template.**', {
url: '/register-template',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "feedmgr.templates.module" */ "./feed-mgr/templates/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "register-template"));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
})
$stateProvider.state({
name: 'users.**',
url: '/users',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "admin.auth.module" */ "./auth/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "users", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'user-details.**',
url: '/user-details/{userId}',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "admin.auth.module" */ "./auth/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "user-details", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'groups.**',
url: '/groups',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "admin.auth.module" */ "./auth/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "groups", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'group-details.**',
url: '/group-details/{groupId}',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "admin.auth.module" */ "./auth/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "group-details", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'search.**',
url: '/search',
params: {
bcExclude_globalSearchResetPaging: null
},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "kylo.search" */ "./search/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "search", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'business-metadata.**',
url: '/business-metadata',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "feedmgr.business-metadata.module" */ "./feed-mgr/business-metadata/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "business-metadata"));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
//Ops Manager
$stateProvider.state({
name: 'dashboard.**',
url: '/dashboard',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "ops-mgr.overview.module" */ "./ops-mgr/overview/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "dashboard"));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'ops-feed-details.**',
url: '/ops-feed-details/{feedName}',
params: {
feedName: null
},
lazyLoad: (transition: any) => {
transition.injector().get('$ocLazyLoad').load('./ops-mgr/feeds/module').then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('ops-feed-details', transition.params())
return args;
}, function error(err: any) {
console.error("Error loading ops-feed-details ", err);
return err;
});
}
});
$stateProvider.state({
name: 'feed-stats.**',
url: '/feed-stats/{feedName}',
params: {
feedName: null
},
lazyLoad: (transition: any) => {
transition.injector().get('$ocLazyLoad').load('./ops-mgr/feeds/feed-stats/module').then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('feed-stats', transition.params())
return args;
}, function error(err: any) {
console.error("Error loading feed-stats ", err);
return err;
});
}
});
$stateProvider.state({
name: 'job-details.**',
url: '/job-details/{executionId}',
params: {
executionId: null
},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "ops-mgr.job-details.module" */ './ops-mgr/jobs/details/module')
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, 'job-details', transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'jobs.**',
url: '/jobs',
params: {
filter: null,
tab: null
},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "ops-mgr.jobs.module" */ "./ops-mgr/jobs/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, 'jobs', transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'service-health.**',
url: '/service-health',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "opsmgr.service-health.module" */ "./ops-mgr/service-health/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "service-health", transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'service-details.**',
url: '/service-details/{serviceName}',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "opsmgr.service-health.module" */ "./ops-mgr/service-health/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "service-details", transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'scheduler.**',
url: '/scheduler',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
return import(/* webpackChunkName: "ops-mgr.scheduler.module" */ './ops-mgr/scheduler/module')
.then(mod => {
$ocLazyLoad.load({name: mod.default.module.name}).then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('scheduler', transition.params())
return args;
}, function error(err: any) {
console.error("Error loading scheduler ", err);
return err;
});
})
.catch(err => {
throw new Error("Failed to load ./ops-mgr/scheduler/module, " + err);
});
}
});
$stateProvider.state({
name: 'alerts.**',
url: '/alerts',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "ops-mgr.alerts.module" */ "./ops-mgr/alerts/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, 'alerts', transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'alert-details.**',
url: '/alert-details/{alertId}',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "ops-mgr.alerts.module" */ "./ops-mgr/alerts/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, 'alert-details', transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'charts.**',
url: '/charts',
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
return import(/* webpackChunkName: "ops-mgr.charts.module" */ "./ops-mgr/charts/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, 'charts', transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: "domain-types.**",
url: "/domain-types",
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "admin.domain-types.module" */ "./feed-mgr/domain-types/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "domain-types", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: "domain-type-details.**",
url: "/domain-type-details/{domainTypeId}",
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "admin.domain-types.module" */ "./feed-mgr/domain-types/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "domain-type-details", transition.params()));
};
import(/* webpackChunkName: "feed-mgr.module-require" */ "./feed-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'service-level-assessment.**',
url: '/service-level-assessment/{assessmentId}',
params: {
assessmentId: null
},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "ops-mgr.slas.module" */ "./ops-mgr/sla/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "service-level-assessment", transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'service-level-assessments.**',
url: '/service-level-assessments',
params: {
filter: null
},
lazyLoad: (transition: any) => {
const $ocLazyLoad = transition.injector().get('$ocLazyLoad');
const onModuleLoad = () => {
import(/* webpackChunkName: "ops-mgr.slas.module" */ "./ops-mgr/sla/module")
.then(Lazy.onModuleFactoryImport($ocLazyLoad)).then(Lazy.goToState($stateProvider, "service-level-assessments", transition.params()));
};
import(/* webpackChunkName: "ops-mgr.module-require" */ "./ops-mgr/module-require").then(Lazy.onModuleImport($ocLazyLoad)).then(onModuleLoad);
}
});
$stateProvider.state({
name: 'projects.**',
url: '/projects',
lazyLoad: (transition: any) => {
transition.injector().get('$ocLazyLoad').load('plugin/projects/module').then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('projects')
return args;
}, function error(err: any) {
console.error("Error loading projects ", err);
return err;
});
}
}).state('project-details.**', {
url: '/project-details/{projectId}',
params: {
projectId: null
},
lazyLoad: (transition: any) => {
transition.injector().get('$ocLazyLoad').load('plugin/projects/module').then(function success(args: any) {
//upon success go back to the state
$stateProvider.stateService.go('project-details', transition.params())
return args;
}, function error(err: any) {
console.error("Error loading projects ", err);
return err;
});
}
});
$stateProvider
.state('access-denied', {
url: '/access-denied',
views: {
"content": {
component: 'accessDeniedController',
}
},
lazyLoad: ($transition$: any) => {
const $ocLazyLoad = $transition$.injector().get("$ocLazyLoad");
return import(/* webpackChunkName: "accessDenied.module" */ './main/AccessDeniedController')
.then(mod => {
$ocLazyLoad.load(mod);
})
.catch(err => {
throw new Error("Failed to load access denied controller, " + err);
});
}
});
}
runFn($rootScope: any, $state: any, $location: any, $transitions: any, $timeout: any, $q: any,
$uiRouter: any, accessControlService: AccessControlService, AngularModuleExtensionService: any,
loginNotificationService: LoginNotificationService,
kyloRouterService:KyloRouterService, $ocLazyLoad: any) {
require('./services/module');
require('./common/module');
require('./feed-mgr/module');
require('./feed-mgr/module-require');
//initialize the access control
accessControlService.init();
loginNotificationService.initNotifications();
$rootScope.$state = $state;
$rootScope.$location = $location;
$rootScope.typeOf = (value: any) => {
return typeof value;
};
var checkAccess = (trans: any) => {
if (!accessControlService.isFutureState(trans.to().name)) {
//if we havent initialized the user yet, init and defer the transition
if (!accessControlService.initialized) {
var defer = $q.defer();
$q.when(accessControlService.init(), () => {
//if not allowed, go to access-denied
if (!accessControlService.hasAccess(trans)) {
if (trans.to().name != 'access-denied') {
let redirect = "access-denied";
if(trans.to().data) {
redirect = trans.to().data.accessRedirect != undefined ? trans.to().data.accessRedirect : "access-denied";
}
defer.resolve($state.target(redirect, {attemptedState: trans.to()}));
}
}
else {
kyloRouterService.saveTransition(trans)
defer.resolve($state.target(trans.to().name, trans.params()));
}
});
return defer.promise;
}
else {
if (!accessControlService.hasAccess(trans)) {
if (trans.to().name != 'access-denied') {
let redirect = "access-denied";
if(trans.to().data) {
redirect = trans.to().data.accessRedirect != undefined ? trans.to().data.accessRedirect : "access-denied";
}
return $state.target(redirect, {attemptedState: trans.to()});
}
}
else {
kyloRouterService.saveTransition(trans)
}
}
}
else {
kyloRouterService.saveTransition(trans)
}
}
var onBeforeTransition = (trans: any) => {
return checkAccess(trans);
}
/**
* Add a listener to the start of every transition to do Access control on the page
* and redirect if not authorized
*
var onStartOfTransition = (trans: any) => {
return checkAccess(trans);
}
$transitions.onStart({}, (trans: any) => {
if (AngularModuleExtensionService.isInitialized()) {
return onStartOfTransition(trans);
}
else {
var defer = $q.defer();
$q.when(AngularModuleExtensionService.registerModules(), () => {
defer.resolve(onStartOfTransition(trans));
});
return defer.promise;
}
});
*/
$transitions.onBefore({}, (trans: any) => {
if (AngularModuleExtensionService.isInitialized()) {
return onBeforeTransition(trans);
}
else {
var defer = $q.defer();
$q.when(AngularModuleExtensionService.registerModules(), () => {
defer.resolve(onBeforeTransition(trans));
});
return defer.promise;
}
});
}
}
const routes = new Route();
export default routes; | the_stack |
import assert from "assert"
import {HasLocation, Token} from "../../ast"
import * as cursors from "./cursors"
import Cursor from "./cursors/cursor"
import ForwardTokenCursor from "./cursors/forward-token-cursor"
import PaddedTokenCursor from "./cursors/padded-token-cursor"
import {search} from "./utils"
export type SkipOptions = number | ((token: Token) => boolean) | {
includeComments?: boolean
filter?: (token: Token) => boolean
skip?: number
}
export type CountOptions = number | ((token: Token) => boolean) | {
includeComments?: boolean
filter?: (token: Token) => boolean
count?: number
}
/**
* Check whether the given token is a comment token or not.
* @param token The token to check.
* @returns `true` if the token is a comment token.
*/
function isCommentToken(token: Token): boolean {
return token.type === "Line" || token.type === "Block" || token.type === "Shebang"
}
/**
* Creates the map from locations to indices in `tokens`.
*
* The first/last location of tokens is mapped to the index of the token.
* The first/last location of comments is mapped to the index of the next token of each comment.
*
* @param tokens - The array of tokens.
* @param comments - The array of comments.
* @returns The map from locations to indices in `tokens`.
* @private
*/
function createIndexMap(tokens: Token[], comments: Token[]): { [key: number]: number } {
const map = Object.create(null)
let tokenIndex = 0
let commentIndex = 0
let nextStart = 0
let range: [number, number] | null = null
while (tokenIndex < tokens.length || commentIndex < comments.length) {
nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER
while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) {
map[range[0]] = tokenIndex
map[range[1] - 1] = tokenIndex
tokenIndex += 1
}
nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER
while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) {
map[range[0]] = tokenIndex
map[range[1] - 1] = tokenIndex
commentIndex += 1
}
}
return map
}
/**
* Creates the cursor iterates tokens with options.
*
* @param factory - The cursor factory to initialize cursor.
* @param tokens - The array of tokens.
* @param comments - The array of comments.
* @param indexMap - The map from locations to indices in `tokens`.
* @param startLoc - The start location of the iteration range.
* @param endLoc - The end location of the iteration range.
* @param opts - The option object. If this is a number then it's `opts.skip`. If this is a function then it's `opts.filter`.
* @returns The created cursor.
* @private
*/
function createCursorWithSkip(factory: cursors.CursorFactory, tokens: Token[], comments: Token[], indexMap: { [key: number]: number }, startLoc: number, endLoc: number, opts?: SkipOptions): Cursor {
let includeComments = false
let skip = 0
let filter: ((token: Token) => boolean) | null = null
if (typeof opts === "number") {
skip = opts | 0
}
else if (typeof opts === "function") {
filter = opts
}
else if (opts) {
includeComments = Boolean(opts.includeComments)
skip = opts.skip || 0
filter = opts.filter || null
}
assert(skip >= 0, "options.skip should be zero or a positive integer.")
assert(!filter || typeof filter === "function", "options.filter should be a function.")
return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1)
}
/**
* Creates the cursor iterates tokens with options.
*
* @param factory - The cursor factory to initialize cursor.
* @param tokens - The array of tokens.
* @param comments - The array of comments.
* @param indexMap - The map from locations to indices in `tokens`.
* @param startLoc - The start location of the iteration range.
* @param endLoc - The end location of the iteration range.
* @param opts - The option object. If this is a number then it's `opts.count`. If this is a function then it's `opts.filter`.
* @returns The created cursor.
* @private
*/
function createCursorWithCount(factory: cursors.CursorFactory, tokens: Token[], comments: Token[], indexMap: { [key: number]: number }, startLoc: number, endLoc: number, opts?: CountOptions): Cursor {
let includeComments = false
let count = 0
let countExists = false
let filter: ((token: Token) => boolean) | null = null
if (typeof opts === "number") {
count = opts | 0
countExists = true
}
else if (typeof opts === "function") {
filter = opts
}
else if (opts) {
includeComments = Boolean(opts.includeComments)
count = opts.count || 0
countExists = typeof opts.count === "number"
filter = opts.filter || null
}
assert(count >= 0, "options.count should be zero or a positive integer.")
assert(!filter || typeof filter === "function", "options.filter should be a function.")
return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1)
}
/**
* Creates the cursor iterates tokens with options.
*
* @param tokens - The array of tokens.
* @param comments - The array of comments.
* @param indexMap - The map from locations to indices in `tokens`.
* @param startLoc - The start location of the iteration range.
* @param endLoc - The end location of the iteration range.
* @param beforeCount - The number of tokens before the node to retrieve.
* @param afterCount - The number of tokens after the node to retrieve.
* @returns The created cursor.
* @private
*/
function createCursorWithPadding(tokens: Token[], comments: Token[], indexMap: { [key: number]: number }, startLoc: number, endLoc: number, beforeCount?: CountOptions, afterCount?: number): Cursor {
if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") {
return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc)
}
if (typeof beforeCount === "number" || typeof beforeCount === "undefined") {
return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount || 0, afterCount || 0)
}
return createCursorWithCount(cursors.forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount)
}
/**
* Gets comment tokens that are adjacent to the current cursor position.
* @param cursor - A cursor instance.
* @returns An array of comment tokens adjacent to the current cursor position.
* @private
*/
function getAdjacentCommentTokensFromCursor(cursor: Cursor): Token[] {
const tokens: Token[] = []
let currentToken = cursor.getOneToken()
while (currentToken && isCommentToken(currentToken)) {
tokens.push(currentToken)
currentToken = cursor.getOneToken()
}
return tokens
}
//------------------------------------------------------------------------------
// Exports
//------------------------------------------------------------------------------
/**
* The token store.
*
* This class provides methods to get tokens by locations as fast as possible.
* The methods are a part of public API, so we should be careful if it changes this class.
*
* People can get tokens in O(1) by the hash map which is mapping from the location of tokens/comments to tokens.
* Also people can get a mix of tokens and comments in O(log k), the k is the number of comments.
* Assuming that comments to be much fewer than tokens, this does not make hash map from token's locations to comments to reduce memory cost.
* This uses binary-searching instead for comments.
*/
export default class TokenStore {
private _tokens: Token[]
private _comments: Token[]
private _indexMap: { [key: number]: number }
/**
* Initializes this token store.
* @param tokens - The array of tokens.
* @param comments - The array of comments.
*/
constructor(tokens: Token[], comments: Token[]) {
this._tokens = tokens
this._comments = comments
this._indexMap = createIndexMap(tokens, comments)
}
//--------------------------------------------------------------------------
// Gets single token.
//--------------------------------------------------------------------------
/**
* Gets the token starting at the specified index.
* @param offset - Index of the start of the token's range.
* @param options - The option object.
* @returns The token starting at index, or null if no such token.
*/
getTokenByRangeStart(offset: number, options?: { includeComments: boolean }): Token | null {
const includeComments = Boolean(options && options.includeComments)
const token = cursors.forward.createBaseCursor(
this._tokens,
this._comments,
this._indexMap,
offset,
-1,
includeComments
).getOneToken()
if (token && token.range[0] === offset) {
return token
}
return null
}
/**
* Gets the first token of the given node.
* @param node - The AST node.
* @param options - The option object.
* @returns An object representing the token.
*/
getFirstToken(node: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
node.range[0],
node.range[1],
options
).getOneToken()
}
/**
* Gets the last token of the given node.
* @param node - The AST node.
* @param options - The option object.
* @returns An object representing the token.
*/
getLastToken(node: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
node.range[0],
node.range[1],
options
).getOneToken()
}
/**
* Gets the token that precedes a given node or token.
* @param node - The AST node or token.
* @param options - The option object.
* @returns An object representing the token.
*/
getTokenBefore(node: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
-1,
node.range[0],
options
).getOneToken()
}
/**
* Gets the token that follows a given node or token.
* @param node - The AST node or token.
* @param options - The option object.
* @returns An object representing the token.
*/
getTokenAfter(node: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
node.range[1],
-1,
options
).getOneToken()
}
/**
* Gets the first token between two non-overlapping nodes.
* @param left - Node before the desired token range.
* @param right - Node after the desired token range.
* @param options - The option object.
* @returns An object representing the token.
*/
getFirstTokenBetween(left: HasLocation, right: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
left.range[1],
right.range[0],
options
).getOneToken()
}
/**
* Gets the last token between two non-overlapping nodes.
* @param left Node before the desired token range.
* @param right Node after the desired token range.
* @param options - The option object.
* @returns An object representing the token.
*/
getLastTokenBetween(left: HasLocation, right: HasLocation, options?: SkipOptions): Token | null {
return createCursorWithSkip(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
left.range[1],
right.range[0],
options
).getOneToken()
}
/**
* Gets the token that precedes a given node or token in the token stream.
* This is defined for backward compatibility. Use `includeComments` option instead.
* TODO: We have a plan to remove this in a future major version.
* @param node The AST node or token.
* @param skip A number of tokens to skip.
* @returns An object representing the token.
* @deprecated
*/
getTokenOrCommentBefore(node: HasLocation, skip?: number): Token | null {
return this.getTokenBefore(node, {includeComments: true, skip})
}
/**
* Gets the token that follows a given node or token in the token stream.
* This is defined for backward compatibility. Use `includeComments` option instead.
* TODO: We have a plan to remove this in a future major version.
* @param node The AST node or token.
* @param skip A number of tokens to skip.
* @returns An object representing the token.
* @deprecated
*/
getTokenOrCommentAfter(node: HasLocation, skip?: number): Token | null {
return this.getTokenAfter(node, {includeComments: true, skip})
}
//--------------------------------------------------------------------------
// Gets multiple tokens.
//--------------------------------------------------------------------------
/**
* Gets the first `count` tokens of the given node.
* @param node - The AST node.
* @param [options=0] - The option object. If this is a number then it's `options.count`. If this is a function then it's `options.filter`.
* @param [options.includeComments=false] - The flag to iterate comments as well.
* @param [options.filter=null] - The predicate function to choose tokens.
* @param [options.count=0] - The maximum count of tokens the cursor iterates.
* @returns Tokens.
*/
getFirstTokens(node: HasLocation, options?: CountOptions): Token[] {
return createCursorWithCount(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
node.range[0],
node.range[1],
options
).getAllTokens()
}
/**
* Gets the last `count` tokens of the given node.
* @param node - The AST node.
* @param [options=0] - The option object. Same options as getFirstTokens()
* @returns Tokens.
*/
getLastTokens(node: HasLocation, options?: CountOptions) {
return createCursorWithCount(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
node.range[0],
node.range[1],
options
).getAllTokens().reverse()
}
/**
* Gets the `count` tokens that precedes a given node or token.
* @param node - The AST node or token.
* @param [options=0] - The option object. Same options as getFirstTokens()
* @returns Tokens.
*/
getTokensBefore(node: HasLocation, options?: CountOptions): Token[] {
return createCursorWithCount(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
-1,
node.range[0],
options
).getAllTokens().reverse()
}
/**
* Gets the `count` tokens that follows a given node or token.
* @param node - The AST node or token.
* @param [options=0] - The option object. Same options as getFirstTokens()
* @returns Tokens.
*/
getTokensAfter(node: HasLocation, options?: CountOptions): Token[] {
return createCursorWithCount(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
node.range[1],
-1,
options
).getAllTokens()
}
/**
* Gets the first `count` tokens between two non-overlapping nodes.
* @param left - Node before the desired token range.
* @param right - Node after the desired token range.
* @param [options=0] - The option object. Same options as getFirstTokens()
* @returns Tokens between left and right.
*/
getFirstTokensBetween(left: HasLocation, right: HasLocation, options?: CountOptions): Token[] {
return createCursorWithCount(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
left.range[1],
right.range[0],
options
).getAllTokens()
}
/**
* Gets the last `count` tokens between two non-overlapping nodes.
* @param left Node before the desired token range.
* @param right Node after the desired token range.
* @param [options=0] - The option object. Same options as getFirstTokens()
* @returns Tokens between left and right.
*/
getLastTokensBetween(left: HasLocation, right: HasLocation, options?: CountOptions): Token[] {
return createCursorWithCount(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
left.range[1],
right.range[0],
options
).getAllTokens().reverse()
}
/**
* Gets all tokens that are related to the given node.
* @param node - The AST node.
* @param beforeCount - The number of tokens before the node to retrieve.
* @param afterCount - The number of tokens after the node to retrieve.
* @returns Array of objects representing tokens.
*/
getTokens(node: HasLocation, beforeCount?: CountOptions, afterCount?: number): Token[] {
return createCursorWithPadding(
this._tokens,
this._comments,
this._indexMap,
node.range[0],
node.range[1],
beforeCount,
afterCount
).getAllTokens()
}
/**
* Gets all of the tokens between two non-overlapping nodes.
* @param left Node before the desired token range.
* @param right Node after the desired token range.
* @param padding Number of extra tokens on either side of center.
* @returns Tokens between left and right.
*/
getTokensBetween(left: HasLocation, right: HasLocation, padding?: CountOptions): Token[] {
return createCursorWithPadding(
this._tokens,
this._comments,
this._indexMap,
left.range[1],
right.range[0],
padding,
typeof padding === "number" ? padding : undefined
).getAllTokens()
}
//--------------------------------------------------------------------------
// Others.
//--------------------------------------------------------------------------
/**
* Checks whether any comments exist or not between the given 2 nodes.
*
* @param left - The node to check.
* @param right - The node to check.
* @returns `true` if one or more comments exist.
*/
commentsExistBetween(left: HasLocation, right: HasLocation): boolean {
const index = search(this._comments, left.range[1])
return (
index < this._comments.length &&
this._comments[index].range[1] <= right.range[0]
)
}
/**
* Gets all comment tokens directly before the given node or token.
* @param nodeOrToken The AST node or token to check for adjacent comment tokens.
* @returns An array of comments in occurrence order.
*/
getCommentsBefore(nodeOrToken: HasLocation): Token[] {
const cursor = createCursorWithCount(
cursors.backward,
this._tokens,
this._comments,
this._indexMap,
-1,
nodeOrToken.range[0],
{includeComments: true}
)
return getAdjacentCommentTokensFromCursor(cursor).reverse()
}
/**
* Gets all comment tokens directly after the given node or token.
* @param nodeOrToken The AST node or token to check for adjacent comment tokens.
* @returns An array of comments in occurrence order.
*/
getCommentsAfter(nodeOrToken: HasLocation): Token[] {
const cursor = createCursorWithCount(
cursors.forward,
this._tokens,
this._comments,
this._indexMap,
nodeOrToken.range[1],
-1,
{includeComments: true}
)
return getAdjacentCommentTokensFromCursor(cursor)
}
/**
* Gets all comment tokens inside the given node.
* @param node The AST node to get the comments for.
* @returns An array of comments in occurrence order.
*/
getCommentsInside(node: HasLocation): Token[] {
return this.getTokens(node, {
includeComments: true,
filter: isCommentToken,
})
}
} | the_stack |
export default [
{ groupa: 'Group number 1', label: 'Afghanistan', id: 'AF' },
{ groupa: 'Group number 1', label: 'Åland Islands', id: 'AX' },
{ groupa: 'Group number 1', label: 'Albania', id: 'AL' },
{ groupa: 'Group number 1', label: 'Algeria', id: 'DZ', disalbed: true },
{ groupa: 'Group number 1', label: 'American Samoa', id: 'AS' },
{ groupa: 'Group number 1', label: 'AndorrA', id: 'AD' },
{ groupa: 'Group number 1', label: 'Angola', id: 'AO' },
{ groupa: 'Group number 1', label: 'Anguilla', id: 'AI', disabled: true },
{ groupa: 'Group number 1', label: 'Antarctica', id: 'AQ' },
{ groupa: 'Group number 1', label: 'Antigua and Barbuda', id: 'AG' },
{ groupa: 'Group number 1', label: 'Argentina', id: 'AR' },
{ groupa: 'Group number 1', label: 'Armenia', id: 'AM' },
{ groupa: 'Group number 1', label: 'Aruba', id: 'AW' },
{ groupa: 'Group number 1', label: 'Australia', id: 'AU' },
{ groupa: 'Group number 1', label: 'Austria', id: 'AT' },
{ groupa: 'Group number 1', label: 'Azerbaijan', id: 'AZ' },
{ groupa: 'Group number 1', label: 'Bahamas', id: 'BS' },
{ groupa: 'Group number 1', label: 'Bahrain', id: 'BH' },
{ groupa: 'Group number 1', label: 'Bangladesh', id: 'BD' },
{ groupa: 'Group number 1', label: 'Barbados', id: 'BB' },
{ groupa: 'Group number 1', label: 'Belarus', id: 'BY' },
{ groupa: 'Group number 1.1', label: 'Belgium', id: 'BE' },
{ groupa: 'Group number 1.1', label: 'Belize', id: 'BZ' },
{ groupa: 'Group number 1.1', label: 'Benin', id: 'BJ' },
{ groupa: 'Group number 1.1', label: 'Bermuda', id: 'BM' },
{ groupa: 'Group number 1.1', label: 'Bhutan', id: 'BT' },
{ groupa: 'Group number 1.1', label: 'Bolivia', id: 'BO' },
{ groupa: 'Group number 1.1', label: 'Bosnia and Herzegovina', id: 'BA' },
{ groupa: 'Group number 1.1', label: 'Botswana', id: 'BW' },
{ groupa: 'Group number 1.1', label: 'Bouvet Island', id: 'BV' },
{ groupa: 'Group number 1.1', label: 'Brazil', id: 'BR' },
{
groupa: 'Group number 1.1',
label: 'British Indian Ocean Territory',
id: 'IO',
},
{ groupa: 'Group number 1.1', label: 'Brunei Darussalam', id: 'BN' },
{ groupa: 'Group number 1.1', label: 'Bulgaria', id: 'BG' },
{ groupa: 'Group number 1.2', label: 'Burkina Faso', id: 'BF' },
{ groupa: 'Group number 1.2', label: 'Burundi', id: 'BI' },
{ groupa: 'Group number 1.2', label: 'Cambodia', id: 'KH' },
{ groupa: 'Group number 1.2', label: 'Cameroon', id: 'CM' },
{ groupa: 'Group number 1.2', label: 'Canada', id: 'CA' },
{ groupa: 'Group number 1.2', label: 'Cape Verde', id: 'CV' },
{ groupa: 'Group number 1.2', label: 'Cayman Islands', id: 'KY' },
{ groupa: 'Group number 1.2', label: 'Central African Republic', id: 'CF' },
{ groupa: 'Group number 1.2', label: 'Chad', id: 'TD' },
{ groupa: 'Group number 1.2', label: 'Chile', id: 'CL' },
{ groupa: 'Group number 1.2', label: 'China', id: 'CN' },
{ groupa: 'Group number 1.2', label: 'Christmas Island', id: 'CX' },
{ groupa: 'Group number 1.2', label: 'Cocos (Keeling) Islands', id: 'CC' },
{ groupa: 'Group number 1.2', label: 'Colombia', id: 'CO' },
{ groupa: 'Group number 1.2', label: 'Comoros', id: 'KM' },
{ groupa: 'Group number 1.2', label: 'Congo', id: 'CG' },
{
groupa: 'Group number 1.2',
label: 'Congo, The Democratic Republic of the',
id: 'CD',
},
{ groupa: 'Group number 1.2', label: 'Cook Islands', id: 'CK' },
{ groupa: 'Group number 1.2', label: 'Costa Rica', id: 'CR' },
{ groupa: 'Group number 1.2', label: "Cote D'Ivoire", id: 'CI' },
{ groupa: 'Group number 1.3', label: 'Croatia', id: 'HR' },
{ groupa: 'Group number 1.3', label: 'Cuba', id: 'CU' },
{ groupa: 'Group number 1.3', label: 'Cyprus', id: 'CY' },
{ groupa: 'Group number 1.3', label: 'Czech Republic', id: 'CZ' },
{ groupa: 'Group number 1.3', label: 'Denmark', id: 'DK' },
{ groupa: 'Group number 1.3', label: 'Djibouti', id: 'DJ' },
{ groupa: 'Group number 1.3', label: 'Dominica', id: 'DM' },
{ groupa: 'Group number 2', label: 'Dominican Republic', id: 'DO' },
{ groupa: 'Group number 2', label: 'Ecuador', id: 'EC' },
{ groupa: 'Group number 2', label: 'Egypt', id: 'EG' },
{ groupa: 'Group number 2', label: 'El Salvador', id: 'SV' },
{ groupa: 'Group number 2', label: 'Equatorial Guinea', id: 'GQ' },
{ groupa: 'Group number 2', label: 'Eritrea', id: 'ER' },
{ groupa: 'Group number 2', label: 'Estonia', id: 'EE' },
{ groupa: 'Group number 2', label: 'Ethiopia', id: 'ET' },
{ groupa: 'Group number 2', label: 'Falkland Islands (Malvinas)', id: 'FK' },
{ groupa: 'Group number 2', label: 'Faroe Islands', id: 'FO' },
{ groupa: 'Group number 2', label: 'Fiji', id: 'FJ' },
{ groupa: 'Group number 2', label: 'Finland', id: 'FI' },
{ groupa: 'Group number 2', label: 'France', id: 'FR' },
{ groupa: 'Group number 2', label: 'French Guiana', id: 'GF' },
{ groupa: 'Group number 2', label: 'French Polynesia', id: 'PF' },
{ groupa: 'Group number 2', label: 'French Southern Territories', id: 'TF' },
{ groupa: 'Group number 2', label: 'Gabon', id: 'GA' },
{ groupa: 'Group number 2', label: 'Gambia', id: 'GM' },
{ groupa: 'Group number 2', label: 'Georgia', id: 'GE' },
{ groupa: 'Group number 2', label: 'Germany', id: 'DE' },
{ groupa: 'Group number 2', label: 'Ghana', id: 'GH' },
{ groupa: 'Group number 2', label: 'Gibraltar', id: 'GI' },
{ groupa: 'Group number 2', label: 'Greece', id: 'GR' },
{ groupa: 'Group number 2', label: 'Greenland', id: 'GL' },
{ groupa: 'Group number 2', label: 'Grenada', id: 'GD' },
{ groupa: 'Group number 2', label: 'Guadeloupe', id: 'GP' },
{ groupa: 'Group number 2', label: 'Guam', id: 'GU' },
{ groupa: 'Group number 2', label: 'Guatemala', id: 'GT' },
{ groupa: 'Group number 2', label: 'Guernsey', id: 'GG' },
{ groupa: 'Group number 2', label: 'Guinea', id: 'GN' },
{ groupa: 'Group number 2', label: 'Guinea-Bissau', id: 'GW' },
{ groupa: 'Group number 2', label: 'Guyana', id: 'GY' },
{ groupa: 'Group number 2', label: 'Haiti', id: 'HT' },
{
groupa: 'Group number 2',
label: 'Heard Island and Mcdonald Islands',
id: 'HM',
},
{
groupa: 'Group number 2',
label: 'Holy See (Vatican City State)',
id: 'VA',
},
{ groupa: 'Group number 2', label: 'Honduras', id: 'HN' },
{ groupa: 'Group number 2', label: 'Hong Kong', id: 'HK' },
{ groupa: 'Group number 2', label: 'Hungary', id: 'HU' },
{ groupa: 'Group number 2', label: 'Iceland', id: 'IS' },
{ groupa: 'Group number 2', label: 'India', id: 'IN' },
{ groupa: 'Group number 2', label: 'Indonesia', id: 'ID' },
{ groupa: 'Group number 3', label: 'Iran, Islamic Republic Of', id: 'IR' },
{ groupa: 'Group number 3', label: 'Iraq', id: 'IQ' },
{ groupa: 'Group number 3', label: 'Ireland', id: 'IE' },
{ groupa: 'Group number 3', label: 'Isle of Man', id: 'IM' },
{ groupa: 'Group number 3', label: 'Israel', id: 'IL' },
{ groupa: 'Group number 3', label: 'Italy', id: 'IT' },
{ groupa: 'Group number 3', label: 'Jamaica', id: 'JM' },
{ groupa: 'Group number 3', label: 'Japan', id: 'JP' },
{ groupa: 'Group number 3', label: 'Jersey', id: 'JE' },
{ groupa: 'Group number 3', label: 'Jordan', id: 'JO' },
{ groupa: 'Group number 3', label: 'Kazakhstan', id: 'KZ' },
{ groupa: 'Group number 3', label: 'Kenya', id: 'KE' },
{ groupa: 'Group number 3', label: 'Kiribati', id: 'KI' },
{
groupa: 'Group number 3',
label: "Korea, Democratic People'S Republic of",
id: 'KP',
},
{ groupa: 'Group number 3', label: 'Korea, Republic of', id: 'KR' },
{ groupa: 'Group number 3', label: 'Kuwait', id: 'KW' },
{ groupa: 'Group number 3', label: 'Kyrgyzstan', id: 'KG' },
{
groupa: 'Group number 3',
label: "Lao People'S Democratic Republic",
id: 'LA',
},
{ groupa: 'Group number 3', label: 'Latvia', id: 'LV' },
{ groupa: 'Group number 3', label: 'Lebanon', id: 'LB' },
{ groupa: 'Group number 3', label: 'Lesotho', id: 'LS' },
{ groupa: 'Group number 3', label: 'Liberia', id: 'LR' },
{ groupa: 'Group number 3', label: 'Libyan Arab Jamahiriya', id: 'LY' },
{ groupa: 'Group number 3', label: 'Liechtenstein', id: 'LI' },
{ groupa: 'Group number 3', label: 'Lithuania', id: 'LT' },
{ groupa: 'Group number 3', label: 'Luxembourg', id: 'LU' },
{ groupa: 'Group number 3', label: 'Macao', id: 'MO' },
{
groupa: 'Group number 3',
label: 'Macedonia, The Former Yugoslav Republic of',
id: 'MK',
},
{ groupa: 'Group number 3', label: 'Madagascar', id: 'MG' },
{ groupa: 'Group number 3', label: 'Malawi', id: 'MW' },
{ groupa: 'Group number 3', label: 'Malaysia', id: 'MY' },
{ groupa: 'Group number 3', label: 'Maldives', id: 'MV' },
{ groupa: 'Group number 3', label: 'Mali', id: 'ML' },
{ groupa: 'Group number 3', label: 'Malta', id: 'MT' },
{ groupa: 'Group number 3', label: 'Marshall Islands', id: 'MH' },
{ groupa: 'Group number 3', label: 'Martinique', id: 'MQ' },
{ groupa: 'Group number 3', label: 'Mauritania', id: 'MR' },
{ groupa: 'Group number 3', label: 'Mauritius', id: 'MU' },
{ groupa: 'Group number 3', label: 'Mayotte', id: 'YT' },
{ groupa: 'Group number 3', label: 'Mexico', id: 'MX' },
{
groupa: 'Group number 3',
label: 'Micronesia, Federated States of',
id: 'FM',
},
{ groupa: 'Group number 3', label: 'Moldova, Republic of', id: 'MD' },
{ groupa: 'Group number 3', label: 'Monaco', id: 'MC' },
{ groupa: 'Group number 3', label: 'Mongolia', id: 'MN' },
{ groupa: 'Group number 3', label: 'Montserrat', id: 'MS' },
{ groupa: 'Group number 3', label: 'Morocco', id: 'MA' },
{ groupa: 'Group number 3', label: 'Mozambique', id: 'MZ' },
{ groupa: 'Group number 3', label: 'Myanmar', id: 'MM' },
{ groupa: 'Group number 3', label: 'Namibia', id: 'NA' },
{ groupa: 'Group number 3', label: 'Nauru', id: 'NR' },
{ groupa: 'Group number 3', label: 'Nepal', id: 'NP' },
{ groupa: 'Group number 3', label: 'Netherlands', id: 'NL' },
{ groupa: 'Group number 3', label: 'Netherlands Antilles', id: 'AN' },
{ groupa: 'Group number 4', label: 'New Caledonia', id: 'NC' },
{ groupa: 'Group number 4', label: 'New Zealand', id: 'NZ' },
{ groupa: 'Group number 4', label: 'Nicaragua', id: 'NI' },
{ groupa: 'Group number 4', label: 'Niger', id: 'NE' },
{ groupa: 'Group number 4', label: 'Nigeria', id: 'NG' },
{ groupa: 'Group number 4', label: 'Niue', id: 'NU' },
{ groupa: 'Group number 4', label: 'Norfolk Island', id: 'NF' },
{ groupa: 'Group number 4', label: 'Northern Mariana Islands', id: 'MP' },
{ groupa: 'Group number 4', label: 'Norway', id: 'NO' },
{ groupa: 'Group number 4', label: 'Oman', id: 'OM' },
{ groupa: 'Group number 4', label: 'Pakistan', id: 'PK' },
{ groupa: 'Group number 4', label: 'Palau', id: 'PW' },
{
groupa: 'Group number 4',
label: 'Palestinian Territory, Occupied',
id: 'PS',
},
{ groupa: 'Group number 4', label: 'Panama', id: 'PA' },
{ groupa: 'Group number 4', label: 'Papua New Guinea', id: 'PG' },
{ groupa: 'Group number 4', label: 'Paraguay', id: 'PY' },
{ groupa: 'Group number 4', label: 'Peru', id: 'PE' },
{ groupa: 'Group number 4', label: 'Philippines', id: 'PH' },
{ groupa: 'Group number 4', label: 'Pitcairn', id: 'PN' },
{ groupa: 'Group number 4', label: 'Poland', id: 'PL' },
{ groupa: 'Group number 4', label: 'Portugal', id: 'PT' },
{ groupa: 'Group number 4', label: 'Puerto Rico', id: 'PR' },
{ groupa: 'Group number 4', label: 'Qatar', id: 'QA' },
{ groupa: 'Group number 4', label: 'Reunion', id: 'RE' },
{ groupa: 'Group number 4', label: 'Romania', id: 'RO' },
{ groupa: 'Group number 4', label: 'Russian Federation', id: 'RU' },
{ groupa: 'Group number 4', label: 'RWANDA', id: 'RW' },
{ groupa: 'Group number 4', label: 'Saint Helena', id: 'SH' },
{ groupa: 'Group number 4', label: 'Saint Kitts and Nevis', id: 'KN' },
{ groupa: 'Group number 4', label: 'Saint Lucia', id: 'LC' },
{ groupa: 'Group number 4', label: 'Saint Pierre and Miquelon', id: 'PM' },
{
groupa: 'Group number 4',
label: 'Saint Vincent and the Grenadines',
id: 'VC',
},
{ groupa: 'Group number 4', label: 'Samoa', id: 'WS' },
{ groupa: 'Group number 4', label: 'San Marino', id: 'SM' },
{ groupa: 'Group number 4', label: 'Sao Tome and Principe', id: 'ST' },
{ groupa: 'Group number 4', label: 'Saudi Arabia', id: 'SA' },
{ groupa: 'Group number 4', label: 'Senegal', id: 'SN' },
{ groupa: 'Group number 4', label: 'Serbia and Montenegro', id: 'CS' },
{ groupa: 'Group number 4', label: 'Seychelles', id: 'SC' },
{ groupa: 'Group number 4', label: 'Sierra Leone', id: 'SL' },
{ groupa: 'Group number 4', label: 'Singapore', id: 'SG' },
{ groupa: 'Group number 4', label: 'Slovakia', id: 'SK' },
{ groupa: 'Group number 4', label: 'Slovenia', id: 'SI' },
{ groupa: 'Group number 4', label: 'Solomon Islands', id: 'SB' },
{ groupa: 'Group number 4', label: 'Somalia', id: 'SO' },
{ groupa: 'Group number 4', label: 'South Africa', id: 'ZA' },
{
groupa: 'Group number 4',
label: 'South Georgia and the South Sandwich Islands',
id: 'GS',
},
{ groupa: 'Group number 4', label: 'Spain', id: 'ES' },
{ groupa: 'Group number 4', label: 'Sri Lanka', id: 'LK' },
{ groupa: 'Group number 4', label: 'Sudan', id: 'SD' },
{ groupa: 'Group number 4', label: 'Surilabel', id: 'SR' },
{ groupa: 'Group number 4', label: 'Svalbard and Jan Mayen', id: 'SJ' },
{ groupa: 'Group number 4', label: 'Swaziland', id: 'SZ' },
{ groupa: 'Group number 4', label: 'Sweden', id: 'SE' },
{ groupa: 'Group number 4', label: 'Switzerland', id: 'CH' },
{ groupa: 'Group number 4', label: 'Syrian Arab Republic', id: 'SY' },
{ groupa: 'Group number 4', label: 'Taiwan, Province of China', id: 'TW' },
{ groupa: 'Group number 4', label: 'Tajikistan', id: 'TJ' },
{
groupa: 'Group number 4',
label: 'Tanzania, United Republic of',
id: 'TZ',
},
{ groupa: 'Group number 4', label: 'Thailand', id: 'TH' },
{ groupa: 'Group number 4', label: 'Timor-Leste', id: 'TL' },
{ groupa: 'Group number 4', label: 'Togo', id: 'TG' },
{ groupa: 'Group number 4', label: 'Tokelau', id: 'TK' },
{ groupa: 'Group number 4', label: 'Tonga', id: 'TO' },
{ groupa: 'Group number 4', label: 'Trinidad and Tobago', id: 'TT' },
{ groupa: 'Group number 4', label: 'Tunisia', id: 'TN' },
{ groupa: 'Group number 4', label: 'Turkey', id: 'TR' },
{ groupa: 'Group number 4', label: 'Turkmenistan', id: 'TM' },
{ groupa: 'Group number 4', label: 'Turks and Caicos Islands', id: 'TC' },
{ groupa: 'Group number 4', label: 'Tuvalu', id: 'TV' },
{ groupa: 'Group number 4', label: 'Uganda', id: 'UG' },
{ groupa: 'Group number 4', label: 'Ukraine', id: 'UA' },
{ groupa: 'Group number 4', label: 'United Arab Emirates', id: 'AE' },
{ groupa: 'Group number 4', label: 'United Kingdom', id: 'GB' },
{ groupa: 'Group number 4', label: 'United States', id: 'US' },
{
groupa: 'Group number 4',
label: 'United States Minor Outlying Islands',
id: 'UM',
},
{ groupa: 'Group number 4', label: 'Uruguay', id: 'UY' },
{ groupa: 'Group number 4', label: 'Uzbekistan', id: 'UZ' },
{ groupa: 'Group number 4', label: 'Vanuatu', id: 'VU' },
{ groupa: 'Group number 4', label: 'Venezuela', id: 'VE' },
{ groupa: 'Group number 4', label: 'Viet Nam', id: 'VN' },
{ groupa: 'Group number 4', label: 'Virgin Islands, British', id: 'VG' },
{ groupa: 'Group number 4', label: 'Virgin Islands, U.S.', id: 'VI' },
{ groupa: 'Group number 4', label: 'Wallis and Futuna', id: 'WF' },
{ groupa: 'Group number 4', label: 'Western Sahara', id: 'EH' },
{ groupa: 'Group number 4', label: 'Yemen', id: 'YE' },
{ groupa: 'Group number 4', label: 'Zambia', id: 'ZM' },
{ groupa: 'Group number 4', label: 'Zimbabwe', id: 'ZW' },
]; | the_stack |
import { GitInspector } from './GitInspector';
import { Types } from '../types';
import fs from 'fs';
import git from 'simple-git/promise';
import os from 'os';
import path from 'path';
import rimraf from 'rimraf';
import util from 'util';
import { Container } from 'inversify';
import { delay } from '../lib/delay';
describe('GitInspector', () => {
let testDir: TestDir;
beforeEach(async () => {
testDir = new TestDir();
});
afterEach(async () => {
await util.promisify(rimraf)(testDir.path);
});
it('is injectable', () => {
const container = new Container();
container.bind(Types.RepositoryPath).toConstantValue(testDir.path);
container.bind(GitInspector).toSelf();
expect(() => container.get(GitInspector)).not.toThrow();
});
describe('#getCommits', () => {
it('returns the page number', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { page } = await gitInspector.getCommits({});
expect(page).toStrictEqual(0);
});
it('returns the per page number', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { perPage } = await gitInspector.getCommits({});
expect(perPage).toStrictEqual(1);
});
it('returns all repository commits', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg');
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({});
const expected = (await testDir.gitLog()).latest;
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns repository commits containing an author', async () => {
await testDir.gitInit();
await testDir.gitCommit('msg1', 'test1 <test1@example.com>');
await testDir.gitCommit('msg2', 'test2 <test2@example.com>');
const expected = (await testDir.gitLog()).latest;
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({ filter: { author: 'test2@example.com' } });
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg2\n',
author: { name: 'test2', email: 'test2@example.com' },
commiter: undefined,
},
]);
});
it('returns repository commits between sha and HEAD', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg1');
const commit1 = (await testDir.gitLog()).latest;
await testDir.gitCommit('msg2');
const commit2 = (await testDir.gitLog()).latest;
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({ filter: { sha: commit1?.hash } });
expect(items).toStrictEqual([
{
sha: commit2?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(commit2!.date),
message: 'msg2\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns repository commits containing a path', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg1');
await testDir.gitAddFile('file.txt');
await testDir.gitCommit('msg2');
const expected = (await testDir.gitLog()).latest;
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({ filter: { path: 'file.txt' } });
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg2\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns repository commits since a date', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg1');
await delay(1000);
await testDir.gitCommit('msg2');
const expected = (await testDir.gitLog()).latest;
const gitInspector = new GitInspector(testDir.path);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const { items } = await gitInspector.getCommits({ filter: { since: new Date(expected!.date) } });
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg2\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns repository commits until a date', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg1');
const expected = (await testDir.gitLog()).latest;
await delay(1000);
await testDir.gitCommit('msg2');
const gitInspector = new GitInspector(testDir.path);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const { items } = await gitInspector.getCommits({ filter: { until: new Date(expected!.date) } });
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg1\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns selected repository commits', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg1');
await testDir.gitCommit('msg2');
await testDir.gitCommit('msg3');
const expected1 = (await testDir.gitLog()).latest;
await testDir.gitCommit('msg4');
const expected2 = (await testDir.gitLog()).latest;
await testDir.gitCommit('msg5');
await testDir.gitCommit('msg6');
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({ pagination: { page: 1, perPage: 2 } });
expect(items).toStrictEqual([
{
sha: expected2?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected2!.date),
message: 'msg4\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
{
sha: expected1?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected1!.date),
message: 'msg3\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns remaining repository commits if pagination specifies a greater subset', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit('msg');
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getCommits({ pagination: { page: 0, perPage: 2 } });
const expected = (await testDir.gitLog()).latest;
expect(items).toStrictEqual([
{
sha: expected?.hash,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
date: new Date(expected!.date),
message: 'msg\n',
author: { name: 'test', email: 'test@example.com' },
commiter: undefined,
},
]);
});
it('returns multiline commit messages', async () => {
await testDir.gitInit();
await testDir.gitCommit('multi\nline\nmessage');
const gitInspector = new GitInspector(testDir.path);
const message = (await gitInspector.getCommits({})).items[0].message;
expect(message).toStrictEqual('multi\nline\nmessage\n');
});
it('returns the total count', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { totalCount } = await gitInspector.getCommits({});
expect(totalCount).toStrictEqual(1);
});
it('returns true if there is a next page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
await testDir.gitCommit();
await testDir.gitCommit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasNextPage } = await gitInspector.getCommits({ pagination: { page: 0, perPage: 2 } });
expect(hasNextPage).toStrictEqual(true);
});
it('returns false if there is no next page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasNextPage } = await gitInspector.getCommits({ pagination: { page: 0, perPage: 2 } });
expect(hasNextPage).toStrictEqual(false);
});
it('returns true if there is a previous page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
await testDir.gitCommit();
await testDir.gitCommit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasPreviousPage } = await gitInspector.getCommits({ pagination: { page: 1, perPage: 2 } });
expect(hasPreviousPage).toStrictEqual(true);
});
it('returns false if there is no previous page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasPreviousPage } = await gitInspector.getCommits({ pagination: { page: 0, perPage: 2 } });
expect(hasPreviousPage).toStrictEqual(false);
});
it('throws an error if the path does not exist', async () => {
const gitInspector = new GitInspector(path.join(testDir.path, 'non-existing-dir'));
await expect(gitInspector.getCommits({})).rejects.toThrow('Cannot use simple-git on a directory that does not exist');
});
it('throws an error if the path is not a repository', async () => {
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getCommits({})).rejects.toThrow();
});
it('throws an error if there are no commits in the repository', async () => {
await testDir.gitInit();
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getCommits({})).rejects.toThrow("fatal: your current branch 'master' does not have any commits yet");
});
it('throws an error if sorting is requested', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getCommits({ sort: {} })).rejects.toThrow('sorting not implemented');
});
});
describe('#getAuthors', () => {
it('returns the page number', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { page } = await gitInspector.getAuthors({});
expect(page).toStrictEqual(0);
});
it('returns the per page number', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { perPage } = await gitInspector.getAuthors({});
expect(perPage).toStrictEqual(1);
});
it('returns all repository authors', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getAuthors({});
expect(items).toStrictEqual([{ name: 'test', email: 'test@example.com' }]);
});
it('returns selected repository authors', async () => {
await testDir.gitInit();
await testDir.gitCommit(undefined, 'test1 <test1@example.com>');
await testDir.gitCommit(undefined, 'test2 <test2@example.com>');
await testDir.gitCommit(undefined, 'test3 <test3@example.com>');
await testDir.gitCommit(undefined, 'test4 <test4@example.com>');
await testDir.gitCommit(undefined, 'test5 <test5@example.com>');
await testDir.gitCommit(undefined, 'test6 <test6@example.com>');
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getAuthors({ pagination: { page: 1, perPage: 2 } });
expect(items).toStrictEqual([
{ name: 'test4', email: 'test4@example.com' },
{ name: 'test3', email: 'test3@example.com' },
]);
});
it('returns remaining repository authors if pagination specifies a greater subset', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getAuthors({ pagination: { page: 0, perPage: 2 } });
expect(items).toStrictEqual([{ name: 'test', email: 'test@example.com' }]);
});
it('returns only unique authors', async () => {
await testDir.gitInit({ name: 'test', email: 'test@example.com' });
await testDir.gitCommit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { items } = await gitInspector.getAuthors({});
expect(items).toStrictEqual([{ name: 'test', email: 'test@example.com' }]);
});
it('returns the total count', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { totalCount } = await gitInspector.getAuthors({});
expect(totalCount).toStrictEqual(1);
});
it('returns true if there is a next page', async () => {
await testDir.gitInit();
await testDir.gitCommit(undefined, 'test1 <test1@example.com>');
await testDir.gitCommit(undefined, 'test2 <test2@example.com>');
await testDir.gitCommit(undefined, 'test3 <test3@example.com>');
await testDir.gitCommit(undefined, 'test4 <test4@example.com>');
const gitInspector = new GitInspector(testDir.path);
const { hasNextPage } = await gitInspector.getAuthors({ pagination: { page: 0, perPage: 2 } });
expect(hasNextPage).toStrictEqual(true);
});
it('returns false if there is no next page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasNextPage } = await gitInspector.getAuthors({});
expect(hasNextPage).toStrictEqual(false);
});
it('returns true if there is a previous page', async () => {
await testDir.gitInit();
await testDir.gitCommit(undefined, 'test1 <test1@example.com>');
await testDir.gitCommit(undefined, 'test2 <test2@example.com>');
await testDir.gitCommit(undefined, 'test3 <test3@example.com>');
await testDir.gitCommit(undefined, 'test4 <test4@example.com>');
const gitInspector = new GitInspector(testDir.path);
const { hasPreviousPage } = await gitInspector.getAuthors({ pagination: { page: 1, perPage: 2 } });
expect(hasPreviousPage).toStrictEqual(true);
});
it('returns false if there is a previous page', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
const { hasPreviousPage } = await gitInspector.getAuthors({});
expect(hasPreviousPage).toStrictEqual(false);
});
it('throws an error if the path does not exist', async () => {
const gitInspector = new GitInspector(path.join(testDir.path, 'non-existing-dir'));
await expect(gitInspector.getAuthors({})).rejects.toThrow('Cannot use simple-git on a directory that does not exist');
});
it('throws an error if the path is not a repository', async () => {
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getAuthors({})).rejects.toThrow();
});
it('throws an error if there are no commits in the repository', async () => {
await testDir.gitInit();
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getAuthors({})).rejects.toThrow("fatal: your current branch 'master' does not have any commits yet");
});
it('throws an error if filtering is requested', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getAuthors({ filter: {} })).rejects.toThrow('filtering and sorting not implemented');
});
it('throws an error if sorting is requested', async () => {
await testDir.gitInit();
await testDir.gitCommit();
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getAuthors({ sort: {} })).rejects.toThrow('filtering and sorting not implemented');
});
});
describe('#getAllTags', () => {
it('returns all repository tags', async () => {
await testDir.gitInit();
await testDir.gitCommit();
await testDir.gitTag('1.0.0');
const gitInspector = new GitInspector(testDir.path);
const tags = gitInspector.getAllTags();
const commit = (await testDir.gitLog()).latest?.hash;
await expect(tags).resolves.toStrictEqual([{ tag: '1.0.0', commit }]);
});
it('throws an error if the path does not exist', async () => {
const gitInspector = new GitInspector(path.join(testDir.path, 'non-existing-dir'));
await expect(gitInspector.getAllTags()).rejects.toThrow('Cannot use simple-git on a directory that does not exist');
});
it('throws an error if the path is not a repository', async () => {
const gitInspector = new GitInspector(testDir.path);
await expect(gitInspector.getAllTags()).rejects.toThrow();
});
});
});
class TestDir {
readonly path: string;
constructor() {
this.path = fs.mkdtempSync(path.join(os.tmpdir(), 'dx-scanner'));
}
async gitInit(user?: { name: string; email: string }) {
if (user === undefined) {
user = { name: 'test', email: 'test@example.com' };
}
await git(this.path).init();
await git(this.path).addConfig('user.name', user.name);
await git(this.path).addConfig('user.email', user.email);
}
async gitAddFile(repoPath: string) {
await fs.promises.writeFile(path.join(this.path, repoPath), '');
await git(this.path).add(repoPath);
}
async gitCommit(message?: string, author?: string) {
if (message === undefined) {
message = 'msg';
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const options: { [key: string]: any } = { '--allow-empty': true };
if (author !== undefined) {
options['--author'] = author;
}
await git(this.path).commit(message, undefined, options);
}
gitLog() {
return git(this.path).log();
}
async gitTag(name: string) {
await git(this.path).tag([name]);
}
} | the_stack |
import { MichelsonMap } from '@taquito/taquito';
import { char2Bytes, InvalidUri } from '@taquito/tzip16';
import { Tzip12ContractAbstraction } from '../src/tzip12-contract-abstraction';
import { InvalidTokenMetadata, TokenIdNotFound, TokenMetadataNotFound } from '../src/tzip12-errors';
describe('Tzip12 contract abstraction test', () => {
let mockContractAbstraction: any = {};
let mockContext: any = {};
let mockTzip16ContractAbstraction: any = {};
let tzip12Abs: Tzip12ContractAbstraction;
let mockMichelsonStorageView: any;
let mockMetadataProvider: {
provideMetadata: jest.Mock<any, any>;
};
let mockSchema: {
FindFirstInTopLevelPair: jest.Mock<any, any>;
};
let mockRpcContractProvider: {
getBigMapKeyByID: jest.Mock<any, any>;
};
beforeEach(() => {
mockMetadataProvider = {
provideMetadata: jest.fn()
};
mockTzip16ContractAbstraction = {
getMetadata: jest.fn(),
metadataViews: jest.fn()
};
mockMichelsonStorageView = {
executeView: jest.fn()
};
mockSchema = {
FindFirstInTopLevelPair: jest.fn()
};
mockRpcContractProvider = {
getBigMapKeyByID: jest.fn()
};
mockContractAbstraction.address = 'test';
mockContractAbstraction['schema'] = mockSchema;
mockContractAbstraction['script'] = {
script: {
code: [],
storage: {
prim: 'Pair',
args: [
{
int: '20350'
},
[]
]
}
}
};
tzip12Abs = new Tzip12ContractAbstraction(mockContractAbstraction, mockContext);
tzip12Abs['_tzip16ContractAbstraction'] = mockTzip16ContractAbstraction;
mockContext['metadataProvider'] = mockMetadataProvider;
mockContext['contract'] = mockRpcContractProvider;
});
it('Test 1 for getContractMetadata(): Should return the `Tzip-016` contract metadata', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: { name: 'Taquito test' }
});
expect(await tzip12Abs['getContractMetadata']()).toEqual(
{ name: 'Taquito test' }
);
done();
});
it('Test 2 for getContractMetadata(): Should return undefined when the contract has no `Tzip-016` metadata', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockImplementation(() => {
throw new Error();
});
expect(await tzip12Abs['getContractMetadata']()).toBeUndefined();
done();
});
it('Test 1 for isTzip12Compliant(): Should return true', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: {
name: 'Taquito test',
interfaces: ["TZIP-012[-<version-info>]"]
}
});
expect(await tzip12Abs.isTzip12Compliant()).toEqual(true);
done();
});
it('Test 2 for isTzip12Compliant(): Should return true', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: {
name: 'Taquito test',
interfaces: ["TZIP-test", "TZIP-012[-<version-info>]", "TZIP-test2"]
}
});
expect(await tzip12Abs.isTzip12Compliant()).toEqual(true);
done();
});
it('Test 3 for isTzip12Compliant(): Should return false when no interfaces property', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: {
name: 'Taquito test'
}
});
expect(await tzip12Abs.isTzip12Compliant()).toEqual(false);
done();
});
it('Test 4 for isTzip12Compliant(): Should return false when no TZIP-012 in interfaces property', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: {
name: 'Taquito test',
interfaces: ["TZIP-test"]
}
});
expect(await tzip12Abs.isTzip12Compliant()).toEqual(false);
done();
});
it('Test 1 for executeTokenMetadataView(): Should properly return the TokenMetadata', async (done) => {
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
// takes as parameter the nat token-id and returns the (pair nat (map string bytes)) value
mockMichelsonStorageView.executeView.mockResolvedValue({
'0': '0',
'1': tokenMap
})
const tokenMetadata = await tzip12Abs['executeTokenMetadataView'](mockMichelsonStorageView, 0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 2 for executeTokenMetadataView(): Should throw TokenIdNotFound', async (done) => {
mockMichelsonStorageView.executeView.mockImplementation(() => {
throw new Error();
});
expect(tzip12Abs['executeTokenMetadataView'](mockMichelsonStorageView, 0)).rejects.toEqual(new TokenIdNotFound(0));
done();
});
it('Test 3 for executeTokenMetadataView(): should throw TokenMetadataNotFound if the type of the view result is wrong (no map)', async (done) => {
mockMichelsonStorageView.executeView.mockResolvedValue({
'0': '0',
'1': 'I am not a map'
})
expect(tzip12Abs['executeTokenMetadataView'](mockMichelsonStorageView, 0)).rejects.toEqual(new TokenMetadataNotFound(mockContractAbstraction.address));
done();
});
it('Test 4 for executeTokenMetadataView(): should throw TokenMetadataNotFound if the type of the view result is wrong', async (done) => {
mockMichelsonStorageView.executeView.mockResolvedValue('wrong type')
expect(tzip12Abs['executeTokenMetadataView'](mockMichelsonStorageView, 0)).rejects.toEqual(new TokenMetadataNotFound(mockContractAbstraction.address));
done();
});
it('Test 5 for executeTokenMetadataView(): Should properly return the TokenMetadata when the map contains a URI', async (done) => {
mockMetadataProvider.provideMetadata.mockResolvedValue({
uri: 'https://test',
metadata: {
name: 'Taquito test',
decimals: 3,
symbol: 'XTZ!',
more: 'more data'
}
});
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('', char2Bytes('https://storage.googleapis.com/tzip-16/token-metadata.json'));
mockMichelsonStorageView.executeView.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
})
const tokenMetadata = await tzip12Abs['executeTokenMetadataView'](mockMichelsonStorageView, 0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito test',
decimals: 3,
symbol: 'XTZ!',
more: 'more data'
});
done();
});
it('Test 1 for fetchTokenMetadataFromUri(): Should warn that the URI is invalid and return undefined', async (done) => {
const tokenMap = new MichelsonMap();
tokenMap.set('test', char2Bytes('test'));
tokenMap.set('', char2Bytes('invalidURI'));
tokenMap.set('testtest', char2Bytes('testtest'));
mockMetadataProvider.provideMetadata.mockImplementation(() => {
throw new InvalidUri(char2Bytes('invalidURI'));
});
const tokenMetadata = await tzip12Abs['fetchTokenMetadataFromUri'](tokenMap as MichelsonMap<string, string>);
expect(tokenMetadata).toBeUndefined();
done();
});
it('Test 2 for fetchTokenMetadataFromUri(): Should return undefined when no URI', async (done) => {
const tokenMap = new MichelsonMap();
tokenMap.set('test', char2Bytes('test'));
tokenMap.set('testtest', char2Bytes('testtest'));
const tokenMetadata = await tzip12Abs['fetchTokenMetadataFromUri'](tokenMap as MichelsonMap<string, string>);
expect(tokenMetadata).toBeUndefined();
done();
});
it('Test 1 for retrieveTokenMetadataFromView(): Should properly return token metadata from token_metadata view', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: { name: 'Taquito test' }
});
mockTzip16ContractAbstraction.metadataViews.mockResolvedValue({ 'token_metadata': () => mockMichelsonStorageView });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
// takes as parameter the nat token-id and returns the (pair nat (map string bytes)) value
mockMichelsonStorageView.executeView.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
})
const tokenMetadata = await tzip12Abs['retrieveTokenMetadataFromView'](0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 2 for retrieveTokenMetadataFromView(): Should return undefined when there is no contract metadata', async (done) => {
const tokenMetadata = await tzip12Abs['retrieveTokenMetadataFromView'](0);
expect(tokenMetadata).toBeUndefined();
done();
});
it('Test 3 for retrieveTokenMetadataFromView(): Should return undefined when there is no token_metadata view', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://test',
metadata: { name: 'Taquito test' }
});
mockTzip16ContractAbstraction.metadataViews.mockResolvedValue({});
const tokenMetadata = await tzip12Abs['retrieveTokenMetadataFromView'](0);
expect(tokenMetadata).toBeUndefined();
done();
});
it('Test 1 for retrieveTokenMetadataFromBigMap(): Should succeed to return the token metadata', async (done) => {
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
});
const tokenMetadata = await tzip12Abs['retrieveTokenMetadataFromBigMap'](0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 2 for retrieveTokenMetadataFromBigMap(): Should throw TokenMetadataNotFound', async (done) => {
mockSchema.FindFirstInTopLevelPair.mockReturnValue(undefined);
try {
await tzip12Abs['retrieveTokenMetadataFromBigMap'](0)
} catch (err) {
expect(err).toBeInstanceOf(TokenMetadataNotFound)
}
done();
});
it('Test 3 for retrieveTokenMetadataFromBigMap(): Should throw TokenIdNotFound', async (done) => {
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
mockRpcContractProvider.getBigMapKeyByID.mockImplementation(() => {
throw new Error();
});
expect(tzip12Abs['retrieveTokenMetadataFromBigMap'](0)).rejects.toEqual(new TokenIdNotFound(0));
done();
});
it('Test 4 for retrieveTokenMetadataFromBigMap(): Should throw TokenIdNotFound', async (done) => {
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue('I am not a pair');
expect(tzip12Abs['retrieveTokenMetadataFromBigMap'](0)).rejects.toEqual(new TokenIdNotFound(0));
done();
});
it('Test 1 for getTokenMetadata(): Should succeed to fetch the token metadata', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockImplementation(() => {
throw new Error();
});
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
});
const tokenMetadata = await tzip12Abs.getTokenMetadata(0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 2 for getTokenMetadata(): Should succeed to fetch the token metadata from URI and token_info map', async (done) => {
mockMetadataProvider.provideMetadata.mockResolvedValue({
uri: 'https://test',
metadata: { name: 'Taquito test' }
});
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('', char2Bytes('https://test'));
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
});
const tokenMetadata = await tzip12Abs.getTokenMetadata(0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito test',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 3 for getTokenMetadata(): Should succeed to fetch the token metadata from URI and token_info map', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockResolvedValue({
uri: 'https://contractMetadata',
metadata: { name: 'Contract metadata' }
});
mockMetadataProvider.provideMetadata.mockResolvedValue({
uri: 'https://test',
metadata: { name: 'Taquito test' }
});
mockTzip16ContractAbstraction.metadataViews.mockResolvedValue({ 'token_metadata': () => mockMichelsonStorageView });
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('', char2Bytes('https://test'));
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
tokenMap.set('decimals', char2Bytes('3'));
// takes as parameter the nat token-id and returns the (pair nat (map string bytes)) value
mockMichelsonStorageView.executeView.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
})
const tokenMetadata = await tzip12Abs.getTokenMetadata(0);
expect(tokenMetadata).toEqual({
token_id: 0,
name: 'Taquito test',
symbol: 'XTZ',
decimals: 3
});
done();
});
it('Test 4 for getTokenMetadata(): Should throw InvalidTokenMetadata', async (done) => {
mockTzip16ContractAbstraction.getMetadata.mockImplementation(() => {
throw new Error();
});
mockSchema.FindFirstInTopLevelPair.mockReturnValue({ int: '20350' });
const tokenMap = new MichelsonMap({ prim: "map", args: [{ prim: "string" }, { prim: "bytes" }] });
tokenMap.set('name', char2Bytes('Taquito'));
tokenMap.set('symbol', char2Bytes('XTZ'));
mockRpcContractProvider.getBigMapKeyByID.mockResolvedValue({
'token_id': '0',
'token_info': tokenMap
});
try {
await tzip12Abs.getTokenMetadata(0)
} catch (err) {
expect (err).toBeInstanceOf(InvalidTokenMetadata)
}
done();
});
}); | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { Highlight } from '../../../src/chart/user-interaction/high-light';
import { SeriesModel } from '../../../src/chart/series/chart-series-model';
import { LineSeries } from '../../../src/chart/series/line-series';
import { StepLineSeries } from '../../../src/chart/series/step-line-series';
import { ColumnSeries } from '../../../src/chart/series/column-series';
import { StackingColumnSeries } from '../../../src/chart/series/stacking-column-series';
import { StackingAreaSeries } from '../../../src/chart/series/stacking-area-series';
import { AreaSeries } from '../../../src/chart/series/area-series';
import { Legend } from '../../../src/chart/legend/legend';
import { MouseEvents } from '../base/events.spec';
import { DataEditing } from '../../../src/chart/user-interaction/data-editing';
import { firstSeries, secondSeries, thirdSeries } from '../base/data.spec';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { EmitType } from '@syncfusion/ej2-base';
import { profile, inMB, getMemoryProfile } from '../../common.spec';
import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface';
Chart.Inject(
LineSeries, DataEditing, StepLineSeries, ColumnSeries, AreaSeries, StackingAreaSeries, Highlight,
StackingColumnSeries, Legend
);
let seriesCollection: SeriesModel[] = [];
let colors: string[] = ['#663AB6', '#EB3F79', '#F8AB1D', '#B82E3D', '#049CB1', '#F2424F', '#C2C924', '#3DA046', '#074D67', '#02A8F4'];
seriesCollection = [
{
name: 'First',
width: 5,
animation: { enable: false },
selectionStyle: null,
fill: colors[0],
dataSource: firstSeries, xName: 'x', yName: 'y',
type: 'Column'
},
{
name: 'Second',
width: 10,
visible: true,
selectionStyle: null,
animation: { enable: false },
fill: colors[5],
dataSource: secondSeries, xName: 'x', yName: 'y',
type: 'Column'
},
{
name: 'Third',
width: 5,
animation: { enable: false },
selectionStyle: null,
fill: colors[8],
dataSource: thirdSeries, xName: 'x', yName: 'y',
type: 'Column'
}
];
describe('Chart Control Highlight ', () => {
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;
}
});
let id: string = 'ej2Container';
let selection: string = id + '_ej2_chart_highlight_series_';
let chartObj: Chart;
let element: HTMLElement;
let selected: HTMLCollection;
let i: number = 0;
let j: number = 0;
let loaded: EmitType<ILoadedEventArgs>;
let trigger: MouseEvents = new MouseEvents();
let chartContainer: HTMLElement;
beforeAll(() => {
chartContainer = createElement('div', { id: id });
document.body.appendChild(chartContainer);
chartObj = new Chart({
series: seriesCollection,
primaryXAxis: { minimum: 2004, maximum: 2012 },
primaryYAxis: { rangePadding: 'None' },
height: '500',
width: '800',
loaded: loaded,
highlightMode: 'Point',
isMultiSelect: false,
legendSettings: { visible: true, toggleVisibility: false },
});
chartObj.appendTo('#' + id);
});
afterAll(() => {
chartObj.destroy();
chartContainer.remove();
});
it('Highlight Mode Point', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_0' + '_Point_3');
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + '0').length).toBe(2);
element = document.getElementById(id + '_Series_0' + '_Point_5');
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + '0').length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Highlight Mode Cluster', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_0' + '_Point_5');
trigger.mousemovetEvent(element, 0, 0);
element = document.getElementById(id + '_Series_1' + '_Point_2');
trigger.mousemovetEvent(element, 0, 0);
for (let i: number = 0; i < seriesCollection.length; i++) {
expect(document.getElementsByClassName(selection + i).length).toBe(2);
}
done();
};
chartObj.highlightMode = 'Cluster';
chartObj.loaded = loaded;
chartObj.highlightModule.selectedDataIndexes = [];
chartObj.refresh();
});
it('Selection Mode Series', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_0' + '_Point_3');
trigger.mousemovetEvent(element, 0, 0);
element = document.getElementById(id + '_Series_1' + '_Point_3');
trigger.mousemovetEvent(element, 0, 0);
selected = document.getElementsByClassName(selection + '1');
expect(selected.length).toBe(2);
expect(selected[0].childNodes.length).toBe(8);
done();
};
chartObj.highlightMode = 'Series';
chartObj.loaded = loaded;
chartObj.highlightModule.selectedDataIndexes = [];
chartObj.refresh();
});
// it('Selected DataBind cluster', (done: Function) => {
// chartObj.highlightMode = 'Cluster';
// chartObj.dataBind();
// for (i = 0; i < chartObj.series.length; i++) {
// expect(document.getElementsByClassName(selection + i).length).toBe(2);
// }
// done();
// });
it('Selected DataBind cluster to series', (done: Function) => {
chartObj.highlightMode = 'Series';
chartObj.dataBind();
selected = document.getElementsByClassName(selection + 1);
expect(selected.length).toBe(2);
expect(selected[1].id.indexOf('legend') > 1).toBe(true);
done();
});
// it('Selected DataBind series to point', (done: Function) => {
// element = document.getElementById(id + '_Series_1_Point_' + 3);
// trigger.mousemovetEvent(element, 0, 0);
// chartObj.highlightMode = 'Point';
// chartObj.dataBind();
// expect(document.getElementsByClassName(selection + '0').length).toBe(0);
// expect(document.getElementsByClassName(selection + '1').length).toBe(2);
// expect(document.getElementsByClassName(selection + '2').length).toBe(0);
// done();
// });
// it('Selected DataBind point to series', (done: Function) => {
// element = document.getElementById(id + '_Series_0_Point_' + 2);
// trigger.mousemovetEvent(element, 0, 0);
// chartObj.highlightMode = 'Series';
// chartObj.dataBind();
// expect(document.getElementsByClassName(selection + '0').length).toBe(2);
// expect(document.getElementsByClassName(selection + '1').length).toBe(0);
// expect(document.getElementsByClassName(selection + '2').length).toBe(0);
// done();
// });
// it('Selected DataBind series to cluster', (done: Function) => {
// element = document.getElementById(id + '_Series_0_Point_' + 4);
// trigger.mousemovetEvent(element, 0, 0);
// chartObj.highlightMode = 'Cluster';
// chartObj.dataBind();
// for (i = 0; i < chartObj.series.length; i++) {
// expect(document.getElementsByClassName(selection + i).length).toBe(2);
// }
// done();
// });
// it('Selected DataBind cluster to point', (done: Function) => {
// chartObj.highlightMode = 'Point';
// chartObj.dataBind();
// expect(document.getElementsByClassName(selection + 0).length).toBe(2);
// expect(document.getElementsByClassName(selection + 1).length).toBe(0);
// expect(document.getElementsByClassName(selection + 2).length).toBe(0);
// element = document.getElementById(id + '_Series_1_Point_' + 4);
// trigger.mousemovetEvent(element, 0, 0);
// expect(document.getElementsByClassName(selection + 0).length).toBe(0);
// expect(document.getElementsByClassName(selection + 1).length).toBe(2);
// expect(document.getElementsByClassName(selection + 2).length).toBe(0);
// done();
// });
it('Selected DataBind point multi select false', (done: Function) => {
chartObj.isMultiSelect = false;
chartObj.dataBind();
expect(document.getElementsByClassName(selection + 0).length).toBe(0);
expect(document.getElementsByClassName(selection + 1).length).toBe(2);
expect(document.getElementsByClassName(selection + 2).length).toBe(0);
done();
});
it('Selected refresh clear selection', (done: Function) => {
loaded = () => {
for (i = 0; i < chartObj.series.length; i++) {
expect(document.getElementsByClassName(selection + i).length).toBe(0);
}
done();
};
chartObj.loaded = loaded;
chartObj.highlightModule.selectedDataIndexes = [];
chartObj.refresh();
});
it('Patterns with Dots', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Dots_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_1_Point_' + 4);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 1).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Dots';
chartObj.highlightMode = 'Point';
chartObj.refresh();
});
it('Patterns with DiagonalForward', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_DiagonalForward_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 4);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'DiagonalForward';
chartObj.refresh();
});
it('Patterns with Crosshatch', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Crosshatch_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_2_Point_' + 4);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Crosshatch';
chartObj.refresh();
});
it('Patterns with Pacman', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Pacman_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 0);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Pacman';
chartObj.refresh();
});
it('Patterns with DiagonalBackward', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_DiagonalBackward_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 6);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'DiagonalBackward';
chartObj.refresh();
});
it('Patterns with Grid', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Grid_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 5);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Grid';
chartObj.refresh();
});
it('Patterns with Turquoise', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[1].id === 'ej2Container_Turquoise_Selection_1').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 1);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Turquoise';
chartObj.highlightMode = 'Series';
chartObj.refresh();
});
it('Patterns with Star', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Star_Selection_0').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 1);
trigger.mousemovetEvent(element, 0, 0);
for (i = 0; i < chartObj.series.length; i++) {
expect(document.getElementsByClassName(selection + i).length).toBe(2);
}
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Star';
chartObj.highlightMode = 'Cluster';
chartObj.refresh();
});
it('Patterns with Triangle', (done: Function) => {
loaded = () => {
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[2].id === 'ej2Container_Triangle_Selection_2').toBe(true);
element = document.getElementById(id + '_Series_0_Point_' + 1);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 0).length).toBe(2);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Triangle';
chartObj.highlightMode = 'Point';
chartObj.refresh();
});
it('Patterns with Chessboard', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 5);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[2].id === 'ej2Container_Chessboard_Selection_2').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Chessboard';
chartObj.refresh();
});
it('Patterns with Circle', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_0_Point_' + 2);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + '0').length).toBe(2);
expect(document.getElementsByClassName(selection + '1').length).toBe(0);
expect(document.getElementsByClassName(selection + '2').length).toBe(0);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Circle_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightMode = 'Series';
chartObj.highlightPattern = 'Circle';
chartObj.refresh();
});
it('Patterns with Tile', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 3);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Tile_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Tile';
chartObj.refresh();
});
it('Patterns with HorizontalDash', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 5);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_HorizontalDash_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'HorizontalDash';
chartObj.refresh();
});
it('Patterns with VerticalDash', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 2);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_VerticalDash_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'VerticalDash';
chartObj.highlightMode = 'Point';
chartObj.refresh();
});
it('Patterns with Rectangle', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 3);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Rectangle_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Rectangle';
chartObj.isMultiSelect = false;
chartObj.refresh();
});
it('Patterns with Box', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_2_Point_' + 0);
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 2).length).toBe(2);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Box_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'Box';
chartObj.refresh();
});
it('Patterns with VerticalStripe', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_0_Point_' + 5 + '_Symbol');
let chartArea: Element = document.getElementById(id + '_ChartAreaBorder');
let y: number = parseFloat(element.getAttribute('cy')) + parseFloat(chartArea.getAttribute('y')) + chartContainer.offsetTop;
let x: number = parseFloat(element.getAttribute('cx')) + parseFloat(chartArea.getAttribute('x')) + chartContainer.offsetLeft;
trigger.mousemovetEvent(element, Math.ceil(x), Math.ceil(y));
expect(document.getElementsByClassName(selection + 0).length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_VerticalStripe_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightPattern = 'VerticalStripe';
chartObj.highlightMode = 'Series';
for (let series of chartObj.series) {
series.type = 'Line';
series.marker.visible = true;
series.marker.height = 20;
series.marker.width = 20;
}
chartObj.refresh();
});
it('Patterns with HorizontalStripe', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_1_Point_' + 4 + '_Symbol');
trigger.mousemovetEvent(element, 0, 0);
expect(document.getElementsByClassName(selection + 1).length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_HorizontalStripe_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
for (let series of chartObj.series) {
series.type = 'Area';
}
chartObj.selectionPattern = 'None';
chartObj.selectionMode = 'None';
chartObj.highlightMode = 'Series';
chartObj.highlightPattern = 'HorizontalStripe';
chartObj.refresh();
});
it('Patterns with Bubble', (done: Function) => {
loaded = () => {
element = document.getElementById(id + '_Series_1_Point_' + 5 + '_Symbol');
let chartArea: Element = document.getElementById(id + '_ChartAreaBorder');
let y: number = parseFloat(element.getAttribute('cy')) + parseFloat(chartArea.getAttribute('y')) + chartContainer.offsetTop;
let x: number = parseFloat(element.getAttribute('cx')) + parseFloat(chartArea.getAttribute('x')) + chartContainer.offsetLeft;
trigger.clickEvent(element);
trigger.mousemovetEvent(element, Math.ceil(x), Math.ceil(y));
expect(document.getElementsByClassName(selection + 1).length).toBe(4);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern').length).toBe(3);
expect(document.getElementsByTagName('svg')[0].querySelectorAll('pattern')[0].id === 'ej2Container_Bubble_Selection_0').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.highlightMode = 'Point';
chartObj.highlightPattern = 'Bubble';
chartObj.refresh();
});
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);
})
}); | the_stack |
module es {
/** 2d 向量 */
export class Vector2 implements IEquatable<Vector2> {
public x: number = 0;
public y: number = 0;
/**
* 从两个值构造一个带有X和Y的二维向量。
* @param x 二维空间中的x坐标
* @param y 二维空间的y坐标
*/
constructor(x: number = 0, y: number = 0) {
this.x = x;
this.y = y;
}
public static get zero() {
return new Vector2(0, 0);
}
public static get one() {
return new Vector2(1, 1);
}
public static get unitX() {
return new Vector2(1, 0);
}
public static get unitY() {
return new Vector2(0, 1);
}
public static get up() {
return new Vector2(0, -1);
}
public static get down() {
return new Vector2(0, 1);
}
public static get left() {
return new Vector2(-1, 0);
}
public static get right() {
return new Vector2(1, 0);
}
/**
*
* @param value1
* @param value2
*/
public static add(value1: Vector2, value2: Vector2) {
let result: Vector2 = Vector2.zero;
result.x = value1.x + value2.x;
result.y = value1.y + value2.y;
return result;
}
/**
*
* @param value1
* @param value2
*/
public static divide(value1: Vector2, value2: Vector2) {
let result: Vector2 = Vector2.zero;
result.x = value1.x / value2.x;
result.y = value1.y / value2.y;
return result;
}
public static divideScaler(value1: Vector2, value2: number) {
let result: Vector2 = Vector2.zero;
result.x = value1.x / value2;
result.y = value1.y / value2;
return result;
}
/**
* 返回两个向量之间距离的平方
* @param value1
* @param value2
*/
public static sqrDistance(value1: Vector2, value2: Vector2) {
return Math.pow(value1.x - value2.x, 2) + Math.pow(value1.y - value2.y, 2);
}
/**
* 将指定的值限制在一个范围内
* @param value1
* @param min
* @param max
*/
public static clamp(value1: Vector2, min: Vector2, max: Vector2) {
return new Vector2(MathHelper.clamp(value1.x, min.x, max.x),
MathHelper.clamp(value1.y, min.y, max.y));
}
/**
* 创建一个新的Vector2,其中包含指定向量的线性插值
* @param value1 第一个向量
* @param value2 第二个向量
* @param amount 加权值(0.0-1.0之间)
* @returns 指定向量的线性插值结果
*/
public static lerp(value1: Vector2, value2: Vector2, amount: number) {
return new Vector2(MathHelper.lerp(value1.x, value2.x, amount), MathHelper.lerp(value1.y, value2.y, amount));
}
/**
* 创建一个新的Vector2,其中包含指定矢量的线性插值
* @param value1
* @param value2
* @param amount
* @returns
*/
public static lerpPrecise(value1: Vector2, value2: Vector2, amount: number) {
return new Vector2(MathHelper.lerpPrecise(value1.x, value2.x, amount),
MathHelper.lerpPrecise(value1.y, value2.y, amount));
}
/**
* 创建一个新的Vector2,该Vector2包含了通过指定的Matrix进行的二维向量变换。
* @param position
* @param matrix
*/
public static transform(position: Vector2, matrix: Matrix2D) {
return new Vector2((position.x * matrix.m11) + (position.y * matrix.m21) + matrix.m31,
(position.x * matrix.m12) + (position.y * matrix.m22) + matrix.m32);
}
/**
* 创建一个新的Vector2,其中包含由指定的Matrix转换的指定法线
* @param normal
* @param matrix
*/
public static transformNormal(normal: Vector2, matrix: Matrix) {
return new Vector2((normal.x * matrix.m11) + (normal.y * matrix.m21),
(normal.x * matrix.m12) + (normal.y * matrix.m22));
}
/**
* 返回两个向量之间的距离
* @param value1
* @param value2
* @returns 两个向量之间的距离
*/
public static distance(vec1: Vector2, vec2: Vector2): number {
return Math.sqrt(Math.pow(vec1.x - vec2.x, 2) + Math.pow(vec1.y - vec2.y, 2));
}
/**
* 返回两个向量之间的角度,单位是度数
* @param from
* @param to
*/
public static angle(from: Vector2, to: Vector2): number {
from = from.normalize();
to = to.normalize();
return Math.acos(MathHelper.clamp(from.dot(to), -1, 1)) * MathHelper.Rad2Deg;
}
/**
* 创建一个包含指定向量反转的新Vector2
* @param value
* @returns 矢量反演的结果
*/
public static negate(value: Vector2) {
value.x = -value.x;
value.y = -value.y;
return value;
}
/**
* 创建一个新的Vector2,其中包含给定矢量和法线的反射矢量
* @param vector
* @param normal
* @returns
*/
public static reflect(vector: Vector2, normal: Vector2) {
let result: Vector2 = es.Vector2.zero;
let val = 2 * ((vector.x * normal.x) + (vector.y * normal.y));
result.x = vector.x - (normal.x * val);
result.y = vector.y - (normal.y * val);
return result;
}
/**
* 创建一个新的Vector2,其中包含指定矢量的三次插值
* @param value1
* @param value2
* @param amount
* @returns
*/
public static smoothStep(value1: Vector2, value2: Vector2, amount: number) {
return new Vector2(MathHelper.smoothStep(value1.x, value2.x, amount),
MathHelper.smoothStep(value1.y, value2.y, amount));
}
public setTo(x: number, y: number) {
this.x = x;
this.y = y;
}
public negate(): Vector2 {
return this.scale(-1);
}
/**
*
* @param value
*/
public add(v: Vector2): Vector2 {
return new Vector2(this.x + v.x, this.y + v.y);
}
public addEqual(v: Vector2): Vector2 {
this.x += v.x;
this.y += v.y;
return this;
}
/**
*
* @param value
*/
public divide(value: Vector2): Vector2 {
return new Vector2(this.x / value.x, this.y / value.y);
}
public divideScaler(value: number): Vector2 {
return new Vector2(this.x / value, this.y / value);
}
/**
*
* @param value
*/
public multiply(value: Vector2): Vector2 {
return new Vector2(value.x * this.x, value.y * this.y);
}
/**
*
* @param value
* @returns
*/
public multiplyScaler(value: number): Vector2 {
this.x *= value;
this.y *= value;
return this;
}
/**
* 从当前Vector2减去一个Vector2
* @param value 要减去的Vector2
* @returns 当前Vector2
*/
public sub(value: Vector2) {
return new Vector2(this.x - value.x, this.y - value.y);
}
public subEqual(v: Vector2): Vector2 {
this.x -= v.x;
this.y -= v.y;
return this;
}
public dot(v: Vector2): number {
return this.x * v.x + this.y * v.y;
}
/**
*
* @param size
* @returns
*/
public scale(size: number): Vector2 {
return new Vector2(this.x * size, this.y * size);
}
public scaleEqual(size: number): Vector2 {
this.x *= size;
this.y *= size;
return this;
}
public transform(matrix: Matrix2D): Vector2 {
return new Vector2(
this.x * matrix.m11 + this.y * matrix.m21 + matrix.m31,
this.x * matrix.m12 + this.y * matrix.m22 + matrix.m32
);
}
public normalize(): Vector2 {
const d = this.distance();
if (d > 0) {
return new Vector2(this.x / d, this.y / d);
} else {
return new Vector2(0, 1);
}
}
/**
* 将这个Vector2变成一个方向相同的单位向量
*/
public normalizeEqual(): Vector2 {
const d = this.distance();
if (d > 0) {
this.setTo(this.x / d, this.y / d);
return this;
} else {
this.setTo(0, 1);
return this;
}
}
public magnitude(): number {
return this.distance();
}
public distance(v?: Vector2): number {
if (!v) {
v = Vector2.zero;
}
return Math.sqrt(Math.pow(this.x - v.x, 2) + Math.pow(this.y - v.y, 2));
}
/**
* 返回该Vector2的平方长度
* @returns 这个Vector2的平方长度
*/
public lengthSquared(): number {
return (this.x * this.x) + (this.y * this.y);
}
/**
* 四舍五入X和Y值
*/
public round(): Vector2 {
return new Vector2(Math.round(this.x), Math.round(this.y));
}
/**
* 返回以自己为中心点的左右角,单位为度
* @param left
* @param right
*/
public angleBetween(left: Vector2, right: Vector2) {
let one = left.sub(this);
let two = right.sub(this);
return Vector2Ext.angle(one, two);
}
/**
* 比较当前实例是否等于指定的对象
* @param other 要比较的对象
* @returns 如果实例相同true 否则false
*/
public equals(other: Vector2, tolerance: number = 0.001): boolean {
return Math.abs(this.x - other.x) <= tolerance && Math.abs(this.y - other.y) <= tolerance;
}
public isValid(): boolean {
return MathHelper.isValid(this.x) && MathHelper.isValid(this.y);
}
/**
* 创建一个新的Vector2,其中包含来自两个向量的最小值
* @param value1
* @param value2
* @returns
*/
public static min(value1: Vector2, value2: Vector2) {
return new Vector2(value1.x < value2.x ? value1.x : value2.x,
value1.y < value2.y ? value1.y : value2.y);
}
/**
* 创建一个新的Vector2,其中包含两个向量的最大值
* @param value1
* @param value2
* @returns
*/
public static max(value1: Vector2, value2: Vector2) {
return new Vector2(value1.x > value2.x ? value1.x : value2.x,
value1.y > value2.y ? value1.y : value2.y);
}
/**
* 创建一个新的Vector2,其中包含Hermite样条插值
* @param value1
* @param tangent1
* @param value2
* @param tangent2
* @param amount
* @returns
*/
public static hermite(value1: Vector2, tangent1: Vector2, value2: Vector2, tangent2: Vector2, amount: number) {
return new Vector2(MathHelper.hermite(value1.x, tangent1.x, value2.x, tangent2.x, amount),
MathHelper.hermite(value1.y, tangent1.y, value2.y, tangent2.y, amount));
}
public static unsignedAngle(from: Vector2, to: Vector2, round: boolean = true) {
from.normalizeEqual();
to.normalizeEqual();
const angle =
Math.acos(MathHelper.clamp(from.dot(to), -1, 1)) * MathHelper.Rad2Deg;
return round ? Math.round(angle) : angle;
}
public clone(): Vector2 {
return new Vector2(this.x, this.y);
}
}
} | the_stack |
import { ManifestBuilder } from "./manifest";
import { VsixManifestBuilder } from "./vsix-manifest-builder";
import { FileDeclaration, PackageSettings, PackageFiles, PackagePart, ResourceSet, ResourcesFile } from "./interfaces";
import { VsixComponents } from "./merger";
import { cleanAssetPath, toZipItemName } from "./utils";
import { LocPrep } from "./loc";
import _ = require("lodash");
import childProcess = require("child_process");
import mkdirp = require("mkdirp");
import os = require("os");
import path = require("path");
import trace = require("../../../lib/trace");
import winreg = require("winreg");
import xml = require("xml2js");
import zip = require("jszip");
import { defer, Deferred } from "../../../lib/promiseUtils";
import { lstat, readdir, readFile, writeFile } from "fs";
import { promisify } from "util";
import { exists } from "../../../lib/fsUtils";
/**
* Facilitates packaging the vsix and writing it to a file
*/
export class VsixWriter {
private manifestBuilders: ManifestBuilder[];
private resources: ResourceSet;
private static VSIX_ADD_FILES_BATCH_SIZE: number = 20;
private static VSO_MANIFEST_FILENAME: string = "extension.vsomanifest";
private static VSIX_MANIFEST_FILENAME: string = "extension.vsixmanifest";
private static CONTENT_TYPES_FILENAME: string = "[Content_Types].xml";
public static DEFAULT_XML_BUILDER_SETTINGS: xml.BuilderOptions = {
indent: " ",
newline: os.EOL,
pretty: true,
xmldec: {
encoding: "utf-8",
standalone: null,
version: "1.0",
},
};
/**
* constructor
* @param any vsoManifest JS Object representing a vso manifest
* @param any vsixManifest JS Object representing the XML for a vsix manifest
*/
constructor(private settings: PackageSettings, components: VsixComponents) {
this.manifestBuilders = components.builders;
this.resources = components.resources;
}
/**
* If outPath is {auto}, generate an automatic file name.
* Otherwise, try to determine if outPath is a directory (checking for a . in the filename)
* If it is, generate an automatic filename in the given outpath
* Otherwise, outPath doesn't change.
* If filename is generated automatically, use fileExt as the extension
*/
public getOutputPath(outPath: string, fileExt: string = "vsix"): string {
// Find the vsix manifest, if it exists
let vsixBuilders = this.manifestBuilders.filter(b => b.getType() === VsixManifestBuilder.manifestType);
let autoName = "extension." + fileExt;
if (vsixBuilders.length === 1) {
let vsixManifest = vsixBuilders[0].getData();
let pub = _.get(vsixManifest, "PackageManifest.Metadata[0].Identity[0].$.Publisher");
let ns = _.get(vsixManifest, "PackageManifest.Metadata[0].Identity[0].$.Id");
let version = _.get(vsixManifest, "PackageManifest.Metadata[0].Identity[0].$.Version");
autoName = `${pub}.${ns}-${version}.${fileExt}`;
}
if (outPath === "{auto}") {
return path.resolve(autoName);
} else {
let basename = path.basename(outPath);
if (basename.indexOf(".") > 0) {
// conscious use of >
return path.resolve(outPath);
} else {
return path.resolve(path.join(outPath, autoName));
}
}
}
private static validatePartName(partName: string): boolean {
let segments = partName.split("/");
if (segments.length === 1 && segments[0] === "[Content_Types].xml") {
return true;
}
// matches most invalid segments.
let re = /(%2f)|(%5c)|(^$)|(%[^0-9a-f])|(%.[^0-9a-f])|(\.$)|([^a-z0-9._~%!$&'()*+,;=:@-])/i;
return segments.filter(segment => re.test(segment)).length === 0;
}
private async writeVsixMetadata(): Promise<string> {
let prevWrittenOutput = null;
const outputPath = this.settings.outputPath;
for (const builder of this.manifestBuilders) {
const metadataResult = builder.getMetadataResult(this.resources.combined);
if (typeof metadataResult === "string") {
if (prevWrittenOutput === outputPath) {
trace.warn(
"Warning: Multiple files written to " +
outputPath +
". Last writer will win. Instead, try providing a folder path in --output-path.",
);
}
const writePath = path.join(outputPath, builder.getPath());
await promisify(writeFile)(writePath, metadataResult, "utf8");
prevWrittenOutput = outputPath;
}
}
return outputPath;
}
/**
* Write a vsix package to the given file name
*/
public async writeVsix(): Promise<string> {
if (this.settings.metadataOnly) {
const outputPath = this.settings.outputPath;
const pathExists = await exists(outputPath);
if (pathExists && !(await promisify(lstat)(outputPath)).isDirectory()) {
throw new Error("--output-path must be a directory when using --metadata-only.");
}
if (!pathExists) {
await promisify(mkdirp)(outputPath, undefined);
}
for (const builder of this.manifestBuilders) {
for (const filePath of Object.keys(builder.files)) {
const fileObj = builder.files[filePath];
if (fileObj.isMetadata) {
const content = fileObj.content || (await promisify(readFile)(fileObj.path, "utf-8"));
const writePath = path.join(this.settings.outputPath, fileObj.partName);
const folder = path.dirname(writePath);
await promisify(mkdirp)(folder, undefined);
await promisify(writeFile)(writePath, content, "utf-8");
}
}
}
return this.writeVsixMetadata();
}
let outputPath = this.getOutputPath(this.settings.outputPath);
let vsix = new zip();
let builderPromises: Promise<void>[] = [];
let seenPartNames = new Set();
this.manifestBuilders.forEach(builder => {
// Avoid the error EMFILE: too many open files
const addPackageFilesBatch = (
paths: string[],
numBatch: number,
batchSize: number,
deferred?: Deferred<void>,
): Promise<void> => {
deferred = deferred || defer<void>();
let readFilePromises = [];
const start = numBatch * batchSize;
const end = Math.min(paths.length, start + batchSize);
for (let i = start; i < end; i++) {
const path = paths[i];
let itemName = toZipItemName(builder.files[path].partName);
if (!VsixWriter.validatePartName(itemName)) {
let eol = require("os").EOL;
throw new Error(
"Part Name '" +
itemName +
"' is invalid. Please check the following: " +
eol +
"1. No whitespace or any of these characters: #^[]<>?" +
eol +
"2. Cannot end with a period." +
eol +
"3. No percent-encoded / or \\ characters. Additionally, % must be followed by two hex characters.",
);
}
if (itemName.indexOf(" "))
if (!builder.files[path].content) {
let readFilePromise = promisify(readFile)(path).then(result => {
if (!seenPartNames.has(itemName)) {
vsix.file(itemName, result);
seenPartNames.add(itemName);
}
if ((builder.files[path] as any)._additionalPackagePaths) {
for (const p of (builder.files[path] as any)._additionalPackagePaths) {
let additionalItemName = toZipItemName(p);
if (!seenPartNames.has(additionalItemName)) {
vsix.file(additionalItemName, result);
seenPartNames.add(additionalItemName);
}
}
}
});
readFilePromises.push(readFilePromise);
} else {
if (!seenPartNames.has(itemName)) {
vsix.file(itemName, builder.files[path].content);
seenPartNames.add(itemName);
}
if ((builder.files[path] as any)._additionalPackagePaths) {
for (const p of (builder.files[path] as any)._additionalPackagePaths) {
let additionalItemName = toZipItemName(p);
if (!seenPartNames.has(additionalItemName)) {
vsix.file(additionalItemName, builder.files[path].content);
seenPartNames.add(additionalItemName);
}
}
}
readFilePromises.push(Promise.resolve<void>(null));
}
}
Promise.all(readFilePromises)
.then(function() {
if (end < paths.length) {
// Next batch
addPackageFilesBatch(paths, numBatch + 1, batchSize, deferred);
} else {
deferred.resolve(null);
}
})
.catch(function(err) {
deferred.reject(err);
});
return deferred.promise;
};
// Add the package files in batches
let builderPromise = addPackageFilesBatch(Object.keys(builder.files), 0, VsixWriter.VSIX_ADD_FILES_BATCH_SIZE).then(
() => {
// Add the manifest itself
vsix.file(toZipItemName(builder.getPath()), builder.getResult(this.resources.combined));
},
);
builderPromises.push(builderPromise);
});
return Promise.all(builderPromises).then(() => {
trace.debug("Writing vsix to: %s", outputPath);
return new Promise((resolve, reject) => {
mkdirp(path.dirname(outputPath), (err, made) => {
if (err) {
reject(err);
} else {
resolve(made);
}
});
}).then(async () => {
let buffer = await vsix.generateAsync({
type: "nodebuffer",
compression: "DEFLATE",
});
return promisify(writeFile)(outputPath, buffer).then(() => outputPath);
});
});
}
/**
* For each folder F under the localization folder (--loc-root),
* look for a resources.resjson file within F. If it exists, split the
* resources.resjson into one file per manifest. Add
* each to the vsix archive as F/<manifest_loc_path> and F/Extension.vsixlangpack
*/
private addResourceStrings(vsix: zip): Promise<void[]> {
// Make sure locRoot is set, that it refers to a directory, and
// iterate each subdirectory of that.
if (!this.settings.locRoot) {
return Promise.resolve<void[]>(null);
}
let stringsPath = path.resolve(this.settings.locRoot);
// Check that --loc-root exists and is a directory.
return exists(stringsPath)
.then<boolean>(exists => {
if (exists) {
return promisify(lstat)(stringsPath).then(stats => {
if (stats.isDirectory()) {
return true;
}
});
} else {
return false;
}
})
.then<void[]>(stringsFolderExists => {
if (!stringsFolderExists) {
return Promise.resolve<void[]>(null);
}
// stringsPath exists and is a directory - read it.
return promisify(readdir)(stringsPath).then((files: string[]) => {
let promises: Promise<void>[] = [];
files.forEach(languageTag => {
var filePath = path.join(stringsPath, languageTag);
let promise = promisify(lstat)(filePath).then(fileStats => {
if (fileStats.isDirectory()) {
// We're under a language tag directory within locRoot. Look for
// resources.resjson and use that to generate manfiest files
let resourcePath = path.join(filePath, "resources.resjson");
exists(resourcePath).then(exists => {
if (exists) {
// A resources.resjson file exists in <locRoot>/<language_tag>/
return promisify(readFile)(resourcePath, "utf8").then(contents => {
let resourcesObj = JSON.parse(contents);
// For each language, go through each builder and generate its
// localized resources.
this.manifestBuilders.forEach(builder => {
const locFiles = builder.getLocResult(resourcesObj, null);
locFiles.forEach(locFile => {});
});
let locGen = new LocPrep.LocKeyGenerator(null);
// let splitRes = locGen.splitIntoVsoAndVsixResourceObjs(resourcesObj);
// let locManifestPath = languageTag + "/" + VsixWriter.VSO_MANIFEST_FILENAME;
// vsix.file(toZipItemName(locManifestPath), this.getVsoManifestString(splitRes.vsoResources));
// this.vsixManifest.PackageManifest.Assets[0].Asset.push({
// "$": {
// Lang: languageTag,
// Type: "Microsoft.VisualStudio.Services.Manifest",
// Path: locManifestPath,
// Addressable: "true",
// "d:Source": "File"
// }
// });
// let builder = new xml.Builder(VsixWriter.DEFAULT_XML_BUILDER_SETTINGS);
// let vsixLangPackStr = builder.buildObject(splitRes.vsixResources);
// vsix.file(toZipItemName(languageTag + "/Extension.vsixlangpack"), vsixLangPackStr);
});
} else {
return Promise.resolve<void>(null);
}
});
}
});
promises.push(promise);
});
return Promise.all(promises);
});
});
}
} | the_stack |
import { RequestTypes } from 'detritus-client-rest';
import { ShardClient } from '../client';
import { BaseCollection } from '../collections/basecollection';
import { BaseSet } from '../collections/baseset';
import {
ApplicationCommandOptionTypes,
ApplicationCommandTypes,
DiscordKeys,
InteractionCallbackTypes,
InteractionTypes,
MessageComponentTypes,
INTERACTION_TIMEOUT,
} from '../constants';
import { Snowflake } from '../utils';
import {
BaseStructure,
BaseStructureData,
} from './basestructure';
import { Channel, createChannelFromData } from './channel';
import { Guild } from './guild';
import { Member } from './member';
import { Message } from './message';
import { Role } from './role';
import { User } from './user';
export type InteractionEditOrRespond = RequestTypes.CreateInteractionResponseInnerPayload & RequestTypes.EditWebhookTokenMessage;
const DEFERRED_TYPES = Object.freeze([
InteractionCallbackTypes.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
InteractionCallbackTypes.DEFERRED_UPDATE_MESSAGE,
]);
const keysInteraction = new BaseSet<string>([
DiscordKeys.APPLICATION_ID,
DiscordKeys.CHANNEL_ID,
DiscordKeys.DATA,
DiscordKeys.GUILD_ID,
DiscordKeys.ID,
DiscordKeys.MEMBER,
DiscordKeys.MESSAGE,
DiscordKeys.TOKEN,
DiscordKeys.TYPE,
DiscordKeys.USER,
DiscordKeys.VERSION,
]);
const keysMergeInteraction = new BaseSet<string>([
DiscordKeys.GUILD_ID,
DiscordKeys.MEMBER,
DiscordKeys.TYPE,
]);
/**
* Interaction Structure
* @category Structure
*/
export class Interaction extends BaseStructure {
readonly _keys = keysInteraction;
readonly _keysMerge = keysMergeInteraction;
readonly _deleted: boolean = false;
applicationId: string = '';
channelId?: string;
data?: InteractionDataApplicationCommand | InteractionDataComponent;
guildId?: string;
id: string = '';
member?: Member;
message?: Message;
responded: boolean = false;
responseDeleted?: boolean;
responseId?: string;
token: string = '';
type: InteractionTypes = InteractionTypes.PING;
user!: User;
version: number = 0;
constructor(
client: ShardClient,
data?: BaseStructureData,
isClone?: boolean,
) {
super(client, undefined, isClone);
this.merge(data);
}
get channel(): Channel | null {
if (this.channelId) {
return this.client.channels.get(this.channelId) || null;
}
return null;
}
get createdAt(): Date {
return new Date(this.createdAtUnix);
}
get createdAtUnix(): number {
return Snowflake.timestamp(this.id);
}
get deleted(): boolean {
if (!this._deleted) {
const didTimeout = INTERACTION_TIMEOUT <= (Date.now() - this.createdAtUnix);
if (didTimeout) {
Object.defineProperty(this, '_deleted', {value: didTimeout});
this.client.interactions.delete(this.id);
}
}
return this._deleted;
}
get guild(): Guild | null {
if (this.guildId) {
return this.client.guilds.get(this.guildId) || null;
}
return null;
}
get inDm(): boolean {
return !this.member;
}
get isFromApplicationCommand() {
return this.type === InteractionTypes.APPLICATION_COMMAND;
}
get isFromMessageComponent() {
return this.type === InteractionTypes.MESSAGE_COMPONENT;
}
get response(): Message | null {
if (this.responseId) {
return this.client.messages.get(this.responseId) || null;
}
return null;
}
get userId(): string {
return this.user.id;
}
createMessage(options: RequestTypes.ExecuteWebhook | string = {}) {
return this.client.rest.executeWebhook(this.applicationId, this.token, options);
}
async createResponse(
options: RequestTypes.CreateInteractionResponse | number,
data?: RequestTypes.CreateInteractionResponseInnerPayload | string,
) {
this.responded = true;
try {
if (this.isFromMessageComponent) {
const toAssignData = (typeof(options) === 'object') ? options.data || data : data;
if (typeof(toAssignData) === 'object' && toAssignData.components) {
const listenerId = (this.message) ? this.message.id : '';
Object.assign(toAssignData, {listenerId});
}
}
return await this.client.rest.createInteractionResponse(this.id, this.token, options, data);
} catch(error) {
this.responded = false;
throw error;
}
}
deleteMessage(messageId: string) {
return this.client.rest.deleteWebhookTokenMessage(this.applicationId, this.token, messageId);
}
deleteResponse() {
return this.deleteMessage('@original');
}
editMessage(messageId: string, options: RequestTypes.EditWebhookTokenMessage = {}) {
return this.client.rest.editWebhookTokenMessage(this.applicationId, this.token, messageId, options);
}
editResponse(options: RequestTypes.EditWebhookTokenMessage = {}) {
return this.editMessage('@original', options);
}
editOrRespond(options: InteractionEditOrRespond | string = {}) {
// try respond, try edit, try followup
if (this.responded) {
if (typeof(options) === 'string') {
options = {content: options};
}
return this.editResponse(options);
}
let type: InteractionCallbackTypes = InteractionCallbackTypes.CHANNEL_MESSAGE_WITH_SOURCE;
switch (this.type) {
case InteractionTypes.APPLICATION_COMMAND: type = InteractionCallbackTypes.CHANNEL_MESSAGE_WITH_SOURCE; break;
case InteractionTypes.MESSAGE_COMPONENT: type = InteractionCallbackTypes.UPDATE_MESSAGE; break;
}
return this.respond(type, options);
}
fetchMessage(messageId: string) {
return this.client.rest.fetchWebhookTokenMessage(this.applicationId, this.token, messageId);
}
fetchResponse() {
return this.fetchMessage('@original');
}
reply(options: RequestTypes.ExecuteWebhook | string = {}) {
return this.createMessage(options);
}
respond(
options: RequestTypes.CreateInteractionResponse | number,
data?: RequestTypes.CreateInteractionResponseInnerPayload | string,
) {
return this.createResponse(options, data);
}
mergeValue(key: string, value: any): void {
if (value !== undefined) {
switch (key) {
case DiscordKeys.DATA: {
switch (this.type) {
case InteractionTypes.PING: {
}; break;
case InteractionTypes.APPLICATION_COMMAND: {
value = new InteractionDataApplicationCommand(this, value);
}; break;
case InteractionTypes.MESSAGE_COMPONENT: {
value = new InteractionDataComponent(this, value);
}; break;
}
}; break;
case DiscordKeys.MEMBER: {
value.guild_id = this.guildId as string;
value = new Member(this.client, value, true);
this.user = value.user;
}; break;
case DiscordKeys.MESSAGE: {
value = new Message(this.client, value, true);
}; break;
case DiscordKeys.USER: {
value = new User(this.client, value, true);
}; break;
}
return super.mergeValue(key, value);
}
}
}
const keysInteractionDataApplicationCommand = new BaseSet<string>([
DiscordKeys.ID,
DiscordKeys.NAME,
DiscordKeys.OPTIONS,
DiscordKeys.RESOLVED,
DiscordKeys.TARGET_ID,
DiscordKeys.TYPE,
]);
/**
* Interaction Data Application Command Structure
* @category Structure
*/
export class InteractionDataApplicationCommand extends BaseStructure {
readonly _keys = keysInteractionDataApplicationCommand;
readonly interaction: Interaction;
id: string = '';
name: string = '';
options?: BaseCollection<string, InteractionDataApplicationCommandOption>;
resolved?: InteractionDataApplicationCommandResolved;
targetId?: string;
type: ApplicationCommandTypes = ApplicationCommandTypes.CHAT_INPUT;
constructor(
interaction: Interaction,
data?: BaseStructureData,
isClone?: boolean,
) {
super(interaction.client, undefined, isClone);
this.interaction = interaction;
this.merge(data);
Object.defineProperty(this, 'interaction', {enumerable: false});
}
get fullName(): string {
if (this.options && this.options.length) {
const option = this.options.first()!;
if (option.isSubCommand || option.isSubCommandGroup) {
return `${this.name} ${option.fullName}`;
}
}
return this.name;
}
get isContextCommand(): boolean {
return this.isContextCommandMessage || this.isContextCommandUser;
}
get isContextCommandMessage(): boolean {
return this.type === ApplicationCommandTypes.MESSAGE;
}
get isContextCommandUser(): boolean {
return this.type === ApplicationCommandTypes.USER;
}
get isSlashCommand(): boolean {
return this.type === ApplicationCommandTypes.CHAT_INPUT;
}
mergeValue(key: string, value: any): void {
if (value !== undefined) {
switch (key) {
case DiscordKeys.OPTIONS: {
if (!this.options) {
this.options = new BaseCollection<string, InteractionDataApplicationCommandOption>();
}
this.options.clear();
for (let raw of value) {
const option = new InteractionDataApplicationCommandOption(this, raw, this.isClone);
this.options.set(option.name, option);
}
}; return;
case DiscordKeys.RESOLVED: {
value = new InteractionDataApplicationCommandResolved(this, value, this.isClone);
}; break;
}
return super.mergeValue(key, value);
}
}
toString(): string {
return this.fullName;
}
}
const keysInteractionDataApplicationCommandOption = new BaseSet<string>([
DiscordKeys.NAME,
DiscordKeys.OPTIONS,
DiscordKeys.TYPE,
DiscordKeys.VALUE,
]);
/**
* Interaction Data Application Command Option Structure
* @category Structure
*/
export class InteractionDataApplicationCommandOption extends BaseStructure {
readonly _keys = keysInteractionDataApplicationCommandOption;
readonly interactionData: InteractionDataApplicationCommand;
name: string = '';
options?: BaseCollection<string, InteractionDataApplicationCommandOption>;
type: ApplicationCommandOptionTypes = ApplicationCommandOptionTypes.SUB_COMMAND;
value?: boolean | number | string;
constructor(
interactionData: InteractionDataApplicationCommand,
data?: BaseStructureData,
isClone?: boolean,
) {
super(interactionData.client, undefined, isClone);
this.interactionData = interactionData;
this.merge(data);
Object.defineProperty(this, 'interactionData', {enumerable: false});
}
get fullName(): string {
if (this.isSubCommandGroup && this.options && this.options.length) {
const option = this.options.first()!;
return `${this.name} ${option.fullName}`;
}
return this.name;
}
get isSubCommand(): boolean {
return this.type === ApplicationCommandOptionTypes.SUB_COMMAND;
}
get isSubCommandGroup(): boolean {
return this.type === ApplicationCommandOptionTypes.SUB_COMMAND_GROUP;
}
mergeValue(key: string, value: any): void {
if (value !== undefined) {
switch (key) {
case DiscordKeys.OPTIONS: {
if (!this.options) {
this.options = new BaseCollection<string, InteractionDataApplicationCommandOption>();
}
this.options.clear();
for (let raw of value) {
const option = new InteractionDataApplicationCommandOption(this.interactionData, raw, this.isClone);
this.options.set(option.name, option);
}
}; return;
}
return super.mergeValue(key, value);
}
}
}
const keysInteractionDataApplicationCommandResolved = new BaseSet<string>([
DiscordKeys.CHANNELS,
DiscordKeys.MEMBERS,
DiscordKeys.MESSAGES,
DiscordKeys.ROLES,
DiscordKeys.USERS,
]);
const keysMergeInteractionDataApplicationCommandResolved = new BaseSet<string>([
DiscordKeys.USERS,
]);
/**
* Interaction Data Application Command Resolved Structure
* @category Structure
*/
export class InteractionDataApplicationCommandResolved extends BaseStructure {
readonly _keys = keysInteractionDataApplicationCommandResolved;
readonly _keysMerge = keysMergeInteractionDataApplicationCommandResolved;
readonly interactionData: InteractionDataApplicationCommand;
channels?: BaseCollection<string, Channel>;
members?: BaseCollection<string, Member>;
messages?: BaseCollection<string, Message>;
roles?: BaseCollection<string, Role>;
users?: BaseCollection<string, User>;
constructor(
interactionData: InteractionDataApplicationCommand,
data?: BaseStructureData,
isClone?: boolean,
) {
super(interactionData.client, undefined, isClone);
this.interactionData = interactionData;
this.merge(data);
Object.defineProperty(this, 'interactionData', {enumerable: false});
}
get guildId(): string | null {
return this.interactionData.interaction.guildId || null;
}
mergeValue(key: string, value: any): void {
if (value !== undefined) {
switch (key) {
case DiscordKeys.CHANNELS: {
if (!this.channels) {
this.channels = new BaseCollection();
}
this.channels.clear();
for (let channelId in value) {
let channel: Channel;
if (this.client.channels.has(channelId)) {
channel = this.client.channels.get(channelId)!;
// do we want to just create it like below? or merge the values?
// not sure if discord verifies the data
} else {
value[channelId][DiscordKeys.GUILD_ID] = this.guildId;
channel = createChannelFromData(this.client, value[channelId]);
}
this.channels.set(channelId, channel);
}
}; return;
case DiscordKeys.MEMBERS: {
if (!this.members) {
this.members = new BaseCollection();
}
this.members.clear();
for (let userId in value) {
value[userId][DiscordKeys.GUILD_ID] = this.guildId;
const member = new Member(this.client, value[userId], true);
if (!member.user) {
member.user = (this.users) ? this.users.get(userId)! : this.client.users.get(userId)!;
}
this.members.set(userId, member);
}
}; return;
case DiscordKeys.MESSAGES: {
if (!this.messages) {
this.messages = new BaseCollection();
}
this.messages.clear();
for (let messageId in value) {
value[messageId][DiscordKeys.GUILD_ID] = this.guildId;
const message = new Message(this.client, value[messageId], true);
this.messages.set(messageId, message);
}
}; return;
case DiscordKeys.ROLES: {
if (!this.roles) {
this.roles = new BaseCollection();
}
this.roles.clear();
for (let roleId in value) {
value[roleId][DiscordKeys.GUILD_ID] = this.guildId;
const role = new Role(this.client, value[roleId]);
this.roles.set(roleId, role);
}
}; return;
case DiscordKeys.USERS: {
if (!this.users) {
this.users = new BaseCollection();
}
this.users.clear();
for (let userId in value) {
const user = new User(this.client, value[userId]);
this.users.set(userId, user);
}
}; return;
}
return super.mergeValue(key, value);
}
}
}
const keysInteractionDataComponent = new BaseSet<string>([
DiscordKeys.COMPONENT_TYPE,
DiscordKeys.CUSTOM_ID,
DiscordKeys.VALUES,
]);
/**
* Interaction Data Component Structure
* @category Structure
*/
export class InteractionDataComponent extends BaseStructure {
readonly _keys = keysInteractionDataComponent;
readonly interaction: Interaction;
componentType: MessageComponentTypes = MessageComponentTypes.BUTTON;
customId: string = '';
values?: Array<string>;
constructor(
interaction: Interaction,
data?: BaseStructureData,
isClone?: boolean,
) {
super(interaction.client, undefined, isClone);
this.interaction = interaction;
this.merge(data);
Object.defineProperty(this, 'interaction', {enumerable: false});
}
} | the_stack |
const models = require('../../../../../db/mysqldb/index')
const {
checkEmail,
checkPhoneNum,
checkUrl,
checkPwd
} = require('../../../utils/validators')
import moment from 'moment'
const { resClientJson } = require('../../../utils/resData')
const { sendVerifyCodeMail } = require('../../../utils/sendEmail')
const { random_number, tools } = require('../../../utils/index')
const config = require('../../../../../config')
const Op = require('sequelize').Op
const tokens = require('../../../utils/tokens')
const xss = require('xss')
const lowdb = require('../../../../../db/lowdb/index')
const clientWhere = require('../../../utils/clientWhere')
import {
statusList,
userMessageAction,
userMessageActionText,
modelAction,
virtualInfo,
virtualPlusLess,
modelName,
modelInfo
} from '../../../utils/constant'
const modelNameNum = Object.values(modelName)
import userVirtual from '../../../common/userVirtual'
class User {
static async userSignIn(req: any, res: any, next: any) {
const { no_login } = lowdb
.read()
.get('config')
.value()
let reqDate = req.body
try {
if (!reqDate.email) {
throw new Error('请输入账户')
}
if (!reqDate.password) {
throw new Error('请输入密码')
}
if (no_login === 'no') {
throw new Error('登录功能关闭,请联系管理员开启')
}
if (reqDate.email) {
/* 邮箱登录 */
let oneUser = await models.user.findOne({
where: {
email: reqDate.email
}
})
if (!oneUser) {
throw new Error('账户不存在')
}
if (!oneUser.enable) {
throw new Error('当前用户已被限制登录,请联系管理员修改')
}
if (oneUser) {
if (
tools.encrypt(reqDate.password, config.ENCRYPT_KEY) ===
oneUser.dataValues.password
) {
let token = tokens.ClientSetToken(60 * 60 * 24 * 7, {
uid: oneUser.uid
})
let ip: any = ''
if (req.headers['x-forwarded-for']) {
ip = req.headers['x-forwarded-for'].toString().split(',')[0]
} else {
ip = req.connection.remoteAddress
}
const NowDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
await models.user.update(
{
last_sign_date: new Date(NowDate),
last_sign_ip: ip || ''
},
{
where: {
uid: oneUser.uid // 查询条件
}
}
)
await resClientJson(res, {
state: 'success',
message: '登录成功',
data: {
token
}
})
} else {
resClientJson(res, {
state: 'error',
message: '密码错误'
})
}
} else {
resClientJson(res, {
state: 'error',
message: '账户不存在'
})
}
} else if (reqDate.phone) {
/* 手机号码登录 */
resClientJson(res, {
state: 'error',
message: '暂时未开放手机号码登录'
})
} else {
/* 非手机号码非邮箱 */
resClientJson(res, {
state: 'error',
message: '请输入正确的手机号码或者邮箱'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
// 注册验证码发送
static async userSignUpCode(req: any, res: any, next: any) {
let reqData = req.body
try {
const { on_register } = lowdb
.read()
.get('config')
.value()
if (reqData.email) {
/* 邮箱注册验证码 */
let oneUser = await models.user.findOne({
where: {
email: reqData.email
}
})
if (on_register === 'no') {
throw new Error('注册功能关闭,请联系管理员开启')
}
if (reqData.email) {
if (!checkEmail(reqData.email)) {
throw new Error('请输入正确的邮箱地址')
}
}
if (reqData.phone) {
if (!checkPhoneNum(reqData.phone)) {
throw new Error('请输入正确的手机号码')
}
}
if (!oneUser) {
let random = random_number(true, 6, 6)
await models.verify_code.create({
email: reqData.email,
verify_code: random,
type: 'register'
})
await sendVerifyCodeMail(reqData.email, '注册验证码', random)
resClientJson(res, {
state: 'success',
message: '验证码已发送到邮箱'
})
} else {
resClientJson(res, {
state: 'error',
message: '邮箱已存在'
})
}
} else if (reqData.phone) {
/* 手机号码注册 */
resClientJson(res, {
state: 'error',
message: '暂时未开放手机号码注册'
})
} else {
/* 非手机号码非邮箱 */
resClientJson(res, {
state: 'error',
message: '请输入正确的手机号码或者邮箱'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 用户注册post
* @param {object} ctx 上下文对象
*/
static async userSignUp(req: any, res: any, next: any) {
// post 数据
let reqData = req.body
let date = new Date()
try {
const { on_register } = lowdb
.read()
.get('config')
.value()
if (on_register === 'no') {
throw new Error('注册功能关闭,请联系管理员开启')
}
if (!reqData.nickname) {
throw new Error('昵称不存在')
}
if (reqData.nickname.length > 20) {
throw new Error('昵称过长')
}
let testNickname = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
if (!testNickname.test(reqData.nickname)) {
throw new Error('用户名只能中文、字母和数字,不能包含特殊字符')
}
if (reqData.email) {
if (!checkEmail(reqData.email)) {
throw new Error('请输入正确的邮箱地址')
}
}
if (reqData.phone) {
if (!checkPhoneNum(reqData.phone)) {
throw new Error('请输入正确的手机号码')
}
}
if (!reqData.password) {
throw new Error('密码不存在')
}
if (!checkPwd(reqData.password)) {
throw new Error(
'密码格式输入有误,请输入字母与数字的组合,长度为最小为6个字符!'
)
}
if (reqData.password !== reqData.double_password) {
throw new Error('两次输入密码不一致')
}
if (!reqData.code) {
throw new Error('验证码不存在')
}
if (reqData.email) {
/* 邮箱注册 */
let oneUserNickname = await models.user.findOne({
where: {
nickname: reqData.nickname
}
})
if (oneUserNickname) {
resClientJson(res, {
state: 'error',
message: '用户昵称已存在,请重新输入'
})
return false
}
let oneUserEmail = await models.user.findOne({
where: {
email: reqData.email
}
})
if (!oneUserEmail) {
await models.verify_code
.findOne({
where: {
email: reqData.email
},
limit: 1,
order: [['id', 'DESC']]
})
.then((data: { verify_code: any; create_timestamp: any }) => {
/* 注册验证码验证 */
if (data) {
let time_num = moment(date.setHours(date.getHours())).format(
'X'
)
if (reqData.code === data.verify_code) {
if (
Number(time_num) - Number(data.create_timestamp) >
30 * 60
) {
throw new Error('验证码已过时,请再次发送')
}
} else {
throw new Error('验证码错误')
}
} else {
throw new Error('请发送验证码')
}
})
let ip: any = ''
if (req.headers['x-forwarded-for']) {
ip = req.headers['x-forwarded-for'].toString().split(',')[0]
} else {
ip = req.connection.remoteAddress
}
await models.sequelize.transaction((t: any) => {
// 在事务中执行操作
return models.user
.create(
{
/* 注册写入数据库操作 */
avatar: config.default_avatar,
nickname: xss(reqData.nickname),
password: tools.encrypt(reqData.password, config.ENCRYPT_KEY),
email: reqData.email,
user_role_ids: config.USER_ROLE.dfId,
sex: 0,
reg_ip: ip,
enable: true
},
{ transaction: t }
)
.then((user: any) => {
return models.user_info.create(
{
/* 注册写入数据库操作 */
uid: user.uid,
avatar_review_status: 2,
shell_balance:
virtualInfo[modelAction.registered][modelName.system]
},
{ transaction: t }
)
})
.then((user_info: any) => {
return models.virtual.create({
// 用户虚拟币消息记录
plus_less: virtualInfo[modelAction.registered].plusLess,
balance:
virtualInfo[modelAction.registered][modelName.system],
amount: virtualInfo[modelAction.registered][modelName.system],
income: virtualInfo[modelAction.registered][modelName.system],
expenses: 0,
uid: user_info.uid,
type: modelName.system,
action: modelAction.registered
})
})
})
resClientJson(res, {
state: 'success',
message: '注册成功,跳往登录页'
})
} else {
throw new Error('邮箱已存在')
}
} else if (reqData.phone) {
/* 手机号码注册 */
throw new Error('暂时未开放手机号码注册')
} else {
/* 非手机号码非邮箱 */
throw new Error('请输入正确的手机号码或者邮箱')
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 获取个人信息get 并且知道用户是否登录,不需要任何参数
*/
static async userPersonalInfo(req: any, res: any, next: any) {
let { islogin = '', user = '' } = req
try {
if (!islogin) {
await resClientJson(res, {
state: 'success',
message: '获取成功',
data: {
islogin: false,
user: {}
}
})
}
let oneUser = await models.user.findOne({
where: { uid: user.uid },
attributes: [
'uid',
'avatar',
'nickname',
'sex',
'introduction',
'user_role_ids'
]
})
let oneUserInfo = await models.user_info.findOne({
where: { uid: user.uid }
})
let bindType = []
let oneUserAuth = await models.user_auth.findAll({
where: { uid: user.uid }
})
for (let i in oneUserAuth) {
bindType.push(oneUserAuth[i].identity_type)
}
await resClientJson(res, {
state: 'success',
message: '获取成功',
data: {
islogin,
user: oneUser,
user_info: oneUserInfo,
bindType
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 获取用户信息get 不需要登录
* @param {object} ctx 上下文对象
*/
static async getUserInfo(req: any, res: any, next: any) {
let uid = req.query.uid
try {
if (!uid) {
throw new Error('uid为空')
}
let oneUser = await models.user.findOne({
// 获取用户信息
where: { uid },
attributes: [
'uid',
'avatar',
'nickname',
'sex',
'introduction',
'user_role_ids'
]
})
let oneUserInfo = await models.user_info.findOne({
// 获取用户信息
where: { uid }
})
oneUser.setDataValue(
// 我关注了哪些用户的信息
'attentionUserIds',
await models.attention.findAll({
where: { uid: oneUser.uid, is_associate: true, type: modelName.user }
})
)
oneUser.setDataValue(
// 哪些用户关注了我
'userAttentionIds',
await models.attention.findAll({
where: {
associate_id: oneUser.uid,
is_associate: true,
type: modelName.user
}
})
)
let userAttentionCount = await models.attention.count({
// 关注了多少人
where: {
uid,
is_associate: true,
type: modelName.user
}
})
let allLikeDynaicId = await models.thumb
.findAll({
where: { uid, type: modelName.dynamic, is_associate: true }
})
.then((res: any) => {
return res.map((item: any, key: any) => {
return item.associate_id
})
})
let allRssDynamicTopicId = await models.attention
.findAll({
where: { uid, type: modelName.dynamic_topic, is_associate: true }
})
.then((res: any) => {
return res.map((item: any, key: any) => {
return item.associate_id
})
})
let otherUserAttentionCount = await models.attention.count({
// 多少人关注了
where: {
associate_id: uid,
is_associate: true,
type: modelName.user
}
})
let articleCount = await models.article.count({
// 他有多少文章
where: {
uid,
...clientWhere.article.me
}
})
let dynamicCount = await models.dynamic.count({
// 他有多少文章
where: {
uid,
...clientWhere.dynamic.myQuery
}
})
resClientJson(res, {
state: 'success',
message: '获取用户所有信息成功',
data: {
user: oneUser,
user_info: oneUserInfo,
otherUserAttentionCount: otherUserAttentionCount,
userAttentionCount: userAttentionCount,
userArticleCount: articleCount,
dynamicCount,
allLikeDynaicId,
allRssDynamicTopicId
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 修改用户信息post
* @param {object} ctx 上下文对象
*/
static async updateUserInfo(req: any, res: any, next: any) {
let reqData = req.body
let { user = '' } = req
let oneUser = await models.user.findOne({
where: {
nickname: reqData.nickname,
uid: {
[Op.ne]: user.uid
}
}
})
try {
if (reqData.nickname && reqData.nickname.length > 20) {
throw new Error('昵称过长')
}
let testNickname = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
if (!testNickname.test(reqData.nickname)) {
throw new Error('用户名只能中文、字母和数字,不能包含特殊字符')
}
if (oneUser) {
throw new Error('用户昵称已存在,请重新输入')
}
if (reqData.introduction && reqData.introduction.length > 50) {
throw new Error('个人介绍过长')
}
if (reqData.profession && reqData.profession.length > 20) {
throw new Error('职位名输入过长')
}
if (reqData.company && reqData.company.length > 20) {
throw new Error('公司名字输入过长')
}
if (reqData.home_page && !checkUrl(reqData.home_page)) {
throw new Error('请输入正确的个人网址')
}
const NowDate = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
await models.user.update(
{
sex: reqData.sex || 0,
nickname: reqData.nickname || '',
introduction: reqData.introduction || '',
update_date: new Date(NowDate),
update_date_timestamp: moment(
new Date().setHours(new Date().getHours())
).format('X')
},
{
where: {
uid: user.uid // 查询条件
}
}
)
await models.user_info.update(
{
profession: reqData.profession || '',
company: reqData.company || '',
home_page: reqData.home_page || '',
is_msg_push: reqData.is_msg_push
},
{
where: {
uid: user.uid // 查询条件
}
}
)
resClientJson(res, {
state: 'success',
message: '修改用户信息成功'
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 修改用户密码
* @param {object} ctx 上下文对象
*/
static async updateUserPassword(req: any, res: any, next: any) {
let reqData = req.body
let { user = '' } = req
try {
let oneUser = await models.user.findOne({
where: {
uid: user.uid
}
})
if (
tools.encrypt(reqData.old_password, config.ENCRYPT_KEY) ===
oneUser.password
) {
if (!reqData.old_password) {
throw new Error('请输入旧密码')
}
if (!reqData.new_password) {
throw new Error('请输入新密码')
}
if (!checkPwd(reqData.new_password)) {
throw new Error('密码格式输入有误!')
}
if (!reqData.repeat_new_password) {
throw new Error('请重复输入新密码')
}
if (reqData.repeat_new_password !== reqData.new_password) {
throw new Error('两次输入密码不相同')
}
await models.user.update(
{
password: tools.encrypt(reqData.new_password, config.ENCRYPT_KEY)
},
{
where: {
uid: user.uid // 查询条件
}
}
)
resClientJson(res, {
state: 'success',
message: '修改用户密码成功'
})
} else {
resClientJson(res, {
state: 'error',
message: '旧密码错误,请重新输入'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 获取用户消息
* @param {object} ctx 上下文对象
*/
static async getUserMessageList(req: any, res: any, next: any) {
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let { user = '' } = req
try {
let allUserMessage = await models.user_message.findAll({
// 获取所有未读消息id
where: {
is_read: false,
uid: user.uid
}
})
let { count, rows } = await models.user_message.findAndCountAll({
where: {
uid: user.uid
}, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: [['create_timestamp', 'desc']]
})
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await moment(rows[i].create_date).format('YYYY-MM-DD')
)
rows[i].setDataValue(
'sender',
await models.user.findOne({
where: { uid: rows[i].sender_id },
attributes: ['uid', 'avatar', 'nickname']
}) || {}
)
rows[i].setDataValue(
'actionText',
userMessageActionText[rows[i].action]
)
if (
rows[i].content &&
rows[i].type !== modelName.user &&
~modelNameNum.indexOf(rows[i].type)
) {
// 排除关注用户
rows[i].setDataValue(
modelInfo[rows[i].type].model,
await models[modelInfo[rows[i].type].model].findOne({
where: { [modelInfo[rows[i].type].idKey]: rows[i].content }
}) || {}
)
}
}
if (allUserMessage.length > 0) {
// 修改未读为已读
await models.user_message.update(
{
is_read: true
},
{
where: {
is_read: false,
uid: user.uid
}
}
)
}
await resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
count,
list: rows,
page,
pageSize
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 删除用户消息
* @param {object} ctx 上下文对象
*/
static async deleteUserMessage(req: any, res: any, next: any) {
let reqData = req.query
let { user = '' } = req
try {
let oneUserMessage = await models.user_message.findOne({
where: {
id: reqData.user_message_id,
uid: user.uid
}
})
if (oneUserMessage) {
await models.user_message.destroy({
where: {
id: reqData.user_message_id,
uid: user.uid
}
})
} else {
throw new Error('非法操作')
}
resClientJson(res, {
state: 'success',
message: '删除用户消息成功'
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 重置密码code发送
* @param {object} ctx 上下文对象
*/
static async sendResetPasswordCode(req: any, res: any, next: any) {
let reqData = req.body
try {
if (reqData.type === 'email') {
/* 邮箱注册验证码 */
if (!reqData.email) {
throw new Error('邮箱不存在')
}
if (!checkEmail(reqData.email)) {
throw new Error('邮箱格式输入有误')
}
let email = await models.user.findOne({
where: {
email: reqData.email
}
})
if (email) {
let random = random_number(true, 6, 6)
await models.verify_code.create({
email: reqData.email,
verify_code: random,
type: 'reset_password'
})
sendVerifyCodeMail(reqData.email, '重置密码验证码', random)
resClientJson(res, {
state: 'success',
message: '验证码已发送到邮箱'
})
} else {
resClientJson(res, {
state: 'error',
message: '邮箱不存在'
})
}
} else if (reqData.type === 'phone') {
/* 手机号码 */
resClientJson(res, {
state: 'error',
message: '暂时未开放手机号码修改密码'
})
} else {
/* 非手机号码非邮箱 */
resClientJson(res, {
state: 'error',
message: '请输入正确的手机号码或者邮箱'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 重置密码
* @param {object} ctx 上下文对象
*/
static async userResetPassword(req: any, res: any, next: any) {
let reqData = req.body
let date = new Date()
try {
if (!reqData.email) {
throw new Error('邮箱不存在')
}
if (!checkEmail(reqData.email)) {
throw new Error('邮箱格式输入有误')
}
if (!reqData.code) {
throw new Error('验证码不存在')
}
if (!reqData.new_password) {
throw new Error('密码不存在')
}
if (!checkPwd(reqData.new_password)) {
throw new Error('密码格式输入有误!')
}
if (reqData.new_password !== reqData.repeat_new_password) {
throw new Error('两次输入密码不一致')
}
if (reqData.type === 'email') {
/* 邮箱注册 */
let email = await models.user.findOne({
where: {
email: reqData.email
}
})
if (email) {
await models.verify_code
.findOne({
where: {
email: reqData.email
},
limit: 1,
order: [['id', 'DESC']]
})
.then((data: { verify_code: any; create_timestamp: any }) => {
/* 注册验证码验证 */
if (data) {
let time_num = moment(date.setHours(date.getHours())).format(
'X'
)
if (reqData.code === data.verify_code) {
if (
Number(time_num) - Number(data.create_timestamp) >
30 * 60
) {
throw new Error('验证码已过时,请再次发送')
}
} else {
throw new Error('验证码错误')
}
} else {
throw new Error('请发送验证码')
}
})
await models.user.update(
{
password: tools.encrypt(reqData.new_password, config.ENCRYPT_KEY)
},
{
where: {
email: reqData.email // 查询条件
}
}
)
resClientJson(res, {
state: 'success',
message: '修改用户密码成功'
})
} else {
resClientJson(res, {
state: 'error',
message: '邮箱不存在'
})
}
} else if (reqData.type === 'phone') {
// 手机号码重置密码
resClientJson(res, {
state: 'error',
message: '暂时未开放手机号码重置密码'
})
} else {
/* 非手机号码非邮箱 */
resClientJson(res, {
state: 'error',
message: '请输入正确的手机号码或者邮箱'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 获取所有用户角色标签
* @param {object} ctx 上下文对象
*/
static async getUserRoleAll(req: any, res: any, next: any) {
// get 页面
try {
let allUserRole = await models.user_role.findAll({
where: {
enable: true,
is_show: true
}
})
resClientJson(res, {
state: 'success',
message: '获取成功',
data: {
user_role_all: allUserRole
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 获取当前登录用户关联的一些信息
* @param {object} ctx 上下文对象
*/
static async getUserAssociateinfo(req: any, res: any, next: any) {
// get 页面
try {
let articleThumdId: any[] = [] // 文章点赞id
let articleCollectId: any[] = [] // 文章收藏id
let dynamicThumdId: any[] = [] // 动态点赞id
let userAttentionId: any[] = [] // 用户关注id
let { user = '', islogin } = req
if (!islogin) {
resClientJson(res, {
state: 'success',
message: '获取成功',
data: {
articleThumdId,
dynamicThumdId
}
})
return false
}
let allThumb = await models.thumb.findAll({
where: {
uid: user.uid,
is_associate: true
}
})
let allAttention = await models.attention.findAll({
where: {
uid: user.uid,
is_associate: true
}
})
let allCollect = await models.collect.findAll({
where: {
uid: user.uid,
is_associate: true
}
})
for (let i in allThumb) {
if (allThumb[i].type === modelName.article) {
articleThumdId.push(allThumb[i].associate_id)
} else if (allThumb[i].type === modelName.dynamic) {
dynamicThumdId.push(allThumb[i].associate_id)
}
}
for (let i in allAttention) {
if (allAttention[i].type === modelName.user) {
userAttentionId.push(allAttention[i].associate_id)
}
}
for (let i in allCollect) {
if (allCollect[i].type === modelName.article) {
articleCollectId.push(allCollect[i].associate_id)
}
}
resClientJson(res, {
state: 'success',
message: '获取成功',
data: {
articleThumdId,
articleCollectId,
dynamicThumdId,
userAttentionId,
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
}
export default User | the_stack |
import {
DinoContainer,
IDinoContainerConfig,
DIContainer,
RouteTable,
ObjectUtility,
DinoUtility,
Attribute,
Reflector,
DataUtility,
IControllerAttributeExtended,
DinoRouter,
IControllerAttributeProvider,
RouteAttribute,
IActionMethodAttribute
} from '../../index';
describe('modules.core.dino.container.two.spec', () => {
it('populateControllerMiddlewares.metadata_undefined', () => {
let config: IDinoContainerConfig = {} as any;
spyOn(ObjectUtility, 'getPrototypeOf').and.callFake(() => undefined);
spyOn(Reflector, 'getMetadata').and.callFake(() => undefined);
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => true);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.populateControllerMiddlewares({} as any);
expect(obj.use).toEqual([]);
expect(obj.middlewares).toEqual([]);
expect(obj.beforeActionFilters).toEqual([]);
expect(obj.afterActionFilters).toEqual([]);
expect(obj.result).toEqual([]);
expect(obj.exceptions).toEqual([]);
expect(obj.prefix).toBe('');
});
it('populateControllerMiddlewares.metadata_defined_without_inheritance_prefix_""', () => {
let inheritanceOrder = 1;
let config: IDinoContainerConfig = {} as any;
let meta: IControllerAttributeExtended = {
use: [Function, String],
middlewares: [Object, Array],
filters: [Number, Boolean],
result: [String, Number],
exceptions: [Boolean, Object],
prefix: ''
};
spyOn(ObjectUtility, 'getPrototypeOf').and.callFake(() => undefined);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(Reflector, 'getMetadata').and.callFake(() => meta);
spyOn(Reflector, 'getOwnMetadata').and.callFake(() => undefined);
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => {
if (inheritanceOrder > 1) return true;
inheritanceOrder++;
return false;
});
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer.populateControllerMiddlewares({} as any);
expect(obj.prefix).toBe('');
// order matters so we have to test for indices
expect(obj.use[0]).toBe(Function);
expect(obj.use[1]).toBe(String);
expect(obj.middlewares[0]).toBe(Object);
expect(obj.middlewares[1]).toBe(Array);
expect(obj.beforeActionFilters[0]).toBe(Number);
expect(obj.beforeActionFilters[1]).toBe(Boolean);
expect(obj.afterActionFilters[0]).toBe(Number);
expect(obj.afterActionFilters[1]).toBe(Boolean);
expect(obj.result[0]).toBe(String);
expect(obj.result[1]).toBe(Number);
expect(obj.exceptions[0]).toBe(Boolean);
expect(obj.exceptions[1]).toBe(Object);
});
it('populateControllerMiddlewares.metadata_defined_without_inheritance_prefix_test', () => {
let inheritanceOrder = 0;
let config: IDinoContainerConfig = {} as any;
let meta: IControllerAttributeExtended = {
use: [Function, String],
middlewares: [Object, Array],
filters: [Number, Boolean],
result: [String, Number],
exceptions: [Boolean, Object],
prefix: 'test'
};
spyOn(ObjectUtility, 'getPrototypeOf').and.callFake(() => undefined);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(Reflector, 'getMetadata').and.callFake(() => meta);
spyOn(Reflector, 'getOwnMetadata').and.callFake(() => meta);
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => {
if (inheritanceOrder > 0) return true;
inheritanceOrder++;
return false;
});
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.populateControllerMiddlewares({} as any);
expect(obj.prefix).toBe('test');
// order matters so we have to test for indices
expect(obj.use[0]).toBe(Function);
expect(obj.use[1]).toBe(String);
expect(obj.middlewares[0]).toBe(Object);
expect(obj.middlewares[1]).toBe(Array);
expect(obj.beforeActionFilters[0]).toBe(Number);
expect(obj.beforeActionFilters[1]).toBe(Boolean);
expect(obj.afterActionFilters[0]).toBe(Number);
expect(obj.afterActionFilters[1]).toBe(Boolean);
expect(obj.result[0]).toBe(String);
expect(obj.result[1]).toBe(Number);
expect(obj.exceptions[0]).toBe(Boolean);
expect(obj.exceptions[1]).toBe(Object);
});
it('populateControllerMiddlewares.metadata_defined_with_inheritance_level_one', () => {
let inheritanceOrder = 0;
let config: IDinoContainerConfig = {} as any;
let child: IControllerAttributeExtended = {
use: [Function, String],
middlewares: [Object, Array],
filters: [Number, Boolean],
result: [String, Number],
exceptions: [Boolean, Object],
prefix: '/test'
};
let base: IControllerAttributeExtended = {
use: [Object, Number],
middlewares: [Function, Boolean],
filters: [Array, String],
result: [Object, Array],
exceptions: [Number, Function],
prefix: '/tester/meta'
};
spyOn(ObjectUtility, 'getPrototypeOf').and.callFake(() => undefined);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(Reflector, 'getMetadata').and.callFake(() => child);
spyOn(Reflector, 'getOwnMetadata').and.callFake(() => base);
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => {
if (inheritanceOrder > 1) return true;
inheritanceOrder++;
return false;
});
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer.populateControllerMiddlewares({} as any);
expect(obj.prefix).toBe(`${base.prefix}${child.prefix}`);
// order matters so we have to test for indices
// for .use, base => child
expect(obj.use[0]).toBe(Object);
expect(obj.use[1]).toBe(Number);
expect(obj.use[2]).toBe(Function);
expect(obj.use[3]).toBe(String);
// for middlwares, base => child
expect(obj.middlewares[0]).toBe(Function);
expect(obj.middlewares[1]).toBe(Boolean);
expect(obj.middlewares[2]).toBe(Object);
expect(obj.middlewares[3]).toBe(Array);
// for beforeFilters, base => child
expect(obj.beforeActionFilters[0]).toBe(Array);
expect(obj.beforeActionFilters[1]).toBe(String);
expect(obj.beforeActionFilters[2]).toBe(Number);
expect(obj.beforeActionFilters[3]).toBe(Boolean);
// for afterFilters, child => base
expect(obj.afterActionFilters[0]).toBe(Number);
expect(obj.afterActionFilters[1]).toBe(Boolean);
expect(obj.afterActionFilters[2]).toBe(Array);
expect(obj.afterActionFilters[3]).toBe(String);
// for resultFilters, child => base
expect(obj.result[0]).toBe(String);
expect(obj.result[1]).toBe(Number);
expect(obj.result[2]).toBe(Object);
expect(obj.result[3]).toBe(Array);
// for exceptions, child => base
expect(obj.exceptions[0]).toBe(Boolean);
expect(obj.exceptions[1]).toBe(Object);
expect(obj.exceptions[2]).toBe(Number);
expect(obj.exceptions[3]).toBe(Function);
});
it('populateControllerMiddlewares.metadata_defined_with_inheritance_level_two', () => {
let inheritanceOrder = 0;
let config: IDinoContainerConfig = {} as any;
let child: IControllerAttributeExtended = {
use: [Function, String],
middlewares: [Array],
filters: [Number, Boolean],
result: [String, Number],
exceptions: [Boolean],
prefix: '/test'
};
let base: IControllerAttributeExtended = {
use: [Object, Number],
middlewares: [Function, Boolean],
filters: [Array],
result: [Object, Array],
exceptions: [Number, Function],
prefix: '/tester/meta'
};
let superbase: IControllerAttributeExtended = {
use: [Boolean, Array],
middlewares: [Number, String],
filters: [Function, Object],
result: [Function],
exceptions: [Array, String],
prefix: ''
};
spyOn(ObjectUtility, 'getPrototypeOf').and.callFake(() => undefined);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(Reflector, 'getMetadata').and.callFake(() => child);
spyOn(Reflector, 'getOwnMetadata').and.callFake(() => {
if (inheritanceOrder === 1) return base;
if (inheritanceOrder === 2) return superbase;
});
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => {
if (inheritanceOrder > 2) return true;
inheritanceOrder++;
return false;
});
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.populateControllerMiddlewares({} as any);
expect(obj.prefix).toBe(`${superbase.prefix}${base.prefix}${child.prefix}`);
// order matters so we have to test for indices
// for .use, superbase => base => child
expect(obj.use[0]).toBe(Boolean);
expect(obj.use[1]).toBe(Array);
expect(obj.use[2]).toBe(Object);
expect(obj.use[3]).toBe(Number);
expect(obj.use[4]).toBe(Function);
expect(obj.use[5]).toBe(String);
// for middlwares, superbase => base => child
expect(obj.middlewares[0]).toBe(Number);
expect(obj.middlewares[1]).toBe(String);
expect(obj.middlewares[2]).toBe(Function);
expect(obj.middlewares[3]).toBe(Boolean);
expect(obj.middlewares[4]).toBe(Array);
// for beforeFilters, superbase => base => child
expect(obj.beforeActionFilters[0]).toBe(Function);
expect(obj.beforeActionFilters[1]).toBe(Object);
expect(obj.beforeActionFilters[2]).toBe(Array);
expect(obj.beforeActionFilters[3]).toBe(Number);
expect(obj.beforeActionFilters[4]).toBe(Boolean);
// for afterFilters, child => base => superbase
expect(obj.afterActionFilters[0]).toBe(Number);
expect(obj.afterActionFilters[1]).toBe(Boolean);
expect(obj.afterActionFilters[2]).toBe(Array);
expect(obj.afterActionFilters[3]).toBe(Function);
expect(obj.afterActionFilters[4]).toBe(Object);
// for resultFilters, child => base => superbase
expect(obj.result[0]).toBe(String);
expect(obj.result[1]).toBe(Number);
expect(obj.result[2]).toBe(Object);
expect(obj.result[3]).toBe(Array);
expect(obj.result[4]).toBe(Function);
// for exceptions, child => base => superbase
expect(obj.exceptions[0]).toBe(Boolean);
expect(obj.exceptions[1]).toBe(Number);
expect(obj.exceptions[2]).toBe(Function);
expect(obj.exceptions[3]).toBe(Array);
expect(obj.exceptions[4]).toBe(String);
});
it('registerController.when_not_Apicontroller', () => {
let config: IDinoContainerConfig = {} as any;
spyOn(DinoUtility, 'isApiController').and.callFake(() => false);
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.registerController({} as any);
expect(DinoUtility.isApiController).toHaveBeenCalledTimes(1);
});
it('registerController.when_Apicontroller_but_metadata_undefined', () => {
let config: IDinoContainerConfig = {} as any;
spyOn(DinoUtility, 'isApiController').and.callFake(() => true);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(ObjectUtility, 'create').and.callFake(() => undefined);
spyOn(Reflector, 'hasMetadata').and.callFake(() => false);
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.registerController({} as any);
expect(Reflector.hasMetadata).toHaveBeenCalledTimes(1);
});
it('registerController.when_Apicontroller_metadata_defined_and_no_actionMethods', () => {
// Following test case validates middlewares, filters etc which is repetitive
// and removed from other tests
// do not delete this test case easily.
let bindedRouterToApp = false;
let expressWares = [];
let mwares;
let beforeFilters;
let afterFilters;
let results;
let exwares;
let meta: IControllerAttributeProvider = {
use: [Function, String],
middlewares: [Array],
beforeActionFilters: [Number, Boolean],
afterActionFilters: [],
result: [String, Number],
exceptions: [Boolean],
prefix: '/test'
};
let config: IDinoContainerConfig = {
baseUri: '/api',
app: {
use: (uri, router) => {
expect(uri).toBe(`${config.baseUri}${meta.prefix}`);
bindedRouterToApp = true;
}
}
} as any;
let dinoRouter = {
expressRouter: () => {
return {
use: mware => expressWares.push(mware)
};
},
registerMiddlewares: mware => mwares = mware,
registerBeginActionFilters: mware => beforeFilters = mware,
registerAfterActionFilters: mware => afterFilters = mware,
registerResultFilters: mware => results = mware,
registerExceptionFilters: (app, uri, mware) => {
expect(uri).toBe(`${config.baseUri}${meta.prefix}`);
expect(app).toBe(config.app);
exwares = mware;
}
};
spyOn(DinoUtility, 'isApiController').and.callFake(() => true);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
spyOn(ObjectUtility, 'create').and.callFake(() => { });
spyOn(Reflector, 'hasMetadata').and.callFake(() => true);
spyOn(DinoRouter, 'create').and.callFake(() => dinoRouter);
spyOn(DinoUtility, 'getControllerProperties').and.callFake(() => []);
let dinoContainer = new DinoContainer(config);
spyOn(dinoContainer, 'populateControllerMiddlewares').and.callFake(() => meta);
let obj = dinoContainer.registerController({} as any);
expect(expressWares[0]).toBe(Function);
expect(expressWares[1]).toBe(String);
expect(mwares).toBe(meta.middlewares);
expect(beforeFilters).toBe(meta.beforeActionFilters);
expect(afterFilters).toBe(meta.afterActionFilters);
expect(results).toBe(meta.result);
expect(exwares).toBe(meta.exceptions);
expect(bindedRouterToApp).toBeTruthy();
});
it('registerController.when_Apicontroller_metadata_defined_and_actionMethod_is_sync', () => {
let controllerType = Object;
let meta: IControllerAttributeProvider = { prefix: '/test', use: [] };
let routeAttr;
let callback;
let router: any = { use: mware => undefined };
let patch;
let invoked;
let actionMeta: IActionMethodAttribute = {
isAsync: false,
httpVerb: 'get',
route: 'test',
sendsResponse: false
};
let fakeRouteTable = RouteTable.create();
router[actionMeta.httpVerb] = (route, cb) => {
expect(route).toBe(actionMeta.route);
callback = cb;
};
let dinoRouter = {
expressRouter: () => router,
registerMiddlewares: mware => undefined,
registerBeginActionFilters: mware => undefined,
registerAfterActionFilters: mware => undefined,
registerResultFilters: mware => undefined,
registerExceptionFilters: (app, uri, mware) => undefined
};
let config: IDinoContainerConfig = {
app: { use: (uri, router) => undefined }
} as any;
spyOn(DinoUtility, 'isApiController').and.callFake(() => true);
spyOn(ObjectUtility, 'keys').and.callFake(o => {
routeAttr = o;
return ['post'];
});
spyOn(ObjectUtility, 'create').and.callFake(() => {
// set some fake properties to loop through
return { get: () => undefined };
});
spyOn(Reflector, 'hasMetadata').and.callFake(() => true);
spyOn(DinoRouter, 'create').and.callFake(() => dinoRouter);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => fakeRouteTable);
spyOn(DinoUtility, 'getControllerProperties').and.callFake(() => ['test']);
let dinoContainer = new DinoContainer(config);
spyOn(dinoContainer, 'populateControllerMiddlewares').and.callFake(() => meta);
spyOn(dinoContainer, 'getActionMethodMetadata').and.callFake(() => actionMeta);
spyOn(dinoContainer, 'setUpDinoController')
.and.callFake((type, action: IActionMethodAttribute, res) => {
expect(type).toBe(controllerType);
expect(action.sendsResponse).toBe(actionMeta.sendsResponse);
expect(res).toEqual({ dino: true });
return {
patch: (req, res, next) => {
expect(req).toEqual({ req: true });
expect(res).toEqual({ dino: true });
expect(next()).toBe('invoke');
patch = true;
},
invoke: action => invoked = true
};
});
let obj = dinoContainer.registerController(controllerType);
expect(routeAttr).toBe(RouteAttribute);
callback({ req: true }, { dino: true }, () => 'invoke');
expect(patch).toBeTruthy();
expect(invoked).toBeTruthy();
expect(fakeRouteTable.getRoutes().length).toBe(1);
});
it('registerController.verify_register_middlewares_filters_etc_for_Apicontroller', () => {
let invokeOrder = 0;
let methodOrder: any = {};
let controllerType = Object;
let meta: IControllerAttributeProvider = { prefix: '/test', use: [Function] };
let router: any = { use: m => methodOrder.routerUse = ++invokeOrder };
let actionMeta: IActionMethodAttribute = {
isAsync: false,
httpVerb: 'get'
} as any;
let callback;
let fakeRouteTable = RouteTable.create();
router[actionMeta.httpVerb] = (route, cb) => {
methodOrder.routerAction = ++invokeOrder;
callback = cb;
};
let dinoRouter = {
expressRouter: () => router,
registerMiddlewares: m => methodOrder.middlewares = ++invokeOrder,
registerBeginActionFilters: m => methodOrder.beginFilters = ++invokeOrder,
registerAfterActionFilters: m => methodOrder.afterFilters = ++invokeOrder,
registerResultFilters: m => methodOrder.resultFilters = ++invokeOrder,
registerExceptionFilters: (app, uri, mware) => methodOrder.exceptionFilters = ++invokeOrder
};
let config: IDinoContainerConfig = {
app: { use: (uri, router) => methodOrder.appUse = ++invokeOrder }
} as any;
spyOn(DinoUtility, 'isApiController').and.callFake(() => true);
spyOn(Reflector, 'hasMetadata').and.callFake(() => true);
spyOn(ObjectUtility, 'keys').and.callFake(() => ['post']);
spyOn(ObjectUtility, 'create').and.callFake(() => {
// set some fake properties to loop through
return { get: () => undefined };
});
spyOn(DinoRouter, 'create').and.callFake(() => dinoRouter);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => fakeRouteTable);
spyOn(DinoUtility, 'getControllerProperties').and.callFake(() => ['test']);
let dinoContainer = new DinoContainer(config);
spyOn(dinoContainer, 'populateControllerMiddlewares').and.callFake(() => meta);
spyOn(dinoContainer, 'getActionMethodMetadata').and.callFake(() => actionMeta);
spyOn(dinoContainer, 'setUpDinoController')
.and.callFake((type, sendsResponse, bindsModel, res) => {
return {
patch: (req, res, next) => undefined,
invoke: (action, verb, route) => undefined
};
});
let obj = dinoContainer.registerController(controllerType);
callback({ req: true }, { dino: true }, () => 'invoke');
expect(methodOrder.routerUse).toBe(1);
expect(methodOrder.middlewares).toBe(2);
expect(methodOrder.beginFilters).toBe(3);
expect(methodOrder.routerAction).toBe(4);
expect(methodOrder.afterFilters).toBe(5);
expect(methodOrder.resultFilters).toBe(6);
expect(methodOrder.appUse).toBe(7);
expect(methodOrder.exceptionFilters).toBe(8);
});
it('registerController.when_Apicontroller_metadata_defined_and_actionMethod_is_Async', async () => {
let controllerType = Object;
let meta: IControllerAttributeProvider = { prefix: '/test', use: [] };
let routeAttr;
let callback;
let router: any = { use: mware => undefined };
let patch;
let invoked;
let actionMeta: IActionMethodAttribute = {
isAsync: true,
httpVerb: 'get',
route: 'test',
sendsResponse: false
};
let fakeRouteTable = RouteTable.create();
router[actionMeta.httpVerb] = (route, cb) => {
expect(route).toBe(actionMeta.route);
callback = cb;
};
let dinoRouter = {
expressRouter: () => router,
registerMiddlewares: mware => undefined,
registerBeginActionFilters: mware => undefined,
registerAfterActionFilters: mware => undefined,
registerResultFilters: mware => undefined,
registerExceptionFilters: (app, uri, mware) => undefined
};
let config: IDinoContainerConfig = {
app: { use: (uri, router) => undefined }
} as any;
spyOn(DinoUtility, 'isApiController').and.callFake(() => true);
spyOn(ObjectUtility, 'keys').and.callFake(o => {
routeAttr = o;
return ['post'];
});
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => fakeRouteTable);
spyOn(ObjectUtility, 'create').and.callFake(() => {
return { get: () => undefined };
});
spyOn(Reflector, 'hasMetadata').and.callFake(() => true);
spyOn(DinoRouter, 'create').and.callFake(() => dinoRouter);
spyOn(DinoUtility, 'getControllerProperties').and.callFake(() => ['test']);
let dinoContainer = new DinoContainer(config);
spyOn(dinoContainer, 'populateControllerMiddlewares').and.callFake(() => meta);
spyOn(dinoContainer, 'getActionMethodMetadata').and.callFake(() => actionMeta);
spyOn(dinoContainer, 'setUpDinoController')
.and.callFake((type, action: IActionMethodAttribute, res) => {
expect(type).toBe(controllerType);
expect(action.sendsResponse).toBe(actionMeta.sendsResponse);
expect(res).toEqual({ dino: true });
return {
patch: (req, res, next) => {
expect(req).toEqual({ req: true });
expect(res).toEqual({ dino: true });
expect(next()).toBe('invoke');
patch = true;
},
invokeAsync: action => invoked = true
};
});
let obj = dinoContainer.registerController(controllerType);
expect(routeAttr).toBe(RouteAttribute);
await callback({ req: true }, { dino: true }, () => 'invoke');
expect(patch).toBeTruthy();
expect(invoked).toBeTruthy();
expect(fakeRouteTable.getRoutes().length).toBe(1);
});
it('getActionMethodMetadata.when_Attribute.parse_is_undefined', async () => {
let returns = { hello: 'world' };
let config: IDinoContainerConfig = { raiseModelError: true } as any;
spyOn(Reflector, 'getMetadata').and.callFake(ob => {
if (ob === Attribute.httpGet) return '/route';
if (ob === Attribute.returns) return returns;
});
spyOn(Reflector, 'hasMetadata').and.callFake(ob => {
if (ob === Attribute.asyncAttr) return true;
if (ob === Attribute.sendsResponse) return false;
});
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => true);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.getActionMethodMetadata(Attribute.httpGet, 'testAction', {} as any);
expect(obj.isAsync).toBeTruthy();
expect(obj.sendsResponse).toBeFalsy();
expect(obj.route).toBe('/route');
expect(obj.httpVerb).toBe(RouteAttribute.httpGet_ActionAttribute);
expect(obj.actionArguments).toEqual([]);
expect(obj.returns).toBe(returns);
});
it('getActionMethodMetadata.when_Attribute.parse_is_defined', async () => {
let config: IDinoContainerConfig = { raiseModelError: true } as any;
let testData = [{
key: 'body',
value: 'test'
}];
spyOn(Reflector, 'getMetadata').and.callFake(ob => {
if (ob === Attribute.httpGet) return '/route';
if (ob === Attribute.parse) return testData;
});
spyOn(Reflector, 'hasMetadata').and.callFake(ob => {
if (ob === Attribute.asyncAttr) return true;
if (ob === Attribute.sendsResponse) return false;
});
spyOn(DataUtility, 'isUndefinedOrNull').and.callFake(() => false);
spyOn(DIContainer, 'create').and.callFake(() => undefined);
spyOn(RouteTable, 'create').and.callFake(() => undefined);
let dinoContainer = new DinoContainer(config);
let obj = dinoContainer
.getActionMethodMetadata(Attribute.httpGet, 'testAction', {} as any);
expect(obj.isAsync).toBeTruthy();
expect(obj.sendsResponse).toBeFalsy();
expect(obj.route).toBe('/route');
expect(obj.httpVerb).toBe(RouteAttribute.httpGet_ActionAttribute);
expect(obj.actionArguments).toBe(testData);
expect(obj.returns).toBeUndefined();
});
}); | the_stack |
import * as fs from 'fs'
import * as path from 'path'
import * as yaml from 'js-yaml'
import { KubernetesManifest } from '../../../app/v2/core/integrations/interfaces/k8s-manifest.interface'
import { AppConstants } from '../../../app/v2/core/constants'
const basePath = path.join(__dirname, '../../../', 'resources/helm-test-chart')
export const simpleManifests: KubernetesManifest[] = yaml.safeLoadAll(fs.readFileSync(`${basePath}/simple-manifests.yaml`, 'utf-8'))
export const getSimpleManifests = (appName: string, namespace: string, image: string): KubernetesManifest[] => {
const manifests = yaml.safeLoadAll(fs.readFileSync(`${basePath}/simple-manifests.yaml`, 'utf-8'))
const service = manifests[0]
service.metadata.labels.app = appName
service.metadata.labels.service = appName
service.metadata.labels.component = appName
service.metadata.name = appName
service.metadata.namespace = namespace
service.spec.selector.app = appName
const deployment = manifests[1]
deployment.metadata.labels.app = appName
deployment.metadata.labels.version = appName
deployment.metadata.labels.component = appName
deployment.metadata.name = appName
deployment.metadata.namespace = namespace
deployment.spec.selector.matchLabels.app = appName
deployment.spec.selector.matchLabels.version = appName
deployment.spec.template.metadata.labels.app = appName
deployment.spec.template.metadata.labels.version = appName
deployment.spec.template.spec.containers[0].image = image
deployment.spec.template.spec.containers[0].name = appName
return [service, deployment]
}
export const getComplexManifests = (appName: string, namespace: string, image: string): KubernetesManifest[] => {
const manifests = yaml.safeLoadAll(fs.readFileSync(`${basePath}/complex-manifests.yaml`, 'utf-8'))
const service = manifests[0]
service.metadata.labels.app = appName
service.metadata.labels.service = appName
service.metadata.labels.component = appName
service.metadata.name = appName
service.metadata.namespace = namespace
service.spec.selector.app = appName
const deployment = manifests[1]
deployment.metadata.labels.app = appName
deployment.metadata.labels.version = appName
deployment.metadata.labels.component = appName
deployment.metadata.name = appName
deployment.metadata.namespace = namespace
deployment.spec.selector.matchLabels.app = appName
deployment.spec.selector.matchLabels.version = appName
deployment.spec.template.metadata.labels.app = appName
deployment.spec.template.metadata.labels.version = appName
deployment.spec.template.spec.containers[0].image = image
deployment.spec.template.spec.containers[0].name = appName
const secret = manifests[2]
secret.metadata.labels.app = appName
secret.metadata.labels.version = appName
secret.metadata.labels.component = appName
secret.metadata.namespace = namespace
return [service, deployment, secret]
}
export const getNoLabelsManifests = (appName: string, image: string): KubernetesManifest[] => {
const manifests = yaml.safeLoadAll(fs.readFileSync(`${basePath}/no-labels-manifests.yaml`, 'utf-8'))
const service = manifests[0]
service.metadata.name = appName
service.spec.selector.app = appName
const deployment = manifests[1]
deployment.metadata.name = appName
deployment.spec.selector.matchLabels.app = appName
deployment.spec.template.spec.containers[0].image = image
deployment.spec.template.spec.containers[0].name = appName
const statefulSet = manifests[2]
statefulSet.metadata.name = appName
statefulSet.spec.selector.matchLabels.app = appName
statefulSet.spec.template.spec.containers[0].image = image
statefulSet.spec.template.spec.containers[0].name = appName
return [service, deployment, statefulSet]
}
export const routesManifestsSameNamespace: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v1',
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-1',
},
{
labels: {
component: 'A',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
route: [
{
destination: {
host: 'A',
subset: 'circle-1'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-1'
}
},
response: {
set: {
'x-circle-source': 'circle-1'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
]
export const routesManifests2ComponentsOneCircle: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
]
export const routesManifestsSameNamespaceWithService: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v1',
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-1',
},
{
labels: {
component: 'A',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
route: [
{
destination: {
host: 'A',
subset: 'circle-1'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-1'
}
},
response: {
set: {
'x-circle-source': 'circle-1'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
app: 'A',
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262',
component: 'A',
service: 'A',
tag: 'tag-example'
},
name: 'A',
namespace: 'namespace'
},
spec: {
ports: [
{
name: 'http',
port: 80,
targetPort: 80
}
],
selector: {
app: 'A'
},
type: 'ClusterIP'
}
} as KubernetesManifest
]
export const routesManifestsSameNamespaceWithServiceAndNoLabels: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v1',
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-1',
},
{
labels: {
component: 'A',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-1","circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
route: [
{
destination: {
host: 'A',
subset: 'circle-1'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-1'
}
},
response: {
set: {
'x-circle-source': 'circle-1'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262',
},
name: 'A',
namespace: 'namespace'
},
spec: {
ports: [
{
name: 'http',
port: 80,
targetPort: 80
}
],
selector: {
app: 'A'
},
type: 'ClusterIP'
}
} as KubernetesManifest
]
export const routesManifestsDiffNamespace: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'diff-namespace',
annotations: {
circles: '["circle-1"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v1',
circleId: 'circle-1',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-1',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'diff-namespace',
annotations: {
circles: '["circle-1"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
route: [
{
destination: {
host: 'A',
subset: 'circle-1'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-1'
}
},
response: {
set: {
'x-circle-source': 'circle-1'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v2',
circleId: 'circle-2',
deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262'
},
name: 'circle-2',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["circle-2"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=circle-2.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'circle-2'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'circle-2'
},
headers: {
request: {
set: {
'x-circle-source': 'circle-2'
}
},
response: {
set: {
'x-circle-source': 'circle-2'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
]
export const routesManifestsWithPreviousDeployment: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["7dedce83-f39d-46d1-98f3-fb9ef3effb05"]'
}
},
spec: {
host: 'A',
subsets: [
{
labels: {
component: 'A',
tag: 'v1',
circleId: '7dedce83-f39d-46d1-98f3-fb9ef3effb05',
deploymentId: 'dbdc12d0-18e9-490b-9e1c-4a4d4592900d'
},
name: '7dedce83-f39d-46d1-98f3-fb9ef3effb05',
}
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'A',
namespace: 'namespace',
annotations: {
circles: '["7dedce83-f39d-46d1-98f3-fb9ef3effb05"]'
}
},
spec: {
gateways: [
],
hosts: [
'A',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=7dedce83-f39d-46d1-98f3-fb9ef3effb05.*'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
},
headers: {
request: {
set: {
'x-circle-source': '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
}
},
response: {
set: {
'x-circle-source': '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
}
}
}
],
route: [
{
destination: {
host: 'A',
subset: '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
},
headers: {
request: {
set: {
'x-circle-source': '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
}
},
response: {
set: {
'x-circle-source': '7dedce83-f39d-46d1-98f3-fb9ef3effb05'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["ae0f14a5-52d2-4619-af6c-18819aa729fe"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v1',
circleId: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
deploymentId: 'c595eb75-dbf9-44a5-8e6f-c2646fadd641'
},
name: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["ae0f14a5-52d2-4619-af6c-18819aa729fe"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=ae0f14a5-52d2-4619-af6c-18819aa729fe.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
},
headers: {
request: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
},
response: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
},
headers: {
request: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
},
response: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
app: 'A',
circleId: '7dedce83-f39d-46d1-98f3-fb9ef3effb05',
component: 'A',
deploymentId: 'dbdc12d0-18e9-490b-9e1c-4a4d4592900d',
service: 'A',
tag: 'tag-example'
},
name: 'A',
namespace: 'namespace'
},
spec: {
ports: [
{
name: 'http',
port: 80,
targetPort: 80
}
],
selector: {
app: 'A'
},
type: 'ClusterIP'
}
} as KubernetesManifest,
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
app: 'B',
circleId: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
component: 'B',
deploymentId: 'c595eb75-dbf9-44a5-8e6f-c2646fadd641',
service: 'B',
tag: 'tag-example'
},
name: 'B',
namespace: 'namespace'
},
spec: {
ports: [
{
name: 'http',
port: 80,
targetPort: 80
}
],
selector: {
app: 'B'
},
type: 'ClusterIP'
}
} as KubernetesManifest
]
export const routesManifestsWithoutPreviousDeployment: KubernetesManifest[] = [
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'DestinationRule',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["ae0f14a5-52d2-4619-af6c-18819aa729fe"]'
}
},
spec: {
host: 'B',
subsets: [
{
labels: {
component: 'B',
tag: 'v1',
circleId: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
deploymentId: 'c595eb75-dbf9-44a5-8e6f-c2646fadd641'
},
name: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
},
],
},
} as KubernetesManifest,
{
apiVersion: AppConstants.ISTIO_RESOURCES_API_VERSION,
kind: 'VirtualService',
metadata: {
name: 'B',
namespace: 'namespace',
annotations: {
circles: '["ae0f14a5-52d2-4619-af6c-18819aa729fe"]'
}
},
spec: {
gateways: [
],
hosts: [
'B',
],
http: [
{
match: [
{
headers: {
cookie: {
regex: '.*x-circle-id=ae0f14a5-52d2-4619-af6c-18819aa729fe.*'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
},
headers: {
request: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
},
response: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
}
]
},
{
match: [
{
headers: {
'x-circle-id': {
exact: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
],
route: [
{
destination: {
host: 'B',
subset: 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
},
headers: {
request: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
},
response: {
set: {
'x-circle-source': 'ae0f14a5-52d2-4619-af6c-18819aa729fe'
}
}
}
}
]
}
]
},
} as KubernetesManifest,
{
apiVersion: 'v1',
kind: 'Service',
metadata: {
labels: {
app: 'B',
circleId: 'ae0f14a5-52d2-4619-af6c-18819aa729fe',
component: 'B',
deploymentId: 'c595eb75-dbf9-44a5-8e6f-c2646fadd641',
service: 'B',
tag: 'tag-example'
},
name: 'B',
namespace: 'namespace'
},
spec: {
ports: [
{
name: 'http',
port: 80,
targetPort: 80
}
],
selector: {
app: 'B'
},
type: 'ClusterIP'
}
} as KubernetesManifest
] | the_stack |
/// <reference path="mocks.d.ts" />
import * as angular from 'angular';
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module 'angular' {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
// Depending on context, it might return a function, however having `void | (() => void)`
// as a return type seems to be not useful. E.g. it requires type assertions in `beforeEach(inject(...))`.
interface IInjectStatic {
(...fns: Array<Injectable<(...args: any[]) => void>>): any; // void | (() => void);
strictDi(val?: boolean): any; // void | (() => void);
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
inject: IInjectStatic;
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module: {
(...modules: any[]): any;
sharedInjector(): void;
};
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number | string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
/**
* **Deprecated** since version 1.7.3. (Use `$flushPendingTasks` instead.)
*
* ---
* Flushes the queue of pending tasks.
*
* _This method is essentially an alias of `$flushPendingTasks`._
*
* > For historical reasons, this method will also flush non-`$timeout` pending tasks, such as
* > `$q` promises and tasks scheduled via `$applyAsync` and `$evalAsync`.
*
* @param delay - The maximum timeout amount to flush up until.
*/
flush(delay?: number): void;
/**
* **Deprecated** since version 1.7.3. (Use `$verifyNoPendingTasks` instead.)
*
* ---
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
* are still pending tasks.
*
* _This method is essentially an alias of `$verifyNoPendingTasks` (called with no arguments)._
*
* > For historical reasons, this method will also verify non-`$timeout` pending tasks, such as
* > pending `$http` requests, in-progress `$route` transitions, unresolved `$q` promises and
* > tasks scheduled via `$applyAsync` and `$evalAsync`.
* >
* > It is recommended to use `$verifyNoPendingTasks` instead, which additionally supports
* > verifying a specific type of tasks. For example, you can verify there are no pending
* > timeouts with `$verifyNoPendingTasks('$timeout')`.
*/
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
/**
* Runs interval tasks scheduled to be run in the next `millis` milliseconds.
*
* @param millis - The maximum timeout amount to flush up until.
* @return The amount of time moved forward.
*/
flush(millis: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// ControllerService mock
// see https://docs.angularjs.org/api/ngMock/service/$controller
// This interface extends http://docs.angularjs.org/api/ng.$controller
///////////////////////////////////////////////////////////////////////////
interface IControllerService {
// Although the documentation doesn't state this, locals are optional
<T>(
controllerConstructor: (new (...args: any[]) => T) | ((...args: any[]) => T) | string,
locals?: any,
bindings?: any
): T;
}
///////////////////////////////////////////////////////////////////////////
// ComponentControllerService
// see https://docs.angularjs.org/api/ngMock/service/$componentController
///////////////////////////////////////////////////////////////////////////
interface IComponentControllerService {
// TBinding is an interface exposed by a component as per John Papa's style guide
// https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top
<T, TBinding>(
componentName: string,
locals: { $scope?: IScope; [key: string]: any },
bindings?: TBinding,
ident?: string
): T;
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes pending requests using the trained responses. Requests are flushed in the order they
* were made, but it is also possible to skip one or more requests (for example to have them
* flushed later). This is useful for simulating scenarios where responses arrive from the server
* in any order.
*
* If there are no pending requests to flush when the method is called, an exception is thrown (as
* this is typically a sign of programming error).
*
* @param count Number of responses to flush. If undefined/null, all pending requests (starting
* after `skip`) will be flushed.
* @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_
*/
flush(count?: number, skip?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest.
* NOTE: this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
*/
verifyNoOutstandingExpectation(digest?: boolean): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expect(
method: string,
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectDELETE(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectGET(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectHEAD(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectJSONP(
url: string | RegExp | ((url: string) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPATCH(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPOST(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
expectPUT(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new request expectation that compares only with the requested route.
* This method offers colon delimited matching of the url path, ignoring the query string.
* This allows declarations similar to how application routes are configured with `$routeProvider`.
* As this method converts the definition url to regex, declaration order is important.
* @param method HTTP method
* @param url HTTP url string that supports colon param matching
*/
expectRoute(method: string, url: string): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
when(
method: string,
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenDELETE(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in request url described above
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenGET(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenHEAD(
url: string | RegExp | ((url: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenJSONP(
url: string | RegExp | ((url: string) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPATCH(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true
* if the url matches the current definition.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPOST(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true
* if the url matches the current definition.
* @param data HTTP request body or function that receives data string and returns true if the data
* is as expected.
* @param headers HTTP headers or function that receives http header object and returns true if the
* headers match the current definition.
* @param keys Array of keys to assign to regex matches in the request url.
*/
whenPUT(
url: string | RegExp | ((url: string) => boolean),
data?: string | RegExp | object | ((data: string) => boolean),
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
keys?: string[]
): mock.IRequestHandler;
/**
* Creates a new backend definition that compares only with the requested route.
* This method offers colon delimited matching of the url path, ignoring the query string.
* This allows declarations similar to how application routes are configured with `$routeProvider`.
* As this method converts the definition url to regex, declaration order is important.
* @param method HTTP method.
* @param url HTTP url string that supports colon param matching.
*/
whenRoute(method: string, url: string): mock.IRequestHandler;
}
///////////////////////////////////////////////////////////////////////////
// FlushPendingTasksService
// see https://docs.angularjs.org/api/ngMock/service/$flushPendingTasks
///////////////////////////////////////////////////////////////////////////
interface IFlushPendingTasksService {
/**
* Flushes all currently pending tasks and executes the corresponding callbacks.
*
* Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be
* executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all
* other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but
* still asynchronously).
*
* If no delay is specified, it uses a delay such that all currently pending tasks are flushed.
*
* The types of tasks that are flushed include:
*
* - Pending timeouts (via `$timeout`).
* - Pending tasks scheduled via `$applyAsync`.
* - Pending tasks scheduled via `$evalAsync`.
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
*
* > Periodic tasks scheduled via `$interval` use a different queue and are not flushed by
* > `$flushPendingTasks()`. Use `$interval.flush(millis)` instead.
*
* @param millis - The number of milliseconds to flush.
*/
(delay?: number): void;
}
///////////////////////////////////////////////////////////////////////////
// VerifyNoPendingTasksService
// see https://docs.angularjs.org/api/ngMock/service/$verifyNoPendingTasks
///////////////////////////////////////////////////////////////////////////
interface IVerifyNoPendingTasksService {
/**
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
* are still pending tasks.
*
* You can check for a specific type of tasks only, by specifying a `taskType`.
*
* Available task types:
*
* - `$timeout`: Pending timeouts (via `$timeout`).
* - `$http`: Pending HTTP requests (via `$http`).
* - `$route`: In-progress route transitions (via `$route`).
* - `$applyAsync`: Pending tasks scheduled via `$applyAsync`.
* - `$evalAsync`: Pending tasks scheduled via `$evalAsync`.
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
*
* > Periodic tasks scheduled via `$interval` use a different queue and are not taken into
* > account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no
* > pending `$interval` tasks.
*
* @param taskType - The type of tasks to check for.
*/
(taskType?: string): void;
}
///////////////////////////////////////////////////////////////////////////
// AnimateService
// see https://docs.angularjs.org/api/ngMock/service/$animate
///////////////////////////////////////////////////////////////////////////
namespace animate {
interface IAnimateService {
/**
* This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining
* animation frames and/or callbacks.
*/
closeAndFlush(): void;
/**
* This method is used to flush the pending callbacks and animation frames to either start
* an animation or conclude an animation. Note that this will not actually close an
* actively running animation (see `closeAndFlush()`} for that).
*/
flush(): void;
}
}
namespace mock {
/** Object returned by the the mocked HttpBackendService expect/when methods */
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys
* to regex matches in the request url and returns an array containing response status (number), data,
* headers, and status text.
*/
respond(
func: ((
method: string,
url: string,
data: string | object,
headers: IHttpHeaders,
params: { [key: string]: string }
) => [number, string | object, IHttpHeaders, string])
): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(
status: number,
data?: string | object,
headers?: IHttpHeaders,
responseText?: string
): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(
data: string | object,
headers?: IHttpHeaders,
responseText?: string
): IRequestHandler;
/**
* Any request matching a backend definition or expectation with passThrough handler will be
* passed through to the real backend (an XHR request will be made to the server.)
* Available when ngMockE2E is loaded
*/
passThrough(): IRequestHandler;
}
interface IHttpHeaders {
[headerName: string]: any;
}
/**
* Contains additional event data used by the `browserTrigger` function when creating an event.
*/
interface IBrowserTriggerEventData {
/**
* [Event.bubbles](https://developer.mozilla.org/docs/Web/API/Event/bubbles).
* Not applicable to all events.
*/
bubbles?: boolean;
/**
* [Event.cancelable](https://developer.mozilla.org/docs/Web/API/Event/cancelable).
* Not applicable to all events.
*/
cancelable?: boolean;
/**
* [charCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/charcode)
* for keyboard events (keydown, keypress, and keyup).
*/
charcode?: number;
/**
* [data](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data) for
* [CompositionEvents](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
*/
data?: string;
/**
* The elapsedTime for
* [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent)
* and [AnimationEvent](https://developer.mozilla.org/docs/Web/API/AnimationEvent).
*/
elapsedTime?: number;
/**
* [keyCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keycode)
* for keyboard events (keydown, keypress, and keyup).
*/
keycode?: number;
/**
* An array of possible modifier keys (ctrl, alt, shift, meta) for
* [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) and
* keyboard events (keydown, keypress, and keyup).
*/
keys?: Array<'ctrl' | 'alt' | 'shift' | 'meta'>;
/**
* The [relatedTarget](https://developer.mozilla.org/docs/Web/API/MouseEvent/relatedTarget)
* for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent).
*/
relatedTarget?: Node;
/**
* [which](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which)
* for keyboard events (keydown, keypress, and keyup).
*/
which?: number;
/**
* x-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
*/
x?: number;
/**
* y-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
*/
y?: number;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
// Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
// declare var module: (...modules: any[]) => any;
declare global {
const inject: angular.IInjectStatic;
/**
* This is a global (window) function that is only available when the `ngMock` module is included.
* It can be used to trigger a native browser event on an element, which is useful for unit testing.
*
* @param element Either a wrapped jQuery/jqLite node or a DOM element.
* @param eventType Optional event type. If none is specified, the function tries to determine the
* right event type for the element, e.g. `change` for `input[text]`.
* @param eventData An optional object which contains additional event data used when creating the
* event.
*/
function browserTrigger(
element: JQuery | Element,
eventType?: string,
eventData?: angular.mock.IBrowserTriggerEventData
): void;
} | the_stack |
import { app, dialog, Menu } from 'electron';
import path from 'path';
import { MainReceiver } from '../actions/main';
import { CLOUD_PROTOCOL, STUDIO_PROTOCOL } from '../constants';
import * as dataImporter from '../services/data-importer';
import { showError } from '../ui/reusable/errors';
import { RealmLoadingMode } from '../utils/realms';
import { IRealmBrowserWindowProps } from '../windows/WindowProps';
import { removeRendererDirectories } from '../utils';
import { CertificateManager } from './CertificateManager';
import { MainActions } from './MainActions';
import { getDefaultMenuTemplate } from './MainMenu';
import { Updater } from './Updater';
import { WindowManager } from './WindowManager';
export class Application {
public static sharedApplication = new Application();
private windowManager = new WindowManager();
private updater = new Updater(this.windowManager);
private certificateManager = new CertificateManager();
private actionHandlers = {
[MainActions.CheckForUpdates]: () => {
this.checkForUpdates();
},
[MainActions.ShowImportData]: (format: dataImporter.ImportFormat) => {
return this.showImportData(format);
},
[MainActions.ShowOpenLocalRealm]: () => {
return this.showOpenLocalRealm();
},
[MainActions.ShowRealmBrowser]: (props: IRealmBrowserWindowProps) => {
return this.showRealmBrowser(props);
},
[MainActions.ClearRendererCache]: async () => {
await this.windowManager.closeAllWindows();
await removeRendererDirectories();
await this.showGreeting();
},
};
// Instantiate a receiver that will receive actions from the main process itself.
private loopbackReceiver = new MainReceiver(this.actionHandlers);
// All files opened while app is loading will be stored on this array and opened when app is ready
private delayedRealmOpens: string[] = [];
public run() {
// Check to see if this is the first instance or not
const hasAnotherInstance = app.requestSingleInstanceLock() === false;
if (hasAnotherInstance) {
// Quit the app if started multiple times
app.quit();
} else {
// Register as a listener for specific URLs
this.registerProtocols();
// In Mac we detect the files opened with `open-file` event otherwise we need get it from `process.argv`
if (process.platform !== 'darwin') {
this.processArguments(process.argv);
}
// Register all app listeners
this.addAppListeners();
// If its already ready - the handler won't be called
if (app.isReady()) {
this.onReady();
}
// Handle any second instances of the Application
app.on('second-instance', this.onInstanceStarted);
}
}
public destroy() {
this.removeAppListeners();
this.updater.destroy();
this.certificateManager.destroy();
this.windowManager.closeAllWindows();
this.certificateManager.destroy();
this.loopbackReceiver.destroy();
}
public userDataPath(): string {
return app.getPath('userData');
}
// Implementation of action handlers below
public showGreeting(): Promise<void> {
const { window, existing } = this.windowManager.createWindow({
type: 'greeting',
props: {},
});
if (existing) {
window.focus();
return Promise.resolve();
} else {
return new Promise(resolve => {
// Save this for later
// Show the window, the first time its ready-to-show
window.once('ready-to-show', () => {
window.show();
resolve();
});
// Check for updates, every time the contents has loaded
window.webContents.on('did-finish-load', () => {
this.updater.checkForUpdates(true);
});
this.updater.addListeningWindow(window);
window.once('close', () => {
this.updater.removeListeningWindow(window);
});
});
}
}
public async showOpenLocalRealm() {
const response = await dialog.showOpenDialog({
properties: ['openFile', 'multiSelections'],
filters: [
{ name: 'Realm Files', extensions: ['realm'] },
{ name: 'All Files', extensions: ['*'] },
],
});
const realmsLoaded = response.filePaths.map(filePath =>
this.openLocalRealmAtPath(filePath),
);
// Resolves when all realms are opened or rejects when a single realm fails
return Promise.all(realmsLoaded);
}
public showImportData(format: dataImporter.ImportFormat) {
// Ask the users for the file names of files to import
const paths = dataImporter.showOpenDialog(format);
if (!paths || paths.length === 0) {
// Don't do anything if the user cancelled or selected no files
return;
}
// Generate the Realm from the provided CSV file(s)
const schema = dataImporter.generateSchema(
dataImporter.ImportFormat.CSV,
paths,
);
// Start the import
const defaultPath = path.dirname(paths[0]) + '/default.realm';
const destinationPath = dialog.showSaveDialogSync({
defaultPath,
title: 'Choose where to store the imported data',
filters: [{ name: 'Realm file', extensions: ['realm'] }],
});
if (!destinationPath) {
// Don't do anything if the user cancelled or selected no files
return;
}
// Open the Realm Browser, which will perform the import
return this.showRealmBrowser({
realm: {
mode: RealmLoadingMode.Local,
path: destinationPath,
},
import: { format, paths, schema },
});
}
public showRealmBrowser(props: IRealmBrowserWindowProps): Promise<void> {
const { window, existing } = this.windowManager.createWindow({
type: 'realm-browser',
props,
});
if (existing) {
window.focus();
return Promise.resolve();
} else {
return new Promise(resolve => {
// Set the represented filename
if (process.platform === 'darwin' && props.realm.mode === 'local') {
window.setRepresentedFilename(props.realm.path);
}
window.show();
window.webContents.once('did-finish-load', () => {
resolve();
});
});
}
}
public checkForUpdates() {
this.updater.checkForUpdates();
}
private addAppListeners() {
app.addListener('ready', this.onReady);
app.addListener('activate', this.onActivate);
app.addListener('open-file', this.onOpenFile);
app.addListener('window-all-closed', this.onWindowAllClosed);
app.addListener('web-contents-created', this.onWebContentsCreated);
}
private removeAppListeners() {
app.removeListener('ready', this.onReady);
app.removeListener('activate', this.onActivate);
app.removeListener('open-file', this.onOpenFile);
app.removeListener('window-all-closed', this.onWindowAllClosed);
app.removeListener('web-contents-created', this.onWebContentsCreated);
}
private onReady = async () => {
this.setDefaultMenu();
if (this.windowManager.windows.length === 0) {
// Wait for the greeting window to show - if no other windows are open
await this.showGreeting();
}
this.performDelayedTasks();
};
private onActivate = () => {
if (this.windowManager.windows.length === 0) {
this.showGreeting();
}
};
private onOpenFile = (e: Electron.Event, filePath: string) => {
e.preventDefault();
if (!app.isReady()) {
this.delayedRealmOpens.push(filePath);
} else {
this.openLocalRealmAtPath(filePath).catch(err =>
showError(`Failed opening the file "${filePath}"`, err),
);
}
};
private onWindowAllClosed = () => {
if (process.platform !== 'darwin') {
app.quit();
} else {
this.setDefaultMenu();
}
};
private onWebContentsCreated = (
event: Electron.Event,
webContents: Electron.WebContents,
) => {
const receiver = new MainReceiver(this.actionHandlers, webContents);
webContents.once('destroyed', () => {
receiver.destroy();
});
};
private registerProtocols() {
this.registerProtocol(CLOUD_PROTOCOL);
this.registerProtocol(STUDIO_PROTOCOL);
}
/**
* If not already - register this as the default protocol client for a protocol
*/
private registerProtocol(protocol: string) {
if (!app.isDefaultProtocolClient(protocol)) {
const success = app.setAsDefaultProtocolClient(protocol);
if (!success) {
dialog.showErrorBox(
'Failed when registering protocols',
`Studio could not register the ${protocol}:// protocol.`,
);
}
}
}
/**
* This is called when another instance of the app is started on Windows or Linux
*/
private onInstanceStarted = async (
event: Event,
argv: string[],
workingDirectory: string,
) => {
this.processArguments(argv);
await this.showGreeting();
this.performDelayedTasks();
};
private setDefaultMenu = () => {
const menuTemplate = getDefaultMenuTemplate(this.setDefaultMenu);
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
};
private openLocalRealmAtPath = (filePath: string) => {
return this.showRealmBrowser({
realm: {
mode: RealmLoadingMode.Local,
path: filePath,
},
});
};
private processArguments(argv: string[]) {
this.delayedRealmOpens = argv.filter(arg => {
return arg.endsWith('.realm');
});
}
private async performDelayedTasks() {
// Open all the realms to be loaded
const realmsLoaded = this.delayedRealmOpens.map(realmPath => {
return this.openLocalRealmAtPath(realmPath);
});
// Reset the array to prevent double loading
this.delayedRealmOpens = [];
// Wait for all realms to open or show an error on failure
await Promise.all(realmsLoaded).catch(err =>
showError(`Failed opening Realm`, err),
);
}
}
if (module.hot) {
module.hot.dispose(() => {
Application.sharedApplication.destroy();
});
} | the_stack |
import * as Bluebird from 'bluebird';
import * as Docker from 'dockerode';
import { EventEmitter } from 'events';
import * as _ from 'lodash';
import StrictEventEmitter from 'strict-event-emitter-types';
import * as config from '../config';
import * as db from '../db';
import * as constants from '../lib/constants';
import { DeltaFetchOptions, FetchOptions, docker } from '../lib/docker-utils';
import * as dockerUtils from '../lib/docker-utils';
import {
DeltaStillProcessingError,
NotFoundError,
StatusError,
} from '../lib/errors';
import * as LogTypes from '../lib/log-types';
import * as logger from '../logger';
import { ImageDownloadBackoffError } from './errors';
import type { Service } from './service';
import { strict as assert } from 'assert';
import log from '../lib/supervisor-console';
interface FetchProgressEvent {
percentage: number;
}
export interface Image {
id?: number;
/**
* image [registry/]repo@digest or [registry/]repo:tag
*/
name: string;
/**
* @deprecated to be removed in target state v4
*/
appId: number;
appUuid: string;
/**
* @deprecated to be removed in target state v4
*/
serviceId: number;
serviceName: string;
/**
* @deprecated to be removed in target state v4
*/
imageId: number;
/**
* @deprecated to be removed in target state v4
*/
releaseId: number;
commit: string;
dependent: number;
dockerImageId?: string;
status?: 'Downloading' | 'Downloaded' | 'Deleting';
downloadProgress?: number | null;
}
// Setup an event emitter
interface ImageEvents {
change: void;
}
class ImageEventEmitter extends (EventEmitter as new () => StrictEventEmitter<
EventEmitter,
ImageEvents
>) {}
const events = new ImageEventEmitter();
export const on: typeof events['on'] = events.on.bind(events);
export const once: typeof events['once'] = events.once.bind(events);
export const removeListener: typeof events['removeListener'] = events.removeListener.bind(
events,
);
export const removeAllListeners: typeof events['removeAllListeners'] = events.removeAllListeners.bind(
events,
);
const imageFetchFailures: Dictionary<number> = {};
const imageFetchLastFailureTime: Dictionary<ReturnType<
typeof process.hrtime
>> = {};
const imageCleanupFailures: Dictionary<number> = {};
type ImageState = Pick<Image, 'status' | 'downloadProgress'>;
type ImageTask = {
// Indicates whether the task has been finished
done?: boolean;
// Current image state of the task
context: Image;
// Update the task with new context. This is a pure function
// meaning it doesn't modify the original task
update: (change?: ImageState) => ImageTaskUpdate;
// Finish the task. This is a pure function
// meaning it doesn't modify the original task
finish: () => ImageTaskUpdate;
};
type ImageTaskUpdate = [ImageTask, boolean];
// Create new running task with the given initial context
function createTask(initialContext: Image) {
// Task has only two state, is either running or finished
const running = (context: Image): ImageTask => {
return {
context,
update: ({ status, downloadProgress }: ImageState) =>
// Keep current state
[
running({
...context,
...(status && { status }),
...(downloadProgress && { downloadProgress }),
}),
// Only mark the task as changed if there is new data
[status, downloadProgress].some((v) => !!v),
],
finish: () => [finished(context), true],
};
};
// Once the task is finished, it cannot go back to a running state
const finished = (context: Image): ImageTask => {
return {
done: true,
context,
update: () => [finished(context), false],
finish: () => [finished(context), false],
};
};
return running(initialContext);
}
const runningTasks: { [imageName: string]: ImageTask } = {};
function reportEvent(event: 'start' | 'update' | 'finish', state: Image) {
const { name: imageName } = state;
// Get the current task and update it in memory
const currentTask = runningTasks[imageName] ?? createTask(state);
runningTasks[imageName] = currentTask;
const stateChanged = (() => {
switch (event) {
case 'start':
return true; // always report change on start
case 'update':
const [updatedTask, changedAfterUpdate] = currentTask.update(state);
runningTasks[imageName] = updatedTask;
return changedAfterUpdate; // report change only if the task context changed
case 'finish':
const [, changedAfterFinish] = currentTask.finish();
delete runningTasks[imageName];
return changedAfterFinish; // report change depending on the state of the task
}
})();
if (stateChanged) {
events.emit('change');
}
}
type ServiceInfo = Pick<
Service,
| 'imageName'
| 'appId'
| 'serviceId'
| 'serviceName'
| 'imageId'
| 'releaseId'
| 'appUuid'
| 'commit'
>;
export function imageFromService(service: ServiceInfo): Image {
// We know these fields are defined because we create these images from target state
return {
name: service.imageName!,
appId: service.appId,
appUuid: service.appUuid!,
serviceId: service.serviceId!,
serviceName: service.serviceName!,
imageId: service.imageId!,
releaseId: service.releaseId!,
commit: service.commit!,
dependent: 0,
};
}
export async function triggerFetch(
image: Image,
opts: FetchOptions,
onFinish: (success: boolean) => void,
serviceName: string,
): Promise<void> {
const appUpdatePollInterval = await config.get('appUpdatePollInterval');
if (imageFetchFailures[image.name] != null) {
// If we are retrying a pull within the backoff time of the last failure,
// we need to throw an error, which will be caught in the device-state
// engine, and ensure that we wait a bit lnger
const minDelay = Math.min(
2 ** imageFetchFailures[image.name] * constants.backoffIncrement,
appUpdatePollInterval,
);
const timeSinceLastError = process.hrtime(
imageFetchLastFailureTime[image.name],
);
const timeSinceLastErrorMs =
timeSinceLastError[0] * 1000 + timeSinceLastError[1] / 1e6;
if (timeSinceLastErrorMs < minDelay) {
throw new ImageDownloadBackoffError();
}
}
const onProgress = (progress: FetchProgressEvent) => {
reportEvent('update', {
...image,
downloadProgress: progress.percentage,
status: 'Downloading',
});
};
let success: boolean;
try {
const imageName = normalise(image.name);
image = { ...image, name: imageName };
// Look for a matching image on the engine
const img = await inspectByName(image.name);
// If we are at this point, the image may not have the proper tag so add it
await tagImage(img.Id, image.name);
// Create image on the database if it already exists on the engine
await markAsSupervised({ ...image, dockerImageId: img.Id });
success = true;
} catch (e) {
if (!NotFoundError(e)) {
if (!(e instanceof ImageDownloadBackoffError)) {
addImageFailure(image.name);
}
throw e;
}
// Report a fetch start
reportEvent('start', {
...image,
status: 'Downloading',
downloadProgress: 0,
});
try {
let id;
if (opts.delta && (opts as DeltaFetchOptions).deltaSource != null) {
id = await fetchDelta(image, opts, onProgress, serviceName);
} else {
id = await fetchImage(image, opts, onProgress);
}
// Tag the image with the proper reference
await tagImage(id, image.name);
// Create image on the database
await markAsSupervised({ ...image, dockerImageId: id });
logger.logSystemEvent(LogTypes.downloadImageSuccess, { image });
success = true;
delete imageFetchFailures[image.name];
delete imageFetchLastFailureTime[image.name];
} catch (err) {
if (err instanceof DeltaStillProcessingError) {
// If this is a delta image pull, and the delta still hasn't finished generating,
// don't show a failure message, and instead just inform the user that it's remotely
// processing
logger.logSystemEvent(LogTypes.deltaStillProcessingError, {});
} else {
addImageFailure(image.name);
logger.logSystemEvent(LogTypes.downloadImageError, {
image,
error: err,
});
}
success = false;
}
}
reportEvent('finish', { ...image, status: 'Downloaded' });
onFinish(success);
}
export async function remove(image: Image): Promise<void> {
try {
await removeImageIfNotNeeded(image);
} catch (e) {
logger.logSystemEvent(LogTypes.deleteImageError, {
image,
error: e,
});
throw e;
}
}
export function getByDockerId(id: string): Promise<Image> {
return db.models('image').where({ dockerImageId: id }).first();
}
export async function removeByDockerId(id: string): Promise<void> {
const image = await getByDockerId(id);
await remove(image);
}
export function getNormalisedTags(image: Docker.ImageInfo): string[] {
return (image.RepoTags || []).map(normalise);
}
async function withImagesFromDockerAndDB<T>(
cb: (dockerImages: Docker.ImageInfo[], composeImages: Image[]) => T,
) {
const [normalisedImages, dbImages] = await Promise.all([
Bluebird.map(docker.listImages({ digests: true }), (image) => ({
...image,
RepoTag: getNormalisedTags(image),
})),
db.models('image').select(),
]);
return cb(normalisedImages, dbImages);
}
function addImageFailure(imageName: string, time = process.hrtime()) {
imageFetchLastFailureTime[imageName] = time;
imageFetchFailures[imageName] =
imageFetchFailures[imageName] != null
? imageFetchFailures[imageName] + 1
: 1;
}
function matchesTagOrDigest(
image: Image,
dockerImage: Docker.ImageInfo,
): boolean {
return (
_.includes(dockerImage.RepoTags, dockerUtils.getImageWithTag(image.name)) ||
_.some(dockerImage.RepoDigests, (digest) =>
hasSameDigest(image.name, digest),
)
);
}
function isAvailableInDocker(
image: Image,
dockerImages: Docker.ImageInfo[],
): boolean {
return _.some(
dockerImages,
(dockerImage) =>
matchesTagOrDigest(image, dockerImage) ||
image.dockerImageId === dockerImage.Id,
);
}
export async function getAvailable(): Promise<Image[]> {
return withImagesFromDockerAndDB((dockerImages, supervisedImages) =>
_.filter(supervisedImages, (image) =>
isAvailableInDocker(image, dockerImages),
),
);
}
export function getDownloadingImageNames(): string[] {
return Object.values(runningTasks)
.filter((t) => t.context.status === 'Downloading')
.map((t) => t.context.name);
}
export async function cleanImageData(): Promise<void> {
const imagesToRemove = await withImagesFromDockerAndDB(
async (dockerImages, supervisedImages) => {
for (const supervisedImage of supervisedImages) {
// If the supervisor was interrupted between fetching an image and storing its id,
// some entries in the db might need to have the dockerImageId populated
if (supervisedImage.dockerImageId == null) {
const id = _.get(
_.find(dockerImages, (dockerImage) =>
matchesTagOrDigest(supervisedImage, dockerImage),
),
'Id',
);
if (id != null) {
await db
.models('image')
.update({ dockerImageId: id })
.where(supervisedImage);
supervisedImage.dockerImageId = id;
}
}
}
// If the supervisor was interrupted between fetching the image and adding
// the tag, the engine image may have been left without the proper tag leading
// to issues with removal. Add tag just in case
await Promise.all(
supervisedImages
.filter((image) => isAvailableInDocker(image, dockerImages))
.map((image) => tagImage(image.dockerImageId!, image.name)),
).catch(() => []); // Ignore errors
// If the image is in the DB but not available in docker, return it
// for removal on the database
return _.reject(supervisedImages, (image) =>
isAvailableInDocker(image, dockerImages),
);
},
);
const ids = _(imagesToRemove).map('id').compact().value();
await db.models('image').del().whereIn('id', ids);
}
/**
* Get the current state of all downloaded and downloading images on the device
*/
export const getState = async () => {
const images = (await getAvailable()).map((img) => ({
...img,
status: 'Downloaded' as Image['status'],
downloadProgress: null,
}));
const imagesFromRunningTasks = Object.values(runningTasks).map(
(task) => task.context,
);
const runningImageNames = imagesFromRunningTasks.map((img) => img.name);
// TODO: this is possibly wrong, the value from getAvailable should be more reliable
// than the value from running tasks
return imagesFromRunningTasks.concat(
images.filter((img) => !runningImageNames.includes(img.name)),
);
};
export async function update(image: Image): Promise<void> {
const formattedImage = format(image);
await db
.models('image')
.update(formattedImage)
.where({ name: formattedImage.name });
}
const tagImage = async (dockerImageId: string, imageName: string) => {
const { repo, tag } = dockerUtils.getRepoAndTag(imageName);
return await docker.getImage(dockerImageId).tag({ repo, tag });
};
export const save = async (image: Image): Promise<void> => {
const img = await inspectByName(image.name);
// Ensure image is tagged
await tagImage(img.Id, image.name);
image = _.clone(image);
image.dockerImageId = img.Id;
await markAsSupervised(image);
};
async function getImagesForCleanup(): Promise<string[]> {
const images: string[] = [];
const supervisorImageInfo = dockerUtils.getRegistryAndName(
constants.supervisorImage,
);
const [supervisorImage, usedImageIds] = await Promise.all([
docker.getImage(constants.supervisorImage).inspect(),
db
.models('image')
.select('dockerImageId')
.then((vals) => vals.map((img: Image) => img.dockerImageId)),
]);
// TODO: remove after we agree on what to do for
// supervisor image cleanup after hup
const supervisorRepos = [supervisorImageInfo.imageName];
// If we're on the new balena/ARCH-supervisor image
if (_.startsWith(supervisorImageInfo.imageName, 'balena/')) {
supervisorRepos.push(
supervisorImageInfo.imageName.replace(/^balena/, 'resin'),
);
}
// TODO: same as above, we no longer use tags to identify supervisors
const isSupervisorRepoTag = ({
imageName,
tagName,
}: {
imageName: string;
tagName?: string;
}) => {
return (
_.some(supervisorRepos, (repo) => imageName === repo) &&
tagName !== supervisorImageInfo.tagName
);
};
const dockerImages = await docker.listImages({ digests: true });
for (const image of dockerImages) {
// Cleanup should remove truly dangling images (i.e dangling and with no digests)
if (isDangling(image) && !_.includes(usedImageIds, image.Id)) {
images.push(image.Id);
} else if (!_.isEmpty(image.RepoTags) && image.Id !== supervisorImage.Id) {
// We also remove images from the supervisor repository with a different tag
for (const tag of image.RepoTags) {
const imageNameComponents = dockerUtils.getRegistryAndName(tag);
// If
if (isSupervisorRepoTag(imageNameComponents)) {
images.push(image.Id);
}
}
}
}
return _(images)
.uniq()
.filter(
(image) =>
imageCleanupFailures[image] == null ||
Date.now() - imageCleanupFailures[image] >
constants.imageCleanupErrorIgnoreTimeout,
)
.value();
}
// Look for an image in the engine with registry/image as reference (tag)
// for images with deltas this should return unless there is some inconsistency
// and the tag was deleted.
const inspectByReference = async (imageName: string) => {
const { registry, imageName: name, tagName } = dockerUtils.getRegistryAndName(
imageName,
);
const repo = [registry, name].filter((s) => !!s).join('/');
const reference = [repo, tagName].filter((s) => !!s).join(':');
return await docker
.listImages({
digests: true,
filters: { reference: [reference] },
})
.then(([img]) =>
!!img
? docker.getImage(img.Id).inspect()
: Promise.reject(
new StatusError(
404,
`Failed to find an image matching ${imageName}`,
),
),
);
};
// Get image by the full image URI. This will only work for regular pulls
// and old style images `repo:tag`.
const inspectByURI = async (imageName: string) =>
await docker.getImage(imageName).inspect();
// Look in the database for an image with same digest or same name and
// get the dockerImageId from there. If this fails the image may still be on the
// engine but we need to re-trigger fetch and let the engine tell us if the
// image data is there.
const inspectByDigest = async (imageName: string) => {
const { digest } = dockerUtils.getRegistryAndName(imageName);
return await db
.models('image')
.where('name', 'like', `%${digest}`)
.orWhere({ name: imageName }) // Default to looking for the full image name
.select()
.then((images) => images.filter((img: Image) => img.dockerImageId !== null))
// Assume that all db entries will point to the same dockerImageId, so use
// the first one. If this assumption is false, there is a bug with cleanup
.then(([img]) =>
!!img
? docker.getImage(img.dockerImageId).inspect()
: Promise.reject(
new StatusError(
404,
`Failed to find an image matching ${imageName}`,
),
),
);
};
export async function inspectByName(imageName: string) {
// Fail fast if image name is null or empty string
assert(!!imageName, `image name to inspect is invalid, got: ${imageName}`);
// Run the queries in sequence, return the first one that matches or
// the error from the last query
return await [inspectByURI, inspectByReference, inspectByDigest].reduce(
(promise, query) => promise.catch(() => query(imageName)),
Promise.reject(
'Promise sequence in inspectByName is broken. This is a bug.',
),
);
}
export async function isCleanupNeeded() {
return !_.isEmpty(await getImagesForCleanup());
}
export async function cleanup() {
const images = await getImagesForCleanup();
for (const image of images) {
log.debug(`Cleaning up ${image}`);
try {
await docker.getImage(image).remove({ force: true });
delete imageCleanupFailures[image];
} catch (e) {
logger.logSystemMessage(
`Error cleaning up ${image}: ${e.message} - will ignore for 1 hour`,
{ error: e },
'Image cleanup error',
);
imageCleanupFailures[image] = Date.now();
}
}
}
export function isSameImage(
image1: Pick<Image, 'name'>,
image2: Pick<Image, 'name'>,
): boolean {
return (
image1?.name === image2?.name || hasSameDigest(image1?.name, image2?.name)
);
}
export function normalise(imageName: string) {
return dockerUtils.normaliseImageName(imageName);
}
function isDangling(image: Docker.ImageInfo): boolean {
return (
(_.isEmpty(image.RepoTags) ||
_.isEqual(image.RepoTags, ['<none>:<none>'])) &&
(_.isEmpty(image.RepoDigests) ||
_.isEqual(image.RepoDigests, ['<none>@<none>']))
);
}
function hasSameDigest(
name1: Nullable<string>,
name2: Nullable<string>,
): boolean {
const hash1 = name1 != null ? name1.split('@')[1] : null;
const hash2 = name2 != null ? name2.split('@')[1] : null;
return hash1 != null && hash1 === hash2;
}
async function removeImageIfNotNeeded(image: Image): Promise<void> {
let removed: boolean;
// We first fetch the image from the DB to ensure it exists,
// and get the dockerImageId and any other missing fields
const images = await db.models('image').select().where(image);
if (images.length === 0) {
removed = false;
}
const img = images[0];
try {
const { registry, imageName, tagName } = dockerUtils.getRegistryAndName(
img.name,
);
// Look for an image in the engine with registry/image as reference (tag)
// for images with deltas this should return unless there is some inconsistency
// and the tag was deleted
const repo = [registry, imageName].filter((s) => !!s).join('/');
const reference = [repo, tagName].filter((s) => !!s).join(':');
const tags = (
await docker.listImages({
digests: true,
filters: { reference: [reference] },
})
).reduce(
(tagList, imgInfo) => tagList.concat(imgInfo.RepoTags || []),
[] as string[],
);
reportEvent('start', { ...image, status: 'Deleting' });
logger.logSystemEvent(LogTypes.deleteImage, { image });
// The engine doesn't handle concurrency too well. If two requests to
// remove the last image tag are sent to the engine at the same time
// (e.g. for two services built from the same image).
// that can lead to weird behavior with the error
// `(HTTP code 500) server error - unrecognized image ID`.
// This random delay tries to prevent that
await new Promise((resolve) => setTimeout(resolve, Math.random() * 100));
// Remove all matching tags in sequence
// as removing in parallel causes some engine weirdness (see above)
// this stops on the first error
await tags.reduce(
(promise, tag) => promise.then(() => docker.getImage(tag).remove()),
Promise.resolve(),
);
// Check for any remaining digests.
const digests = (
await docker.listImages({
digests: true,
filters: { reference: [reference] },
})
).reduce(
(digestList, imgInfo) => digestList.concat(imgInfo.RepoDigests || []),
[] as string[],
);
// Remove all remaining digests
await digests.reduce(
(promise, digest) => promise.then(() => docker.getImage(digest).remove()),
Promise.resolve(),
);
// Mark the image as removed
removed = true;
} catch (e) {
if (NotFoundError(e)) {
removed = false;
} else {
throw e;
}
} finally {
reportEvent('finish', image);
}
await db.models('image').del().where({ id: img.id });
if (removed) {
logger.logSystemEvent(LogTypes.deleteImageSuccess, { image });
}
}
async function markAsSupervised(image: Image): Promise<void> {
const formattedImage = format(image);
await db.upsertModel(
'image',
formattedImage,
// TODO: Upsert to new values only when they already match? This is likely a bug
// and currently acts like an "insert if not exists"
formattedImage,
);
}
function format(image: Image): Partial<Omit<Image, 'id'>> {
return _(image)
.defaults({
serviceId: null,
serviceName: null,
imageId: null,
releaseId: null,
commit: null,
dependent: 0,
dockerImageId: null,
})
.omit('id')
.value();
}
async function fetchDelta(
image: Image,
opts: FetchOptions,
onProgress: (evt: FetchProgressEvent) => void,
serviceName: string,
): Promise<string> {
logger.logSystemEvent(LogTypes.downloadImageDelta, { image });
const deltaOpts = (opts as unknown) as DeltaFetchOptions;
const srcImage = await inspectByName(deltaOpts.deltaSource);
deltaOpts.deltaSourceId = srcImage.Id;
const id = await dockerUtils.fetchDeltaWithProgress(
image.name,
deltaOpts,
onProgress,
serviceName,
);
return id;
}
function fetchImage(
image: Image,
opts: FetchOptions,
onProgress: (evt: FetchProgressEvent) => void,
): Promise<string> {
logger.logSystemEvent(LogTypes.downloadImage, { image });
return dockerUtils.fetchImageWithProgress(image.name, opts, onProgress);
} | the_stack |
import * as THREE from 'three';
import { times } from 'lodash';
import { WORLD_SIZE, normalizeAngle } from '../../../../utils/lba';
import { IslandSection } from '../IslandLayout';
import Scene from '../../../Scene';
import Actor, { SlideWay } from '../../../Actor';
import Extra from '../../../Extra';
import { scanGrid, intersect2DLines, pointInTriangle2D, interpolateY } from './math';
import HeightMapCell, { HeightMapTriangle } from './HeightMapCell';
import GroundInfo from './GroundInfo';
import { AnimType } from '../../../data/animType';
import { Time } from '../../../../datatypes';
const MAX_ITERATIONS = 4;
enum SlidingStatus {
SLIDING,
STUCK,
NONE
}
export default class HeightMap {
private sections: IslandSection[] = [];
/** Line segment from actor starting position to target position (for this frame) */
private line = new THREE.Line3();
private triangle_side = new THREE.Line3();
private cell = new HeightMapCell();
/** List of intersection points in the current cell */
private intersect_points = times(6).map(() => new THREE.Vector3());
/** List of projected target points in the current cell */
private projection_points = times(6).map(() => new THREE.Vector3());
private vec_tmp = new THREE.Vector3();
private proj_offset = new THREE.Vector3();
constructor(sections: IslandSection[]) {
this.sections = sections;
}
/**
* The goal of this function is to test if the actor
* intersects with any of the "solid" triangles of the
* heightmap (such as rocks).
* It translates the target position (actor.physics.position)
* so as to maintain smooth movements.
* @returns Whether we're touching ground or not.
*/
processCollisions(
scene: Scene,
obj: Actor | Extra,
isTouchingGround: boolean,
time: Time
): boolean {
if (obj instanceof Actor
&& obj.state.isJumping
&& obj.physics.temp.position.y >= 0
&& obj.threeObject.position.y - obj.state.jumpStartHeight < 0.8) {
return isTouchingGround;
}
sceneSpaceToGridSpace(scene, obj.threeObject.position, this.line.start);
sceneSpaceToGridSpace(scene, obj.physics.position, this.line.end);
let done = false;
let iteration = 0;
let isSliding = false;
let isStuck = false;
while (!done && iteration < MAX_ITERATIONS) {
done = true;
scanGrid(this.line, (x, z) => {
this.cell.setFrom(this.sections, x, z);
if (!this.cell.valid) {
return true;
}
let idx = 0;
for (const tri of this.cell.triangles) {
if (tri.collision) {
const { points } = tri;
let intersect = false;
if (!(obj instanceof Actor && obj.state.isSliding)) {
for (let i = 0; i < 3; i += 1) {
const pt0 = i;
const pt1 = (i + 1) % 3;
this.triangle_side.set(points[pt0], points[pt1]);
const t = intersect2DLines(this.line, this.triangle_side);
if (t !== -1) {
// Found some intersection.
// Push the intersection point and projected point
// (closest point to the target on the interesected edge).
this.intersect_points[idx].copy(this.line.start);
this.vec_tmp.copy(this.line.end);
this.vec_tmp.sub(this.line.start);
this.vec_tmp.multiplyScalar(t);
this.intersect_points[idx].add(this.vec_tmp);
this.triangle_side.closestPointToPoint(
this.line.end,
true,
this.projection_points[idx]
);
idx += 1;
intersect = true;
}
}
}
if (!intersect) {
if (obj instanceof Actor
&& pointInTriangle2D(points, this.line.start)) {
// If we have no intersection and the start of the
// directional vector is within a solid triangle,
// we should be sliding down the slope.
switch (this.processSliding(scene, tri, obj, time)) {
case SlidingStatus.SLIDING:
isSliding = true;
break;
case SlidingStatus.STUCK:
isStuck = true;
break;
}
return true;
}
}
}
}
// Find the closest intersection
let closestIdx = -1;
let dist = Infinity;
for (let i = 0; i < idx; i += 1) {
const nDist = this.intersect_points[i].distanceToSquared(this.line.start);
if (nDist < dist) {
closestIdx = i;
dist = nDist;
}
}
if (closestIdx !== -1) {
// Apply a little offset to the projected point
// to push it out of the intersected triangle's edge.
this.proj_offset.copy(this.projection_points[closestIdx]);
this.proj_offset.sub(this.line.end);
this.proj_offset.normalize();
this.proj_offset.multiplyScalar(0.01);
this.line.end.copy(this.projection_points[closestIdx]);
this.line.end.add(this.proj_offset);
gridSpaceToSceneSpace(scene, this.line.end, obj.physics.position);
this.cell.setFromPos(this.sections, this.line.end);
for (const tri of this.cell.triangles) {
if (tri.collision && pointInTriangle2D(tri.points, this.line.end)) {
// If the new target position is within another solid triangle
// we should keep iterating until we're out.
// (otherwise we would jump into the solid triangles in the corners)
done = false;
}
}
isTouchingGround = true;
return true;
}
return false;
});
iteration += 1;
}
if (obj instanceof Actor) {
obj.state.isSliding = isSliding;
obj.state.isStuck = isStuck;
if (isSliding || isStuck) {
obj.state.isJumping = false;
obj.state.hasGravityByAnim = false;
}
}
return isTouchingGround;
}
getGroundInfo(position: THREE.Vector3, result: GroundInfo) {
this.vec_tmp.set(position.x * GRID_SCALE, position.y, position.z * GRID_SCALE);
this.getGroundInfoInGridSpace(this.vec_tmp, result);
}
private getGroundInfoInGridSpace(position: THREE.Vector3, result: GroundInfo) {
this.cell.setFromPos(this.sections, position);
if (this.cell.valid) {
for (const tri of this.cell.triangles) {
if (pointInTriangle2D(tri.points, position)) {
result.valid = true;
result.collision = tri.collision;
result.sound = tri.sound;
result.liquid = tri.liquid;
result.height = interpolateY(tri.points, position);
result.section = this.cell.section;
for (let i = 0; i < 3; i += 1) {
const pt = tri.points[i];
result.points[i].set(
pt.x * INV_GRID_SCALE,
pt.y,
pt.z * INV_GRID_SCALE
);
}
return;
}
}
}
result.setDefault();
}
private lowSlideIdx = [-1, -1, -1];
private highSlideIdx = [-1, -1, -1];
private slideSrc = new THREE.Vector3();
private slideTgt = new THREE.Vector3();
private groundTmp = new GroundInfo();
private processSliding(
scene: Scene,
tri: HeightMapTriangle,
actor: Actor,
time: Time
): SlidingStatus {
if (actor.state.isStuck) {
return SlidingStatus.STUCK;
}
const { points } = tri;
// Find the triangle's slope by finding the set of
// lowest points. If all 3 points are the same height,
// it means the triangle is flat.
let lowCount = 0;
let highCount = 0;
let lowest = Infinity;
let highest = -Infinity;
for (let i = 0; i < 3; i += 1) {
const pt = points[i];
if (pt.y < lowest) {
this.lowSlideIdx[0] = i;
lowCount = 1;
lowest = pt.y;
} else if (pt.y === lowest) {
this.lowSlideIdx[lowCount] = i;
lowCount += 1;
}
if (pt.y > highest) {
this.highSlideIdx[0] = i;
highCount = 1;
highest = pt.y;
} else if (pt.y === highest) {
this.highSlideIdx[highCount] = i;
highCount += 1;
}
}
// Triangle has a slope, let's slide down
// in that slope's direction.
if (lowCount < 3 && !actor.state.isStuck) {
if (!actor.state.isSliding) {
actor.slideState.startTime = time.elapsed,
actor.slideState.startPos.copy(this.line.start);
} else if (time.elapsed - actor.slideState.startTime > 0.5) {
if (this.line.start.distanceToSquared(actor.slideState.startPos) < 1) {
// Get stuck if we didn't travel enough in half a second
actor.physics.position.copy(actor.threeObject.position);
return SlidingStatus.STUCK;
}
actor.slideState.startTime = time.elapsed;
actor.slideState.startPos.copy(this.line.start);
}
// Slide origin is the average of the high
// points of the triangle.
this.slideSrc.set(0, 0, 0);
for (let i = 0; i < highCount; i += 1) {
this.slideSrc.add(points[this.highSlideIdx[i]]);
}
this.slideSrc.divideScalar(highCount);
// Slide target is the average of the low
// points of the triangle.
this.slideTgt.set(0, 0, 0);
for (let i = 0; i < lowCount; i += 1) {
this.slideTgt.add(points[this.lowSlideIdx[i]]);
}
this.slideTgt.divideScalar(lowCount);
// Compute normalized vector from high to low point
this.proj_offset.copy(this.slideTgt);
this.proj_offset.sub(this.slideSrc);
this.proj_offset.normalize();
actor.slideState.direction.copy(this.proj_offset);
this.proj_offset.multiplyScalar(time.delta * 4);
if (!actor.state.isSliding) {
this.vec_tmp.copy(this.line.end);
this.vec_tmp.sub(this.line.start);
const way = this.vec_tmp.dot(this.proj_offset) > 0
? SlideWay.FORWARD
: SlideWay.BACKWARD;
actor.slideState.way = way;
actor.setAnim(way === SlideWay.FORWARD
? AnimType.SLIDE_FORWARD
: AnimType.SLIDE_BACKWARD);
}
this.applyTargetPos(scene, actor, this.proj_offset, time);
return SlidingStatus.SLIDING;
}
// Triangle is flat, we were sliding in the previous frame,
// let's keep sliding in the same direction.
if (actor.state.isSliding && !actor.state.isStuck) {
this.proj_offset.copy(actor.slideState.direction);
this.proj_offset.normalize();
this.proj_offset.multiplyScalar(time.delta * 4);
this.applyTargetPos(scene, actor, this.proj_offset, time);
return SlidingStatus.SLIDING;
}
// Triangle is flat and we weren't sliding. Stop where we are.
if (!actor.state.isJumping) {
actor.physics.position.copy(actor.threeObject.position);
return SlidingStatus.STUCK;
}
return SlidingStatus.NONE;
}
private euler = new THREE.Euler();
private tgtQuat = new THREE.Quaternion();
private applyTargetPos(scene: Scene, actor: Actor, tgt: THREE.Vector3, time: Time) {
this.line.end.copy(this.line.start);
this.line.end.add(tgt);
let angle = Math.atan2(tgt.x, tgt.z);
if (actor.slideState.way === SlideWay.BACKWARD) {
angle = normalizeAngle(angle + Math.PI);
}
this.euler.set(0, angle, 0, 'YXZ');
this.tgtQuat.setFromEuler(this.euler);
actor.physics.orientation.slerp(this.tgtQuat, time.delta * 4);
this.euler.setFromQuaternion(actor.physics.orientation, 'YXZ');
actor.physics.temp.angle = this.euler.y;
this.getGroundInfoInGridSpace(this.line.end, this.groundTmp);
this.line.end.y = this.groundTmp.height;
gridSpaceToSceneSpace(
scene,
this.line.end,
actor.physics.position
);
}
}
const GRID_SCALE = 32 / WORLD_SIZE;
const INV_GRID_SCALE = WORLD_SIZE / 32;
/**
* Turns an input vector in local scene space
* into an output vector in heightmap grid space
* @param src Input vector in scene space
* @param tgt Output vector in heightmap grid space
*/
function sceneSpaceToGridSpace(
scene: Scene,
src: THREE.Vector3,
tgt: THREE.Vector3
) {
tgt.copy(src);
tgt.add(scene.sceneNode.position);
tgt.set(tgt.x * GRID_SCALE, src.y, tgt.z * GRID_SCALE);
}
/**
* Turns an input vector in heightmap grid space
* into an output vector in local scene space.
* @param src Input vector in heightmap grid space
* @param tgt Output vector in scene space
*/
function gridSpaceToSceneSpace(
scene: Scene,
src: THREE.Vector3,
tgt: THREE.Vector3
) {
tgt.set(src.x * INV_GRID_SCALE, src.y, src.z * INV_GRID_SCALE);
tgt.sub(scene.sceneNode.position);
} | the_stack |
import type { IndexedCollection } from "./utility-types.ts";
export type Comparator<T> = (a: T, b: T) => -1 | 0 | 1;
/**
* Extends Array to handle sorted data.
*/
export class SortedArray<ItemType> extends Array<ItemType> {
unique = false;
/**
* The default comparator.
*
* @param a the first value
* @param b the second value
* @throws RangeError if the comparison is unstable
*/
static compare<T>(a: T, b: T): -1 | 0 | 1 {
if (a > b) return 1;
if (a < b) return -1;
if (a === b) return 0;
throw new RangeError("Unstable comparison.");
}
/**
* Creates a new SortedArray from a given array-like object.
*/
static from<T>(iterable: Iterable<T> | ArrayLike<T>): SortedArray<T>;
static from<T, U>(
iterable: Iterable<T> | ArrayLike<T>,
mapfn?: (v: T, k: number) => U,
thisArg?: unknown,
): SortedArray<U> {
const result =
(mapfn !== undefined
? super.from(iterable, mapfn, thisArg)
: super.from(iterable)) as SortedArray<U>;
result.sort();
return result;
}
/**
* Returns the difference of two sorted arrays,
* i.e. elements present in the first array but not in the second array.
* If `symmetric=true` finds the symmetric difference of two arrays, that is,
* the elements that are absent in one or another array.
*
* @param a the first array
* @param b the second array
* @param [symmetric=false] whether to get symmetric difference.
* @param [comparator] the comparator static used to sort the arrays
* @param [container] an array-like object to hold the results
* @return the difference of the arrays
* @example
*
* SortedArray.getDifference([1, 2, 3, 4, 8], [2, 4, 6, 7, 9]);
* //=> [ 1, 3, 8 ]
*
* // symmetric difference of sorted arrays:
* SortedArray.getDifference(first, second, true);
* //=> [ 1, 3, 6, 7, 8, 9 ]
* // difference using a custom comparator:
* const customComparator = (a, b) => (a > b ? -1 : a < b ? 1 : 0);
* SortedArray.getDifference([8, 4, 3, 2, 1], [9, 7, 6, 4, 2], false, customComparator);
* //=> [ 8, 3, 1 ]
*/
static getDifference<T, U extends IndexedCollection<T>>(
a: U,
b: U,
symmetric = false,
comparator: Comparator<T> = this.compare,
container: U = ([] as unknown) as U,
): typeof container {
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const compared = comparator(a[i], b[j]);
if (compared > 0) {
if (symmetric) container[container.length] = b[j];
j++;
} else if (compared < 0) {
container[container.length] = a[i];
i++;
} else {
i++;
j++;
}
}
while (i < a.length) {
container[container.length] = a[i];
i++;
}
if (symmetric) {
while (j < b.length) {
container[container.length] = b[j];
j++;
}
}
return container;
}
/**
* Returns the amount of differing elements in the first array.
*
* @param a the first array
* @param b the second array
* @param [symmetric=false] whether to use symmetric difference
* @param [comparator] the comparator static used to sort the arrays
* @return the amount of differing elements
* @example
*
* SortedArray.getDifferenceScore([1, 2, 3, 4, 8], [2, 4, 6, 7, 9]);
* //=> 3
*/
static getDifferenceScore<T, U extends IndexedCollection<T>>(
a: U,
b: U,
symmetric = false,
comparator = this.compare,
): number {
const score = this.getIntersectionScore(a, b, comparator);
return symmetric ? a.length + b.length - 2 * score : a.length - score;
}
/**
* Uses binary search to find the index of an element inside a sorted array.
*
* @param arr the array to search
* @param target the target value to search for
* @param [comparator] a custom comparator
* @param [rank=false] whether to return the element's rank if the element isn't found
* @param [start] the start position of the search
* @param [end] the end position of the search
* @return the index of the searched element or it's rank
* @example
*
* SortedArray.getIndex([1, 2, 3, 4, 8], 4);
* //=> 3
*/
static getIndex<T, U extends IndexedCollection<T>>(
arr: U,
target: T,
comparator: Comparator<T> = this.compare,
rank = false,
start = 0,
end = arr.length - 1,
): number {
let left = start;
let right = end;
let m;
while (left <= right) {
m = (left + right) >> 1;
const compared = comparator(arr[m], target);
if (compared < 0) {
left = m + 1;
} else if (compared > 0) {
right = m - 1;
} else {
return m;
}
}
return rank ? left : -1;
}
/**
* Returns the intersection of two sorted arrays.
*
* @param a the first array
* @param b the second array
* @param [comparator] the comparator static used to sort the arrays
* @param [container] an array-like object to hold the results
* @return the intersection of the arrays
* @example
*
* SortedArray.getIntersection([1, 2, 3, 4, 8], [2, 4, 6, 7, 9]);
* //=> [ 2, 4 ]
*
* // intersection using a custom comparator:
* const customComparator = (a, b) => (a > b ? -1 : a < b ? 1 : 0);
* SortedArray.getIntersection([8, 4, 3, 2, 1], [9, 7, 6, 4, 2], customComparator);
* //=> [ 4, 2 ]
*/
static getIntersection<T, U extends IndexedCollection<T>>(
a: U,
b: U,
comparator: Comparator<T> = this.compare,
container: U = ([] as unknown) as U,
): U {
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const compared = comparator(a[i], b[j]);
if (compared > 0) {
j++;
} else if (compared < 0) {
i++;
} else {
container[container.length] = a[i];
i++;
j++;
}
}
return container;
}
/**
* Returns the amount of common elements in two sorted arrays.
*
* @param a the first array
* @param b the second array
* @param [comparator] the comparator static used to sort the arrays
* @return the amount of different elements
* @example
*
* SortedArray.getIntersection([1, 2, 3, 4, 8], [2, 4, 6, 7, 9]);
* //=> 2
*/
static getIntersectionScore<T, U extends IndexedCollection<T>>(
a: U,
b: U,
comparator: Comparator<T> = this.compare,
): number {
let score = 0;
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const compared = comparator(a[i], b[j]);
if (compared > 0) {
j++;
} else if (compared < 0) {
i++;
} else {
score++;
i++;
j++;
}
}
return score;
}
/**
* Returns a range of elements of a sorted array from the start through the end inclusively.
*
* @param arr the array
* @param [start] the starting item
* @param [end] the ending item
* @param [comparator] a custom comparator
* @param [subarray] return a subarray instead of copying resulting value with slice
* @return the range of items
* @example
*
* SortedArray.getRange([1, 2, 3, 4, 8], 2, 4);
* //=> [ 2, 3, 4 ]
*
* const customComparator = (a, b) => (a > b ? -1 : a < b ? 1 : 0);
* SortedArray.getRange([8, 4, 3, 2, 1], 8, 3, customComparator);
* //=> [ 8, 4, 3 ]
*/
static getRange<T, U extends IndexedCollection<T>>(
arr: U,
start?: T,
end?: T,
comparator?: Comparator<T>,
subarray?: boolean,
): U {
const startIndex = start === undefined
? 0
: this.getIndex<T, U>(arr, start, comparator, true);
const endIndex = end === undefined
? arr.length
: this.getIndex(arr, end, comparator, true, startIndex) + 1;
return subarray
? (arr as unknown as Int32Array).subarray(startIndex, endIndex)
: // deno-lint-ignore no-explicit-any
(arr as any).slice(startIndex, endIndex);
}
/**
* Returns the union of two sorted arrays as a sorted array.
*
* @param a the first array
* @param b the second array
* @param [unique=false] whether to avoid duplicating items when merging unique arrays
* @param [comparator] the comparator static used to sort the arrays
* @param [container] an array-like object to hold the results
* @return the union of the arrays
* @example
*
* SortedArray.getUnion([1, 2, 3, 4, 8], [2, 4, 6, 7, 9]);
* //=> [ 1, 2, 2, 3, 4, 4, 6, 7, 8, 9 ]
*
* // union of sorted arrays without duplicates:
* SortedArray.getUnion([1, 2, 3, 4, 8], [2, 4, 6, 7, 9], true);
* //=> [ 1, 2, 3, 4, 6, 7, 8, 9 ]
*
* //union using a custom comparator:
* SortedArray.getUnion([8, 4, 3, 2, 1], [9, 7, 6, 4, 2], true, customComparator);
* //=> [ 9, 8, 7, 6, 4, 3, 2, 1 ]
*/
static getUnion<T, U extends IndexedCollection<T>>(
a: IndexedCollection<T>,
b: IndexedCollection<T>,
unique = false,
comparator: Comparator<T> = this.compare,
container: U = ([] as unknown) as U,
): U {
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const compared = comparator(a[i], b[j]);
if (compared > 0) {
container[container.length] = b[j];
j++;
} else if (compared < 0) {
container[container.length] = a[i];
i++;
} else {
container[container.length] = a[i];
if (!unique) container[container.length] = b[j];
i++;
j++;
}
}
while (i < a.length) {
container[container.length] = a[i];
i++;
}
while (j < b.length) {
container[container.length] = b[j];
j++;
}
return container;
}
/**
* Returns an array of unique elements from a sorted array.
*
* @param arr the sorted array
* @param [comparator] a custom comparator
* @param [container] an array-like object to hold the results
* @return the sorted array without duplicates
* @example
*
* SortedArray.getUnique([1, 1, 2, 2, 3, 4]);
* //=> [ 1, 2, 3, 4 ]
*/
static getUnique<T, U extends IndexedCollection<T>>(
arr: IndexedCollection<T>,
comparator: Comparator<T> = this.compare,
container: U = ([] as unknown) as U,
): typeof container {
container[0] = arr[0];
for (let i = 1; i < arr.length; i++) {
if (comparator(arr[i - 1], arr[i]) !== 0) {
container[container.length] = arr[i];
}
}
return container;
}
/**
* Checks whether an array is sorted according to a provided comparator.
*
* @param arr the array to check
* @param [comparator] a custom comparator
* @return whether the array is sorted
*
* @example
*
* SortedArray.isSorted([1, 2, 3, 4, 8]);
* //=> true
*/
static isSorted<T, U extends IndexedCollection<T>>(
arr: U,
comparator: Comparator<T> = this.compare,
): boolean {
for (let i = 1; i < arr.length; i++) {
if (comparator(arr[i - 1], arr[i]) > 0) return false;
}
return true;
}
/**
* Checks whether an array has any duplicating elements.
*
* @param arr the array to check
* @param [comparator] a custom comparator
* @return whether the array has duplicating elements
* @example
*
* SortedArray.isUnique([1, 2, 2, 3, 4]);
* //=> false
*/
static isUnique<T, U extends IndexedCollection<T>>(
arr: U,
comparator: Comparator<T> = this.compare,
) {
for (let i = 1; i < arr.length; i++) {
if (comparator(arr[i - 1], arr[i]) === 0) return false;
}
return true;
}
/**
* Creates a new SortedArray instance with a variable number of arguments,
* regardless of number or type of the arguments
*
* @param elements the elements of which to create the array
* @return the new SortedArray
*/
static of<U>(...elements: Array<U>): SortedArray<U> {
const result = (super.of(...elements) as unknown) as SortedArray<U>;
result.sort();
return result;
}
/**
* Returns a merger of the array with one or more provided sorted arrays.
*
* @param arrays sorted array(s) to merge
* @return a new SortedArray
*/
concat(...arrays: Array<Array<ItemType>>): SortedArray<ItemType> {
const constructor = this.constructor as typeof SortedArray;
let result = this.slice(0) as SortedArray<ItemType>;
// TODO rewrite
for (let i = 0; i < arrays.length; i++) {
result = constructor.getUnion(
result,
arrays[i],
this.unique,
constructor.compare,
new constructor<ItemType>() as this,
);
}
return result;
}
/**
* Uses binary search to quickly check if the element is the array.
* @param element the element to check
* @return whether the element is in the array
*/
includes(element: ItemType): boolean {
return !!~this.indexOf(element);
}
/**
* Looks for the index of a given element in the array or -1
*
* @param element the element to look for
* @return the element's index in the array or -1
*/
indexOf(element: ItemType): number {
return (this.constructor as typeof SortedArray).getIndex(this, element);
}
/**
* Checks if the array is sorted.
*
* @return whether the array is sorted
* @example
*
* //=> SortedArray [ 2, 3, 4, 5, 9 ];
* SortedArray.isSorted();
* //=> true
* SortedArray.reverse();
* SortedArray.isSorted();
* //=> false;
*/
isSorted(): boolean {
return (this.constructor as typeof SortedArray).isSorted(this);
}
/**
* Checks if the array has duplicating elements.
*
* @return whether the array has duplicating elements
* @example
*
* //=> SortedArray [ 2, 3, 3, 4, 5, 9 ];
* SortedArray.isUnique();
* //=> false;
*/
isUnique(): boolean {
return (this.constructor as typeof SortedArray).isUnique(this);
}
/**
* Adds provided elements to the array preserving the sorted order of the array.
*
* @param elements the elements to add to the array
* @return the new length of the array
*/
push(...elements: Array<ItemType>): number {
const { compare } = this.constructor as typeof SortedArray;
const m = this.length;
if (!m) return super.push(...elements.sort(compare));
const toAdd = this.unique
? elements.filter((el) => !~this.indexOf(el))
: elements;
const n = toAdd.length;
if (!n) return m;
toAdd.sort(compare);
for (let i = n - 1; i >= 0; i--) {
let j;
const last = this[m - 1];
for (j = m - 2; j >= 0 && compare(this[j], toAdd[i]) === 1; j--) {
this[j + 1] = this[j];
}
if (j !== m - 2 || compare(last, toAdd[i]) === 1) {
this[j + 1] = toAdd[i];
toAdd[i] = last;
}
}
return super.push(...toAdd);
}
/**
* Returns a range of elements of the array that are greater or equal to the provided
* starting element and less or equal to the provided ending element.
*
* @param start the starting element
* @param end the ending element
* @return the resulting range of elements
* @example
*
* //=> SortedArray [ 2, 3, 4, 5, 9 ];
* SortedArray.range(3, 5);
* // => [ 3, 4, 5 ]
* SortedArray.range(undefined, 4);
* // => [ 2, 3, 4 ]
* SortedArray.range(4);
* // => [ 4, 5, 8 ]
*/
range(start?: ItemType, end?: ItemType): SortedArray<ItemType> {
const constructor = this.constructor as typeof SortedArray;
return constructor.getRange(this, start, end, constructor.compare, false);
}
/**
* Returns the rank of an element in the array.
*
* @param element the element to look for
* @return the rank in the array
* @example
*
* //=> SortedArray [ 2, 3, 4, 5, 9 ];
* SortedArray.rank(1);
* // => 0
* SortedArray.rank(6);
* // => 4
*/
rank(element: ItemType): number {
const constructor = this.constructor as typeof SortedArray;
return constructor.getIndex(this, element, constructor.compare, true);
}
/**
* Implements in-place replacement of the array elements.
*
* @param arr an array of new elements to use
*
* @example
*
* //=> SortedArray [ 2, 3, 4, 5, 9 ];
* sortedArray.set([1, 2, 3]);
* //=> SortedArray [ 1, 2, 3 ]
*/
set(arr: Array<ItemType>): this {
this.length = arr.length;
for (let i = 0; i < arr.length; i++) {
this[i] = arr[i];
}
return this;
}
/**
* Sorts the array with a provided compare function.
*
* @param compareFunction the function to use for comparison
*/
sort(
compareFunction: Comparator<ItemType> = (this
.constructor as typeof SortedArray).compare,
): this {
return super.sort(compareFunction);
}
/**
* Changes the array by removing existing elements and adding new ones.
*
* @param start the index at which to start changing the array
* @param deleteCount the amount of old elements to delete
* @param elements the elements to add to the array
* @return an array of deleted elements
*/
splice(
start: number,
deleteCount: number,
...elements: Array<ItemType>
): SortedArray<ItemType> {
const deletedElements = super.splice(
start,
deleteCount,
) as SortedArray<ItemType>;
this.push(...elements);
return deletedElements;
}
/**
* Removes duplicating elements from the array.
*
* @example
*
* //=> SortedArray [ 2, 2, 3, 4, 5, 5, 9 ];
* sortedArray.uniquify();
* // => SortedArray [ 2, 3, 4, 5, 9 ]
*/
uniquify() {
const constructor = this.constructor as typeof SortedArray;
return this.set(
constructor.getUnique(this, constructor.compare, new constructor()),
);
}
/**
* Adds provided elements to the array preserving the sorted order of the array.
*
* @param elements the elements to add to the array
* @return the new length of the array
*/
unshift(...elements: Array<ItemType>) {
return this.push(...elements);
}
} | the_stack |
import { RefreshMode, IExternalBaseLayer, Bounds, LayerTransparencySet, LayerProperty, MgBuiltInLayers, MgLayerType, MG_LAYER_TYPE_NAME, MG_BASE_LAYER_GROUP_NAME, ImageFormat, GenericEvent, ClientKind, Coordinate2D, Size, BLANK_SIZE, Dictionary, UnitOfMeasure } from './common';
import LayerGroup from "ol/layer/Group";
import TileGrid from "ol/tilegrid/TileGrid";
import AbstractSource from "ol/source/Source";
import TileImageSource from "ol/source/TileImage";
import { createMapGuideSource } from "./ol-mapguide-source-factory";
import ImageStaticSource from "ol/source/ImageStatic";
import { restrictToRange } from "../utils/number";
import View from "ol/View";
import * as olExtent from "ol/extent";
import TileLayer from "ol/layer/Tile";
import ImageLayer from "ol/layer/Image";
import LayerBase from "ol/layer/Base";
import { RuntimeMap } from './contracts/runtime-map';
import { createExternalSource, createOLLayerFromSubjectDefn } from '../components/external-layer-factory';
import { strIsNullOrEmpty } from '../utils/string';
import { parseUrl } from '../utils/url';
import ImageWrapper from 'ol/Image';
import { DEFAULT_LOCALE, tr } from './i18n';
import * as olHas from "ol/has";
import Feature from "ol/Feature";
import { debug } from '../utils/logger';
import { Client } from './client';
import { ILayerSetOL, IImageLayerEvents } from './layer-set-contracts';
import Geometry from 'ol/geom/Geometry';
import UrlTile from 'ol/source/UrlTile';
import { LoadFunction as TileLoadFunction } from 'ol/Tile';
import { MapGuideMockMode } from '../components/mapguide-debug-context';
import { BLANK_GIF_DATA_URI, LAYER_ID_BASE, LAYER_ID_MG_BASE, LAYER_ID_MG_SEL_OVERLAY } from '../constants';
import { OLImageLayer, OLTileLayer } from './ol-types';
import { IGenericSubjectMapLayer } from '../actions/defs';
import { GenericLayerSetOL } from './generic-layer-set';
import { get, METERS_PER_UNIT, Projection, ProjectionLike } from "ol/proj";
import { isRuntimeMap } from '../utils/type-guards';
import { MgError } from './error';
import { tryParseArbitraryCs } from '../utils/units';
const DEFAULT_BOUNDS_3857: Bounds = [
-20026376.39,
-20048966.10,
20026376.39,
20048966.10
];
const DEFAULT_BOUNDS_4326: Bounds = [-180, -90, 180, 90];
function getMetersPerUnit(projection: string) {
const proj = get(projection);
return proj.getMetersPerUnit();
}
function toMetersPerUnit(unit: UnitOfMeasure) {
const u = toProjUnit(unit);
// Use OL-provided mpu if available
let mpu = METERS_PER_UNIT[u];
if (mpu) {
return mpu;
} else {
// Otherwise, compute ourselves
switch (unit) {
case UnitOfMeasure.Centimeters:
return 0.01;
case UnitOfMeasure.DMS:
case UnitOfMeasure.DecimalDegrees:
case UnitOfMeasure.Degrees:
return (2 * Math.PI * 6370997) / 360;
case UnitOfMeasure.Feet:
return 0.3048;
case UnitOfMeasure.Inches:
return 0.0254;
case UnitOfMeasure.Kilometers:
return 1000;
case UnitOfMeasure.Meters:
return 1;
case UnitOfMeasure.Miles:
return 1609.344;
case UnitOfMeasure.Millimeters:
return 0.001;
case UnitOfMeasure.NauticalMiles:
return 1852;
case UnitOfMeasure.Pixels:
return 1;
case UnitOfMeasure.Unknown:
return 1;
case UnitOfMeasure.Yards:
return 0.9144;
}
}
}
export function toProjUnit(unit: UnitOfMeasure) {
switch (unit) {
case UnitOfMeasure.Meters:
return "m";
case UnitOfMeasure.Feet:
return "ft";
case UnitOfMeasure.Inches:
return "in";
case UnitOfMeasure.Centimeters:
return "cm";
case UnitOfMeasure.Kilometers:
return "km";
case UnitOfMeasure.Yards:
return "yd";
case UnitOfMeasure.Millimeters:
return "mm";
case UnitOfMeasure.Miles:
return "mi";
case UnitOfMeasure.NauticalMiles:
return "nm";
case UnitOfMeasure.Pixels:
return "px";
}
}
export function blankImageLoadFunction(image: ImageWrapper) {
(image.getImage() as any).src = BLANK_GIF_DATA_URI;
}
export function mockMapGuideImageLoadFunction(image: ImageWrapper, src: string) {
let el = document.getElementById("mg-debug-text-canvas");
if (!el) {
el = document.createElement("canvas");
el.style.visibility = "hidden";
el.id = "mg-debug-text-canvas";
document.body.append(el);
}
const tCtx = (el as HTMLCanvasElement).getContext("2d");
if (tCtx) {
tCtx.clearRect(0, 0, tCtx.canvas.width, tCtx.canvas.height);
const strings = [];
const parsed = parseUrl(src);
strings.push("[Mock MapGuide Map Image Request]");
strings.push(`Agent: ${parsed.url}`);
const xoff = 10;
const yoff = 30;
const fontSize = 14;
let mm = tCtx.measureText(strings[0])
let maxSize = mm.width + xoff;
let ch = yoff + fontSize + 2;
maxSize = Math.max(tCtx.measureText(strings[1]).width + xoff, maxSize);
ch += (fontSize + 2);
const keys = Object.keys(parsed.query);
for (const k of keys) {
if (k == "MAPNAME" || k == "SETDISPLAYWIDTH" || k == "SETDISPLAYHEIGHT" || k == "SETVIEWCENTERX" || k == "SETVIEWCENTERY" || k == "SETVIEWSCALE") {
if (!strIsNullOrEmpty(parsed.query[k])) {
const s = `${k}: ${parsed.query[k]}`;
strings.push(s);
maxSize = Math.max(tCtx.measureText(s).width + xoff, maxSize);
ch += (fontSize + 2);
}
}
}
tCtx.canvas.width = maxSize;
tCtx.canvas.height = ch;
tCtx.fillStyle = "rgba(255, 0, 0, 0.5)";
tCtx.fillRect(0, 0, maxSize, ch);
tCtx.fillStyle = "rgba(255, 255, 0, 1.0)";
//console.log(`Canvas size: [${tCtx.canvas.width}, ${tCtx.canvas.height}]`);
tCtx.font = `${fontSize}px sans-serif`;
let y = yoff;
for (const str of strings) {
//console.log(`Draw (${str}) at [10, ${y}]`);
tCtx.fillText(str, 10, y);
y += (fontSize + 1);
}
(image.getImage() as any).src = tCtx.canvas.toDataURL();
}
}
export enum MgLayerSetMode {
Stateless,
Stateful,
OverviewMap
}
/**
* @hidden
*/
export class MgLayerSetOL implements ILayerSetOL {
constructor(public readonly mgTiledLayers: OLTileLayer[],
public readonly externalBaseLayersGroup: LayerGroup | undefined,
public readonly overlay: OLImageLayer,
public readonly projection: ProjectionLike,
public readonly dpi: number,
public readonly extent: Bounds,
private readonly inPerUnit: number,
public readonly view: View) { }
public selectionOverlay: OLImageLayer | undefined;
public activeSelectedFeatureOverlay: OLImageLayer | undefined;
public getMetersPerUnit(): number {
return this.inPerUnit / 39.37
}
public scaleToResolution(scale: number): number {
return (scale / this.inPerUnit / this.dpi) * olHas.DEVICE_PIXEL_RATIO;
}
public resolutionToScale(resolution: number): number {
return (resolution * this.dpi * this.inPerUnit) / olHas.DEVICE_PIXEL_RATIO;
}
public getSourcesForProgressTracking(): AbstractSource[] {
const sources: AbstractSource[] = [];
if (this.externalBaseLayersGroup) {
const bls = this.externalBaseLayersGroup.getLayersArray();
for (const bl of bls) {
if (bl instanceof ImageLayer || bl instanceof TileLayer) {
sources.push(bl.getSource());
}
}
}
for (let i = this.mgTiledLayers.length - 1; i >= 0; i--) {
sources.push(this.mgTiledLayers[i].getSource());
}
sources.push(this.overlay.getSource());
if (this.selectionOverlay) {
sources.push(this.selectionOverlay.getSource());
}
if (this.activeSelectedFeatureOverlay) {
sources.push(this.activeSelectedFeatureOverlay.getSource());
}
return sources;
}
public getLayers(): LayerBase[] {
const layers: LayerBase[] = [];
if (this.externalBaseLayersGroup) {
layers.push(this.externalBaseLayersGroup);
}
for (let i = this.mgTiledLayers.length - 1; i >= 0; i--) {
layers.push(this.mgTiledLayers[i]);
}
layers.push(this.overlay);
if (this.selectionOverlay) {
layers.push(this.selectionOverlay);
}
if (this.activeSelectedFeatureOverlay) {
layers.push(this.activeSelectedFeatureOverlay);
}
return layers;
}
public update(showGroups: string[] | undefined, showLayers: string[] | undefined, hideGroups: string[] | undefined, hideLayers: string[] | undefined) {
//Send the request
const imgSource = this.overlay.getSource() as any; //olMapGuideSource;
//NOTE: Even if these group ids being shown/hidden are MG base layer groups, it still has to be
//done as the server-side snapshot of the runtime map needs to be aware as well. This will be
//apparent if you were to plot a runtime-map server-side that has base layer groups.
imgSource.updateParams({
showlayers: showLayers,
showgroups: showGroups,
hidelayers: hideLayers,
hidegroups: hideGroups
});
//As MG base layer groups are separate ol layer instances, we have to toggle them on the client-side as well
if (showGroups && showGroups.length > 0) {
for (const groupId of showGroups) {
const match = this.mgTiledLayers.filter(l => l.get(LayerProperty.LAYER_NAME) === groupId);
if (match.length == 1) {
match[0].setVisible(true);
}
}
}
if (hideGroups && hideGroups.length > 0) {
for (const groupId of hideGroups) {
const match = this.mgTiledLayers.filter(l => l.get(LayerProperty.LAYER_NAME) === groupId);
if (match.length == 1) {
match[0].setVisible(false);
}
}
}
}
public updateSelectionColor(color: string) {
if (this.selectionOverlay) {
const source = this.selectionOverlay.getSource() as any; // olMapGuideSource;
source.updateParams({
SELECTIONCOLOR: color
});
}
}
public updateExternalBaseLayers(externalBaseLayers: IExternalBaseLayer[]) {
if (this.externalBaseLayersGroup) {
const layers = this.externalBaseLayersGroup.getLayers();
layers.forEach((l: LayerBase) => {
const match = (externalBaseLayers || []).filter(el => el.name === l.get("title"));
if (match.length == 1) {
l.setVisible(!!match[0].visible);
} else {
l.setVisible(false);
}
});
}
}
public updateTransparency(trans: LayerTransparencySet) {
//If no external layers defined, this won't be set
if (this.externalBaseLayersGroup) {
if (LAYER_ID_BASE in trans) {
this.externalBaseLayersGroup.setOpacity(restrictToRange(trans[LAYER_ID_BASE], 0, 1.0));
} else {
this.externalBaseLayersGroup.setOpacity(1.0);
}
}
if (LAYER_ID_MG_BASE in trans) {
const opacity = restrictToRange(trans[LAYER_ID_MG_BASE], 0, 1.0);
this.overlay.setOpacity(opacity);
for (const group of this.mgTiledLayers) {
group.setOpacity(opacity);
}
} else {
this.overlay.setOpacity(1.0);
for (const group of this.mgTiledLayers) {
group.setOpacity(1.0);
}
}
if (this.selectionOverlay) {
if (LAYER_ID_MG_SEL_OVERLAY in trans) {
this.selectionOverlay.setOpacity(restrictToRange(trans[LAYER_ID_MG_SEL_OVERLAY], 0, 1.0));
} else {
this.selectionOverlay.setOpacity(1.0);
}
}
}
public refreshMap(mode: RefreshMode = RefreshMode.LayersOnly | RefreshMode.SelectionOnly): void {
if ((mode & RefreshMode.LayersOnly) == RefreshMode.LayersOnly) {
const imgSource = this.overlay.getSource() as any; // olMapGuideSource;
imgSource.updateParams({
seq: (new Date()).getTime()
});
}
if (this.selectionOverlay) {
if ((mode & RefreshMode.SelectionOnly) == RefreshMode.SelectionOnly) {
const imgSource = this.selectionOverlay.getSource() as any; // olMapGuideSource;
imgSource.updateParams({
seq: (new Date()).getTime()
});
}
}
}
private makeActiveSelectedFeatureSource(mapExtent: Bounds, size: Size, url: string = BLANK_GIF_DATA_URI) {
return new ImageStaticSource({
imageExtent: mapExtent,
imageSize: [size.w, size.h],
url: url
});
}
public showActiveSelectedFeature(mapExtent: Bounds, size: Size, uri: string) {
if (this.activeSelectedFeatureOverlay) {
this.activeSelectedFeatureOverlay.setSource(this.makeActiveSelectedFeatureSource(mapExtent, size, uri));
this.activeSelectedFeatureOverlay.setVisible(true);
}
}
}
export interface IMapViewerContextCallback {
getMockMode(): MapGuideMockMode | undefined;
incrementBusyWorker(): void;
decrementBusyWorker(): void;
addImageLoading(): void;
addImageLoaded(): void;
onImageError(e: GenericEvent): void;
onSessionExpired(): void;
getSelectableLayers(): string[];
getClient(): Client;
isContextMenuOpen(): boolean;
getAgentUri(): string;
getAgentKind(): ClientKind;
getMapName(): string;
getSessionId(): string;
getLocale(): string | undefined;
isFeatureTooltipEnabled(): boolean;
getPointSelectionBox(point: Coordinate2D): Bounds;
openTooltipLink(url: string): void;
addFeatureToHighlight(feat: Feature<Geometry> | undefined, bAppend: boolean): void;
getBaseTileLoaders(): Dictionary<TileLoadFunction>;
}
export interface ILayerSetFactory {
create(locale: string | undefined,
externalBaseLayers: IExternalBaseLayer[] | undefined,
mode: MgLayerSetMode,
appSettings: Dictionary<string>): ILayerSetOL
}
export class MgInnerLayerSetFactory implements ILayerSetFactory {
private dynamicOverlayParams: any;
private staticOverlayParams: any;
private selectionOverlayParams: any;
constructor(private callback: IMapViewerContextCallback,
private map: RuntimeMap | IGenericSubjectMapLayer,
private agentUri: string | undefined,
imageFormat: string,
selectionImageFormat: string | undefined,
selectionColor: string | undefined) {
if (isRuntimeMap(map)) {
this.dynamicOverlayParams = {
MAPNAME: map.Name,
FORMAT: imageFormat,
SESSION: map.SessionId,
BEHAVIOR: 2
};
this.staticOverlayParams = {
MAPDEFINITION: map.MapDefinition,
FORMAT: imageFormat,
CLIENTAGENT: "ol.source.ImageMapGuide for OverviewMap",
USERNAME: "Anonymous",
VERSION: "3.0.0"
};
this.selectionOverlayParams = {
MAPNAME: map.Name,
FORMAT: selectionImageFormat || "PNG8",
SESSION: map.SessionId,
SELECTIONCOLOR: selectionColor,
BEHAVIOR: 1 | 4 //selected features + include outside current scale
};
}
}
private getTileUrlFunctionForGroup(resourceId: string, groupName: string, zOrigin: number) {
const urlTemplate = this.callback.getClient().getTileTemplateUrl(resourceId, groupName, '{x}', '{y}', '{z}');
return function (tileCoord: [number, number, number]) {
const z = tileCoord[0];
const x = tileCoord[1];
const y = tileCoord[2]; //NOTE: tileCoord format changed in OL 6.0, no longer need to negate and subtract by 1
return urlTemplate
.replace('{z}', (zOrigin - z).toString())
.replace('{x}', x.toString())
.replace('{y}', (y).toString());
};
}
public create(locale: string | undefined,
externalBaseLayers: IExternalBaseLayer[] | undefined,
mode: MgLayerSetMode,
appSettings: Dictionary<string>): ILayerSetOL {
const { map, agentUri } = this;
if (isRuntimeMap(map)) {
if (strIsNullOrEmpty(agentUri)) {
throw new MgError("Expected agentUri to be set");
}
//If a tile set definition is defined it takes precedence over the map definition, this enables
//this example to work with older releases of MapGuide where no such resource type exists.
const resourceId = map.TileSetDefinition || map.MapDefinition;
//On MGOS 2.6 or older, tile width/height is never returned, so default to 300x300
const tileWidth = map.TileWidth || 300;
const tileHeight = map.TileHeight || 300;
const metersPerUnit = map.CoordinateSystem.MetersPerUnit;
const finiteScales = [] as number[];
if (map.FiniteDisplayScale) {
for (let i = map.FiniteDisplayScale.length - 1; i >= 0; i--) {
finiteScales.push(map.FiniteDisplayScale[i]);
}
}
const extent: olExtent.Extent = [
map.Extents.LowerLeftCoordinate.X,
map.Extents.LowerLeftCoordinate.Y,
map.Extents.UpperRightCoordinate.X,
map.Extents.UpperRightCoordinate.Y
];
const dpi = map.DisplayDpi;
const inPerUnit = 39.37 * map.CoordinateSystem.MetersPerUnit;
const resolutions = new Array(finiteScales.length);
let projection: ProjectionLike;
for (let i = 0; i < finiteScales.length; ++i) {
resolutions[i] = finiteScales[i] / inPerUnit / dpi;
}
const parsedArb = tryParseArbitraryCs(map.CoordinateSystem.MentorCode);
if (parsedArb) {
projection = new Projection({
code: parsedArb.code,
units: toProjUnit(parsedArb.units),
metersPerUnit: toMetersPerUnit(parsedArb.units)
})
} else {
if (map.CoordinateSystem.EpsgCode.length > 0) {
projection = `EPSG:${map.CoordinateSystem.EpsgCode}`;
}
}
const tileGrid = new TileGrid({
origin: olExtent.getTopLeft(extent),
resolutions: resolutions,
tileSize: [tileWidth, tileHeight]
});
const zOrigin = finiteScales.length - 1;
const mgTiledLayers = [];
//const groupLayers = [] as TileLayer[];
if (map.Group) {
for (let i = 0; i < map.Group.length; i++) {
const group = map.Group[i];
if (group.Type != 2 && group.Type != 3) { //BaseMap or LinkedTileSet
continue;
}
const tileSource = new TileImageSource({
tileGrid: tileGrid,
projection: projection,
tileUrlFunction: this.getTileUrlFunctionForGroup(resourceId, group.Name, zOrigin),
wrapX: false
});
const tileLayer = new TileLayer({
//name: group.Name,
source: tileSource
});
tileLayer.set(LayerProperty.LAYER_NAME, group.ObjectId);
tileLayer.set(LayerProperty.LAYER_DISPLAY_NAME, group.ObjectId);
tileLayer.set(LayerProperty.LAYER_TYPE, MgLayerType.Tiled);
tileLayer.set(LayerProperty.IS_EXTERNAL, false);
tileLayer.set(LayerProperty.IS_GROUP, false);
tileLayer.setVisible(group.Visible);
//groupLayers.push(tileLayer);
mgTiledLayers.push(tileLayer);
}
}
/*
if (groupLayers.length > 0) {
groupLayers.push(
new ol.layer.Tile({
source: new ol.source.TileDebug({
tileGrid: tileGrid,
projection: projection,
tileUrlFunction: function(tileCoord) {
const z = tileCoord[0];
const x = tileCoord[1];
const y = tileCoord[2]; //NOTE: tileCoord format changed in OL 6.0, no longer need to negate and subtract by 1
return urlTemplate
.replace('{z}', (zOrigin - z).toString())
.replace('{x}', x.toString())
.replace('{y}', (y).toString());
},
wrapX: false
})
})
);
}
*/
const overlay = this.createMgOverlayLayer(MgBuiltInLayers.Overlay, agentUri, locale, metersPerUnit, projection, mode == MgLayerSetMode.Stateful, mode == MgLayerSetMode.Stateful ? this.dynamicOverlayParams : this.staticOverlayParams);
let selectionOverlay: OLImageLayer | undefined;
let activeSelectedFeatureOverlay: OLImageLayer | undefined;
if (mode == MgLayerSetMode.Stateful) {
selectionOverlay = this.createMgOverlayLayer(MgBuiltInLayers.SelectionOverlay, agentUri, locale, metersPerUnit, projection, true, this.selectionOverlayParams);
}
if (mode == MgLayerSetMode.Stateful) {
//NOTE: Not tracking this source atm
activeSelectedFeatureOverlay = new ImageLayer({
//OL6: need to specify a source up-front otherwise it will error blindly
//trying to get a source out of this URL, so set up a source with an empty
//image data URI, it will be updated if we receive a request to show an
//active selected feature image
source: new ImageStaticSource({
imageExtent: extent,
imageSize: [BLANK_SIZE.w, BLANK_SIZE.h],
url: BLANK_GIF_DATA_URI
})
});
activeSelectedFeatureOverlay.set(LayerProperty.LAYER_NAME, MgBuiltInLayers.ActiveFeatureSelectionOverlay);
activeSelectedFeatureOverlay.set(LayerProperty.LAYER_DISPLAY_NAME, MgBuiltInLayers.ActiveFeatureSelectionOverlay);
activeSelectedFeatureOverlay.set(LayerProperty.LAYER_TYPE, MG_LAYER_TYPE_NAME);
activeSelectedFeatureOverlay.set(LayerProperty.IS_EXTERNAL, false)
activeSelectedFeatureOverlay.set(LayerProperty.IS_GROUP, false);
}
let externalBaseLayersGroup: LayerGroup | undefined;
//NOTE: Don't bother adding external base layers for overview map as the main map in the
//overview is rendered with GETMAPIMAGE and not GETDYNAMICMAPOVERLAYIMAGE meaning the background
//is opaque and you won't be able to see the base layers underneath anyways.
if (mode != MgLayerSetMode.OverviewMap && externalBaseLayers != null) {
const groupOpts: any = {
title: tr("EXTERNAL_BASE_LAYERS", locale),
layers: externalBaseLayers.map(ext => {
const tl = this.createExternalBaseLayer(ext);
return tl;
})
};
externalBaseLayersGroup = new LayerGroup(groupOpts);
externalBaseLayersGroup.set(LayerProperty.LAYER_NAME, MG_BASE_LAYER_GROUP_NAME);
externalBaseLayersGroup.set(LayerProperty.LAYER_DISPLAY_NAME, MG_BASE_LAYER_GROUP_NAME);
externalBaseLayersGroup.set(LayerProperty.IS_EXTERNAL, false);
externalBaseLayersGroup.set(LayerProperty.IS_GROUP, true);
}
debug(`Creating OL view with projection ${projection} and ${resolutions.length} resolutions`);
let view: View;
if (resolutions.length == 0) {
view = new View({
projection: projection
});
} else {
view = new View({
projection: projection,
resolutions: resolutions
});
}
const layerSet = new MgLayerSetOL(mgTiledLayers,
externalBaseLayersGroup,
overlay,
projection,
dpi,
extent as Bounds,
inPerUnit,
view);
layerSet.selectionOverlay = selectionOverlay;
layerSet.activeSelectedFeatureOverlay = activeSelectedFeatureOverlay;
return layerSet;
} else {
let projection: ProjectionLike = map?.meta?.projection;
let bounds: Bounds | undefined;
let externalBaseLayersGroup: LayerGroup | undefined;
if (externalBaseLayers != null) {
const groupOpts: any = {
title: tr("EXTERNAL_BASE_LAYERS", locale),
layers: externalBaseLayers.map(ext => {
const tl = this.createExternalBaseLayer(ext);
return tl;
})
};
externalBaseLayersGroup = new LayerGroup(groupOpts);
externalBaseLayersGroup.set(LayerProperty.LAYER_NAME, MG_BASE_LAYER_GROUP_NAME);
externalBaseLayersGroup.set(LayerProperty.IS_EXTERNAL, false);
externalBaseLayersGroup.set(LayerProperty.IS_GROUP, true);
//projection = "EPSG:3857";
//bounds = DEFAULT_BOUNDS_3857;
}
let subjectLayer;
if (map) {
subjectLayer = createOLLayerFromSubjectDefn(map, projection, false, appSettings);
if (map.meta) {
projection = map.meta.projection;
bounds = map.meta.extents;
}
}
if (!projection && !bounds) {
projection = "EPSG:4326";
bounds = DEFAULT_BOUNDS_4326;
}
const parsedArb = tryParseArbitraryCs(projection);
let metersPerUnit: number | undefined = 1;
if (parsedArb) {
projection = new Projection({
code: parsedArb.code,
units: toProjUnit(parsedArb.units),
metersPerUnit: toMetersPerUnit(parsedArb.units),
extent: bounds
});
} else {
metersPerUnit = getMetersPerUnit(projection!);
}
const view = new View({
projection: projection
});
return new GenericLayerSetOL(view, subjectLayer, bounds!, externalBaseLayersGroup, projection!, metersPerUnit);
}
}
private createExternalBaseLayer(ext: IExternalBaseLayer) {
const extSource = createExternalSource(ext);
if (extSource instanceof UrlTile) {
const loaders = this.callback.getBaseTileLoaders();
if (loaders[ext.name])
extSource.setTileLoadFunction(loaders[ext.name]);
}
const options: any = {
title: ext.name,
type: "base",
visible: ext.visible === true,
source: extSource
};
const tl = new TileLayer(options);
tl.set(LayerProperty.LAYER_TYPE, ext.kind);
tl.set(LayerProperty.LAYER_NAME, ext.name);
tl.set(LayerProperty.LAYER_DISPLAY_NAME, ext.name);
tl.set(LayerProperty.IS_EXTERNAL, false);
tl.set(LayerProperty.IS_GROUP, false);
return tl;
}
private createMgOverlayLayer(layerName: string, agentUri: string, locale: string | undefined, metersPerUnit: number, projection: ProjectionLike, useImageOverlayOp: boolean, params: any): OLImageLayer {
const overlaySource = createMapGuideSource({
projection: projection,
url: agentUri,
useOverlay: useImageOverlayOp,
metersPerUnit: metersPerUnit,
params: params,
ratio: 1,
// For mobile devices with retina/hidpi displays, the default 96 DPI produces
// really low quality map images. For such devices, the DPI should be some
// function of the device pixel ratio reported. As this value can be fractional
// round it down to the nearest integer
displayDpi: Math.floor(olHas.DEVICE_PIXEL_RATIO) * 96
});
overlaySource.setAttributions(tr("PBMG", locale ?? DEFAULT_LOCALE));
const layer = new ImageLayer({
//name: "MapGuide Dynamic Overlay",
source: overlaySource
});
layer.set(LayerProperty.LAYER_NAME, layerName);
layer.set(LayerProperty.LAYER_DISPLAY_NAME, layerName);
layer.set(LayerProperty.LAYER_TYPE, MG_LAYER_TYPE_NAME);
layer.set(LayerProperty.IS_EXTERNAL, false);
layer.set(LayerProperty.IS_GROUP, false);
return layer;
}
}
export interface IMgLayerSetProps {
/**
* @since 0.14 This property can now also be a IGenericSubjectMapLayer
*/
map: RuntimeMap | IGenericSubjectMapLayer;
/**
* Use stateless GETMAP requests for map rendering
* @since 0.14
*/
stateless?: boolean;
imageFormat: ImageFormat;
selectionImageFormat?: ImageFormat;
selectionColor?: string;
/**
* @since 0.14 Made optional
*/
agentUri?: string;
externalBaseLayers?: IExternalBaseLayer[];
locale?: string;
/**
* @since 0.14
*/
appSettings: Dictionary<string>;
}
export interface IMgLayerSetCallback extends IImageLayerEvents {
getMockMode(): MapGuideMockMode | undefined;
incrementBusyWorker(): void;
decrementBusyWorker(): void;
onSessionExpired(): void;
getSelectableLayers(): string[];
getClient(): Client;
isContextMenuOpen(): boolean;
getAgentUri(): string;
getAgentKind(): ClientKind;
getMapName(): string;
getSessionId(): string;
isFeatureTooltipEnabled(): boolean;
getPointSelectionBox(point: Coordinate2D): Bounds;
openTooltipLink(url: string): void;
addFeatureToHighlight(feat: Feature<Geometry> | undefined, bAppend: boolean): void;
} | the_stack |
import { Injectable, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Params, RouteReuseStrategy, RouterStateSnapshot } from '@angular/router';
import { DefaultRouterStateSerializer, RouterStateSerializer, StoreRouterConnectingModule } from '@ngrx/router-store';
import { Store } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { getGitHubAPIURL, GITHUB_API_URL } from '@stratosui/git';
import { debounceTime, filter, withLatestFrom } from 'rxjs/operators';
import { SetRecentlyVisitedEntityAction } from '../../store/src/actions/recently-visited.actions';
import { GeneralEntityAppState, GeneralRequestDataState } from '../../store/src/app-state';
import { EntityCatalogModule } from '../../store/src/entity-catalog.module';
import { entityCatalog } from '../../store/src/entity-catalog/entity-catalog';
import { EntityCatalogHelper } from '../../store/src/entity-catalog/entity-catalog-entity/entity-catalog.service';
import { EntityCatalogHelpers } from '../../store/src/entity-catalog/entity-catalog.helper';
import { endpointEntityType, STRATOS_ENDPOINT_TYPE } from '../../store/src/helpers/stratos-entity-factory';
import { getAPIRequestDataState, selectEntity } from '../../store/src/selectors/api.selectors';
import { internalEventStateSelector } from '../../store/src/selectors/internal-events.selectors';
import { recentlyVisitedSelector } from '../../store/src/selectors/recently-visitied.selectors';
import { AppStoreModule } from '../../store/src/store.module';
import { stratosEntityCatalog } from '../../store/src/stratos-entity-catalog';
import { generateStratosEntities } from '../../store/src/stratos-entity-generator';
import { EndpointModel } from '../../store/src/types/endpoint.types';
import { IFavoriteMetadata, UserFavorite } from '../../store/src/types/user-favorites.types';
import { UserFavoriteManager } from '../../store/src/user-favorite-manager';
import { AppComponent } from './app.component';
import { RouteModule } from './app.routing';
import { CoreModule } from './core/core.module';
import { CustomizationService } from './core/customizations.types';
import { DynamicExtensionRoutes } from './core/extension/dynamic-extension-routes';
import { ExtensionService } from './core/extension/extension-service';
import { CurrentUserPermissionsService } from './core/permissions/current-user-permissions.service';
import { CustomImportModule } from './custom-import.module';
import { environment } from './environments/environment';
import { AboutModule } from './features/about/about.module';
import { DashboardModule } from './features/dashboard/dashboard.module';
import { HomeModule } from './features/home/home.module';
import { LoginModule } from './features/login/login.module';
import { NoEndpointsNonAdminComponent } from './features/no-endpoints-non-admin/no-endpoints-non-admin.component';
import { SetupModule } from './features/setup/setup.module';
import { LoggedInService } from './logged-in.service';
import { CustomReuseStrategy } from './route-reuse-stragegy';
import { endpointEventKey, GlobalEventData, GlobalEventService } from './shared/global-events.service';
import { SidePanelService } from './shared/services/side-panel.service';
import { SharedModule } from './shared/shared.module';
import { TabNavService } from './tab-nav.service';
import { XSRFModule } from './xsrf.module';
// Create action for router navigation. See
// - https://github.com/ngrx/platform/issues/68
// - https://github.com/ngrx/platform/issues/201 (https://github.com/ngrx/platform/pull/355)
// https://github.com/ngrx/platform/blob/master/docs/router-store/api.md#custom-router-state-serializer
export interface RouterStateUrl {
url: string;
params: Params;
queryParams: Params;
}
@Injectable()
export class CustomRouterStateSerializer
implements RouterStateSerializer<RouterStateUrl> {
serialize(routerState: RouterStateSnapshot): RouterStateUrl {
let route = routerState.root;
while (route.firstChild) {
route = route.firstChild;
}
const { url } = routerState;
const queryParams = routerState.root.queryParams;
const params = route.params;
// Only return an object including the URL, params and query params
// instead of the entire snapshot
return { url, params, queryParams };
}
}
const storeDebugImports = environment.production ? [] : [
StoreDevtoolsModule.instrument({
maxAge: 100,
logOnly: !environment.production
})
];
@NgModule({
imports: storeDebugImports
})
class AppStoreDebugModule { }
@NgModule({
declarations: [
AppComponent,
NoEndpointsNonAdminComponent,
],
imports: [
EntityCatalogModule.forFeature(generateStratosEntities),
RouteModule,
AppStoreModule,
AppStoreDebugModule,
BrowserModule,
SharedModule,
BrowserAnimationsModule,
CoreModule,
SetupModule,
LoginModule,
HomeModule,
DashboardModule,
StoreRouterConnectingModule.forRoot({ serializer: DefaultRouterStateSerializer }), // Create action for router navigation
AboutModule,
CustomImportModule,
XSRFModule,
],
providers: [
CustomizationService,
TabNavService,
LoggedInService,
ExtensionService,
DynamicExtensionRoutes,
SidePanelService,
{ provide: GITHUB_API_URL, useFactory: getGitHubAPIURL },
{ provide: RouterStateSerializer, useClass: CustomRouterStateSerializer }, // Create action for router navigation
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy },
CurrentUserPermissionsService
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(
ext: ExtensionService,
private store: Store<GeneralEntityAppState>,
eventService: GlobalEventService,
private userFavoriteManager: UserFavoriteManager,
ech: EntityCatalogHelper
) {
EntityCatalogHelpers.SetEntityCatalogHelper(ech);
eventService.addEventConfig<boolean>({
eventTriggered: (state: GeneralEntityAppState) => new GlobalEventData(!state.dashboard.timeoutSession),
message: 'Timeout session is disabled - this is considered a security risk.',
key: 'timeoutSessionWarning',
link: '/user-profile'
});
eventService.addEventConfig<boolean>({
eventTriggered: (state: GeneralEntityAppState) => new GlobalEventData(!state.dashboard.pollingEnabled),
message: 'Data polling is disabled - you may be seeing out-of-date data throughout the application.',
key: 'pollingEnabledWarning',
link: '/user-profile'
});
eventService.addEventConfig<{
count: number,
endpoint: EndpointModel;
}>({
eventTriggered: (state: GeneralEntityAppState) => {
const eventState = internalEventStateSelector(state);
return Object.entries(eventState.types.endpoint).reduce((res, [eventId, value]) => {
const backendErrors = value.filter(error => {
const eventCode = parseInt(error.eventCode, 10);
return eventCode >= 500;
});
if (!backendErrors.length) {
return res;
}
const entityConfig = entityCatalog.getEntity(STRATOS_ENDPOINT_TYPE, endpointEntityType);
res.push(new GlobalEventData(true, {
endpoint: selectEntity<EndpointModel>(entityConfig.entityKey, eventId)(state),
count: backendErrors.length
}));
return res;
}, []);
},
message: data => {
const part1 = data.count > 1 ? `There are ${data.count} errors` : `There is an error`;
const part2 = data.endpoint ? ` associated with the endpoint '${data.endpoint.name}'` : ` associated with multiple endpoints`;
return part1 + part2;
},
key: data => `${endpointEventKey}-${data.endpoint.guid}`,
link: data => `/errors/${data.endpoint.guid}`,
type: 'error'
});
// This should be brought back in in the future
// eventService.addEventConfig<IRequestEntityTypeState<EndpointModel>, EndpointModel>(
// {
// selector: (state: AppState) => state.requestData.endpoint,
// eventTriggered: (state: IRequestEntityTypeState<EndpointModel>) => {
// return Object.values(state).reduce((events, endpoint) => {
// if (endpoint.connectionStatus === 'checking') {
// events.push(new GlobalEventData(true, endpoint));
// }
// return events;
// }, []);
// },
// message: (endpoint: EndpointModel) => `Connecting endpoint ${endpoint.name}`,
// link: '/endpoints',
// key: 'endpoint-connect',
// type: 'process'
// }
// );
ext.init();
// Init Auth Types and Endpoint Types provided by extensions
// Once the CF modules become an extension point, these should be moved to a CF specific module
const allFavs$ = this.userFavoriteManager.getAllFavorites().pipe(
filter(([groups, favoriteEntities]) => !!groups && !!favoriteEntities)
);
const recents$ = this.store.select(recentlyVisitedSelector);
const debouncedApiRequestData$ = this.store.select(getAPIRequestDataState).pipe(debounceTime(2000));
debouncedApiRequestData$.pipe(
withLatestFrom(allFavs$)
).subscribe(
([entities, [favoriteGroups, favorites]]) => {
Object.keys(favoriteGroups).forEach(endpointId => {
const favoriteGroup = favoriteGroups[endpointId];
if (!favoriteGroup.ethereal) {
const endpointFavorite = favorites[endpointId];
this.syncFavorite(endpointFavorite, entities);
}
favoriteGroup.entitiesIds.forEach(id => {
const favorite = favorites[id];
this.syncFavorite(favorite, entities);
});
});
}
);
// This updates the names of any recents
debouncedApiRequestData$.pipe(
withLatestFrom(recents$)
).subscribe(
([entities, recents]) => {
Object.values(recents).forEach(recentEntity => {
const entityKey = entityCatalog.getEntityKey(recentEntity);
if (entities[entityKey] && entities[entityKey][recentEntity.entityId]) {
const entity = entities[entityKey][recentEntity.entityId];
const entityToMetadata = this.userFavoriteManager.getEntityMetadata(recentEntity, entity);
const name = entityToMetadata.name;
if (name && name !== recentEntity.name) {
// Update the entity name
this.store.dispatch(new SetRecentlyVisitedEntityAction({
...recentEntity,
name
}));
}
}
});
}
);
}
private syncFavorite(favorite: UserFavorite<IFavoriteMetadata>, entities: GeneralRequestDataState) {
if (favorite) {
const isEndpoint = (favorite.entityType === endpointEntityType);
// If the favorite is an endpoint ensure we look in the stratosEndpoint part of the store instead of, for example, cfEndpoint
const entityKey = isEndpoint ? entityCatalog.getEntityKey({
...favorite,
endpointType: STRATOS_ENDPOINT_TYPE
}) : entityCatalog.getEntityKey(favorite);
const entity = entities[entityKey][favorite.entityId || favorite.endpointId];
if (entity) {
const newMetadata = this.userFavoriteManager.getEntityMetadata(favorite, entity);
if (this.metadataHasChanged(favorite.metadata, newMetadata)) {
const fav = this.userFavoriteManager.getUserFavoriteFromObject(favorite);
fav.metadata = newMetadata;
stratosEntityCatalog.userFavorite.api.updateFavorite(fav);
}
}
}
}
private metadataHasChanged(oldMeta: IFavoriteMetadata, newMeta: IFavoriteMetadata) {
if ((!oldMeta && newMeta) || (oldMeta && !newMeta)) {
return true;
}
const oldKeys = Object.keys(oldMeta);
const newKeys = Object.keys(newMeta);
const oldValues = Object.values(oldMeta);
const newValues = Object.values(newMeta);
if (oldKeys.length !== newKeys.length) {
return true;
}
if (oldKeys.sort().join(',') !== newKeys.sort().join(',')) {
return true;
}
if (oldValues.sort().join(',') !== newValues.sort().join(',')) {
return true;
}
return false;
}
} | the_stack |
import { strictParseByte, strictParseDouble, strictParseFloat32, strictParseShort } from "./parse-utils";
// Build indexes outside so we allocate them once.
const DAYS: Array<String> = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
// These must be kept in order
// prettier-ignore
const MONTHS: Array<String> = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/**
* Builds a proper UTC HttpDate timestamp from a Date object
* since not all environments will have this as the expected
* format.
*
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
* > Prior to ECMAScript 2018, the format of the return value
* > varied according to the platform. The most common return
* > value was an RFC-1123 formatted date stamp, which is a
* > slightly updated version of RFC-822 date stamps.
*/
export function dateToUtcString(date: Date): string {
const year = date.getUTCFullYear();
const month = date.getUTCMonth();
const dayOfWeek = date.getUTCDay();
const dayOfMonthInt = date.getUTCDate();
const hoursInt = date.getUTCHours();
const minutesInt = date.getUTCMinutes();
const secondsInt = date.getUTCSeconds();
// Build 0 prefixed strings for contents that need to be
// two digits and where we get an integer back.
const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`;
const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`;
const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`;
const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`;
return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`;
}
const RFC3339 = new RegExp(
/^(?<Y>\d{4})-(?<M>\d{2})-(?<D>\d{2})[tT](?<H>\d{2}):(?<m>\d{2}):(?<s>\d{2})(?:\.(?<frac>\d+))?[zZ]$/
);
/**
* Parses a value into a Date. Returns undefined if the input is null or
* undefined, throws an error if the input is not a string that can be parsed
* as an RFC 3339 date.
*
* Input strings must conform to RFC3339 section 5.6, and cannot have a UTC
* offset. Fractional precision is supported.
*
* {@see https://xml2rfc.tools.ietf.org/public/rfc/html/rfc3339.html#anchor14}
*
* @param value the value to parse
* @return a Date or undefined
*/
export const parseRfc3339DateTime = (value: unknown): Date | undefined => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "string") {
throw new TypeError("RFC-3339 date-times must be expressed as strings");
}
const match = RFC3339.exec(value);
if (!match || !match.groups) {
throw new TypeError("Invalid RFC-3339 date-time value");
}
const year = strictParseShort(stripLeadingZeroes(match.groups["Y"]))!;
const month = parseDateValue(match.groups["M"], "month", 1, 12);
const day = parseDateValue(match.groups["D"], "day", 1, 31);
return buildDate(year, month, day, match);
};
const IMF_FIXDATE = new RegExp(
/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?<D>\d{2}) (?<M>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?<Y>\d{4}) (?<H>\d{2}):(?<m>\d{2}):(?<s>\d{2})(?:\.(?<frac>\d+))? GMT$/
);
const RFC_850_DATE = new RegExp(
/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?<D>\d{2})-(?<M>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(?<Y>\d{2}) (?<H>\d{2}):(?<m>\d{2}):(?<s>\d{2})(?:\.(?<frac>\d+))? GMT$/
);
const ASC_TIME = new RegExp(
/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?<M>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?<D> [1-9]|\d{2}) (?<H>\d{2}):(?<m>\d{2}):(?<s>\d{2})(?:\.(?<frac>\d+))? (?<Y>\d{4})$/
);
/**
* Parses a value into a Date. Returns undefined if the input is null or
* undefined, throws an error if the input is not a string that can be parsed
* as an RFC 7231 IMF-fixdate or obs-date.
*
* Input strings must conform to RFC7231 section 7.1.1.1. Fractional seconds are supported.
*
* {@see https://datatracker.ietf.org/doc/html/rfc7231.html#section-7.1.1.1}
*
* @param value the value to parse
* @return a Date or undefined
*/
export const parseRfc7231DateTime = (value: unknown): Date | undefined => {
if (value === null || value === undefined) {
return undefined;
}
if (typeof value !== "string") {
throw new TypeError("RFC-7231 date-times must be expressed as strings");
}
//allow customization of day parsing for asctime days, which can be left-padded with spaces
let dayFn: (value: string) => number = (value) => parseDateValue(value, "day", 1, 31);
//all formats other than RFC 850 use a four-digit year
let yearFn: (value: string) => number = (value: string) => strictParseShort(stripLeadingZeroes(value))!;
//RFC 850 dates need post-processing to adjust year values if they are too far in the future
let dateAdjustmentFn: (value: Date) => Date = (value) => value;
let match = IMF_FIXDATE.exec(value);
if (!match || !match.groups) {
match = RFC_850_DATE.exec(value);
if (match && match.groups) {
// RFC 850 dates use 2-digit years. So we parse the year specifically,
// and then once we've constructed the entire date, we adjust it if the resultant date
// is too far in the future.
yearFn = parseTwoDigitYear;
dateAdjustmentFn = adjustRfc850Year;
} else {
match = ASC_TIME.exec(value);
if (match && match.groups) {
dayFn = (value) => parseDateValue(value.trimLeft(), "day", 1, 31);
} else {
throw new TypeError("Invalid RFC-7231 date-time value");
}
}
}
const year = yearFn(match.groups["Y"]);
const month = parseMonthByShortName(match.groups["M"]);
const day = dayFn(match.groups["D"]);
return dateAdjustmentFn(buildDate(year, month, day, match));
};
/**
* Parses a value into a Date. Returns undefined if the input is null or
* undefined, throws an error if the input is not a number or a parseable string.
*
* Input strings must be an integer or floating point number. Fractional seconds are supported.
*
* @param value the value to parse
* @return a Date or undefined
*/
export const parseEpochTimestamp = (value: unknown): Date | undefined => {
if (value === null || value === undefined) {
return undefined;
}
let valueAsDouble: number;
if (typeof value === "number") {
valueAsDouble = value;
} else if (typeof value === "string") {
valueAsDouble = strictParseDouble(value)!;
} else {
throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");
}
if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) {
throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");
}
return new Date(Math.round(valueAsDouble * 1000));
};
/**
* Build a date from a numeric year, month, date, and an match with named groups
* "H", "m", s", and "frac", representing hours, minutes, seconds, and optional fractional seconds.
* @param year numeric year
* @param month numeric month, 1-indexed
* @param day numeric year
* @param match match with groups "H", "m", s", and "frac"
*/
const buildDate = (year: number, month: number, day: number, match: RegExpMatchArray): Date => {
const adjustedMonth = month - 1; // JavaScript, and our internal data structures, expect 0-indexed months
validateDayOfMonth(year, adjustedMonth, day);
// Adjust month down by 1
return new Date(
Date.UTC(
year,
adjustedMonth,
day,
parseDateValue(match.groups!["H"]!, "hour", 0, 23),
parseDateValue(match.groups!["m"]!, "minute", 0, 59),
// seconds can go up to 60 for leap seconds
parseDateValue(match.groups!["s"]!, "seconds", 0, 60),
parseMilliseconds(match.groups!["frac"])
)
);
};
/**
* RFC 850 dates use a 2-digit year; start with the assumption that if it doesn't
* match the current year, then it's a date in the future, then let adjustRfc850Year adjust
* the final date back to the past if it's too far in the future.
*
* Example: in 2021, start with the assumption that '11' is '2111', and that '22' is '2022'.
* adjustRfc850Year will adjust '11' to 2011, (as 2111 is more than 50 years in the future),
* but keep '22' as 2022. in 2099, '11' will represent '2111', but '98' should be '2098'.
* There's no description of an RFC 850 date being considered too far in the past in RFC-7231,
* so it's entirely possible that 2011 is a valid interpretation of '11' in 2099.
* @param value the 2 digit year to parse
* @return number a year that is equal to or greater than the current UTC year
*/
const parseTwoDigitYear = (value: string): number => {
const thisYear = new Date().getUTCFullYear();
const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value))!;
if (valueInThisCentury < thisYear) {
// This may end up returning a year that adjustRfc850Year turns back by 100.
// That's fine! We don't know the other components of the date yet, so there are
// boundary conditions that only adjustRfc850Year can handle.
return valueInThisCentury + 100;
}
return valueInThisCentury;
};
const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000;
/**
* Adjusts the year value found in RFC 850 dates according to the rules
* expressed in RFC7231, which state:
*
* <blockquote>Recipients of a timestamp value in rfc850-date format, which uses a
* two-digit year, MUST interpret a timestamp that appears to be more
* than 50 years in the future as representing the most recent year in
* the past that had the same last two digits.</blockquote>
*
* @param input a Date that assumes the two-digit year was in the future
* @return a Date that is in the past if input is > 50 years in the future
*/
const adjustRfc850Year = (input: Date): Date => {
if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) {
return new Date(
Date.UTC(
input.getUTCFullYear() - 100,
input.getUTCMonth(),
input.getUTCDate(),
input.getUTCHours(),
input.getUTCMinutes(),
input.getUTCSeconds(),
input.getUTCMilliseconds()
)
);
}
return input;
};
const parseMonthByShortName = (value: string): number => {
const monthIdx = MONTHS.indexOf(value);
if (monthIdx < 0) {
throw new TypeError(`Invalid month: ${value}`);
}
return monthIdx + 1;
};
const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/**
* Validate the day is valid for the given month.
* @param year the year
* @param month the month (0-indexed)
* @param day the day of the month
*/
const validateDayOfMonth = (year: number, month: number, day: number) => {
let maxDays = DAYS_IN_MONTH[month];
if (month === 1 && isLeapYear(year)) {
maxDays = 29;
}
if (day > maxDays) {
throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`);
}
};
const isLeapYear = (year: number): boolean => {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
};
const parseDateValue = (value: string, type: string, lower: number, upper: number): number => {
const dateVal = strictParseByte(stripLeadingZeroes(value))!;
if (dateVal < lower || dateVal > upper) {
throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);
}
return dateVal;
};
const parseMilliseconds = (value: string | undefined): number => {
if (value === null || value === undefined) {
return 0;
}
return strictParseFloat32("0." + value)! * 1000;
};
const stripLeadingZeroes = (value: string): string => {
let idx = 0;
while (idx < value.length - 1 && value.charAt(idx) === "0") {
idx++;
}
if (idx === 0) {
return value;
}
return value.slice(idx);
}; | the_stack |
import { TreeGrid } from '../../src/treegrid/base/treegrid';
import { createGrid, destroy } from '../base/treegridutil.spec';
import { sampleData, projectData, sortData } from '../base/datasource.spec';
import { Sort } from '../../src/treegrid/actions/sort';
import { profile, inMB, getMemoryProfile } from '../common.spec';
/**
* Grid base spec
*/
TreeGrid.Inject(Sort);
describe('TreeGrid Sort module', () => {
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('Flat Data Single Sort Descending', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
allowSorting: true,
allowMultiSorting: true,
columns: ['TaskID', 'TaskName', 'StartDate', 'EndDate']
},done);
});
it('expand testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Parent Task 2").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Child Task 1").toBe(true);
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[0].innerHTML == "3").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[0].innerHTML == "4").toBe(true);
expect(gridObj.parentData.length).toBe(2);
done();
}
gridObj.grid.actionComplete = actionComplete;
gridObj.sortByColumn("TaskName", "Descending", true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Flat Data Single Sort Ascending', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: projectData,
idMapping: 'TaskID',
parentIdMapping: 'parentID',
treeColumnIndex: 1,
allowSorting: true,
columns: ['TaskID', 'TaskName', 'StartDate', 'EndDate']
},done);
});
it('expand testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Parent Task 1").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Child Task 1").toBe(true);
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[0].innerHTML == "1").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[0].innerHTML == "2").toBe(true);
expect(gridObj.parentData.length).toBe(2);
done();
}
gridObj.sortByColumn("TaskName", "Ascending", true);
gridObj.grid.actionComplete = actionComplete;
gridObj.clearSorting();
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Hierarchy data Single sort Ascending', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
allowSorting: true,
columns: ['taskID', 'taskName', 'startDate', 'endDate']
},done);
});
it('expand testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Design").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Design complete").toBe(true);
expect(gridObj.getRows()[8].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Implementation Module 1").toBe(true);
expect(gridObj.getRows()[9].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Bug fix").toBe(true);
expect(gridObj.getRows()[16].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Implementation Module 2").toBe(true);
expect(gridObj.getRows()[31].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Planning").toBe(true);
done();
}
gridObj.sortByColumn("taskName", "Ascending", false);
gridObj.grid.actionComplete = actionComplete;
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Multi sort Ascending', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
allowSorting: true,
columns: ['taskID', 'taskName', 'startDate', 'endDate']
},done);
});
it('expand testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Design").toBe(true);
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[0].innerHTML == "6").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Design complete").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[0].innerHTML == "11").toBe(true);
expect(gridObj.getRows()[8].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Implementation Module 1").toBe(true);
expect(gridObj.getRows()[8].getElementsByClassName('e-rowcell')[0].innerHTML == "14").toBe(true);
expect(gridObj.getRows()[9].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Bug fix").toBe(true);
expect(gridObj.getRows()[9].getElementsByClassName('e-rowcell')[0].innerHTML == "18").toBe(true);
expect(gridObj.getRows()[16].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Implementation Module 2").toBe(true);
expect(gridObj.getRows()[16].getElementsByClassName('e-rowcell')[0].innerHTML == "22").toBe(true);
expect(gridObj.getRows()[31].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Planning").toBe(true);
expect(gridObj.getRows()[31].getElementsByClassName('e-rowcell')[0].innerHTML == "1").toBe(true);
done();
}
gridObj.grid.actionComplete = actionComplete;
gridObj.sortByColumn("taskName", "Ascending", true);
gridObj.sortByColumn("taskID", "Ascending", true);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Single sort Descending', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
allowSorting: true,
columns: ['taskID', 'taskName', 'startDate', 'endDate']
},done);
});
it('expand testing', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Planning").toBe(true);
expect(gridObj.getRows()[1].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Planning complete").toBe(true);
expect(gridObj.getRows()[8].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Testing").toBe(true);
expect(gridObj.getRows()[9].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Phase 3 complete").toBe(true);
expect(gridObj.getRows()[16].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Testing").toBe(true);
expect(gridObj.getRows()[30].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Design").toBe(true);
done();
}
gridObj.sortByColumn("taskName", "Descending", true);
gridObj.grid.actionComplete = actionComplete;
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Sorting Propertychange', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
columns: ['taskID', 'taskName', 'startDate', 'endDate', 'duration', 'progress'],
},
done
);
});
it('allowSorting and sortSettings using onproperty', () => {
gridObj.allowSorting = true;
gridObj.allowMultiSorting = true;
gridObj.sortSettings = { columns: [{ field: 'taskName', direction: 'Descending' }] };
});
afterAll(() => {
destroy(gridObj);
});
});
describe('Remove Sort Column', () => {
let gridObj: TreeGrid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
allowSorting: true,
columns: ['taskID', 'taskName', 'startDate', 'endDate']
},done);
});
it('Remove Sorting', () => {
gridObj.sortByColumn("taskName", "Descending", true);
gridObj.removeSortColumn('taskName');
expect(gridObj.sortSettings.columns.length).toBe(0);
});
afterAll(() => {
destroy(gridObj);
});
});
});
describe('Sorting with Sort comparer property functionality checking', () => {
let gridObj: TreeGrid;
let actionComplete: () => void;
let called: boolean = false;
let sortComparer: (reference: string, comparer: string) => number = (reference: string,
comparer: string) => {
called = true;
if (reference < comparer) {
return -1;
}
if (reference > comparer) {
return 1;
}
return 0;
};
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
allowSorting: true,
treeColumnIndex: 1,
allowPaging: true,
columns: [
{ field: 'taskID', }, { field: 'taskName', sortComparer: sortComparer, }, { field: 'startDate' }, { field: 'endDate' },
{ field: 'duration' },]
}, done);
});
it('Sorting with sortComparer property', (done: Function) => {
actionComplete = (args?: any): void => {
expect(called).toBe(true);
expect(args.rows[0].data.taskName === "Planning").toBe(true);
expect(args.direction === "Descending").toBe(true);
expect(args.rows[6].data.taskName === "Phase 3").toBe(true);
expect(args.rows[5].data.taskName === "Implementation Phase").toBe(true);
gridObj.actionComplete = null;
done();
}
gridObj.actionComplete = actionComplete;
gridObj.sortByColumn("taskName", "Descending", false);
});
afterAll(() => {
destroy(gridObj);
});
describe('EJ2-25219: Updating datasource dynamically after performing sorting is not working', () => {
let gridObj: TreeGrid;
let rows: Element[];
let actionComplete: ()=> void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sampleData,
childMapping: 'subtasks',
treeColumnIndex: 1,
allowSorting: true,
sortSettings: {columns: [{field: 'taskName', direction: 'Ascending'}]},
toolbar: ['Search'],
columns: [
{ field: 'taskId', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right', width: 80 },
{ field: 'taskName', headerText: 'Task Name', width: 200 },
{ field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 100, format: { skeleton: 'yMd', type: 'date' } },
{ field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 90 },
{ field: 'progress', headerText: 'Progress', textAlign: 'Right', width: 90 }
]
},
done
);
});
it('Datasource update with Sorting', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].querySelector("div>.e-treecell").innerHTML == "Implementation Phase").toBe(true);
done();
}
gridObj.grid.dataBound = actionComplete;
gridObj.dataSource = sampleData.slice(2);
});
afterAll(() => {
destroy(gridObj);
});
});
describe('EJ2-32541 - Issue in MultiSorting Sample', () => {
let gridObj: TreeGrid;
let actionComplete: ()=> void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: sortData,
childMapping: 'subtasks',
treeColumnIndex: 0,
allowSorting: true,
columns: [
{ field: 'orderName', headerText: 'Order Name', width: 200 },
{ field: 'Category', headerText: 'Category', width: 140 },
{ field: 'orderDate', headerText: 'Order Date', width: 150, textAlign: 'Right', format: 'yMd', type: 'date' },
{ field: 'units', headerText: 'Units', width: 110, textAlign: 'Right' }
],
sortSettings: { columns: [{ field: 'Category', direction: 'Ascending' }, { field: 'orderName', direction: 'Ascending' }] }
},
done
);
});
it('Datasource update with Sorting', (done: Function) => {
actionComplete = (args?: Object): void => {
expect(gridObj.getRows()[0].getElementsByClassName('e-rowcell')[1].innerHTML == "Seafoods").toBe(true);
done();
}
let event: MouseEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
gridObj.actionComplete = actionComplete;
gridObj.getHeaderTable().querySelectorAll('.e-sortnumber')[1].dispatchEvent(event);
});
afterAll(() => {
destroy(gridObj);
});
});
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);
});
}); | the_stack |
describe('team management', () => {
const now = Cypress.moment().format('MMDDYYhhmm');
const cypressPrefix = 'test-team-mgmt';
const teamName = `${cypressPrefix} team ${now}`;
const customTeamID = `${cypressPrefix}-custom-id-${now}`;
const generatedTeamID = teamName.split(' ').join('-');
const unassignedTeam1ID = `${cypressPrefix}-unassigned-1-${now}`;
const unassignedTeam2ID = `${cypressPrefix}-unassigned-2-${now}`;
const teamIDWithSomeProjects = `${cypressPrefix}-some-projects-${now}`;
const teamIDWithOneProject = `${cypressPrefix}-one-project-${now}`;
const project1ID = `${cypressPrefix}-project1-${now}`;
const project1Name = `${cypressPrefix} project1 ${now}`;
const project2ID = `${cypressPrefix}-project2-${now}`;
const project2Name = `${cypressPrefix} project2 ${now}`;
const unassigned = '(unassigned)';
before(() => {
cy.adminLogin('/settings/teams').then(() => {
const admin = JSON.parse(<string>localStorage.getItem('chef-automate-user'));
cy.request({
auth: { bearer: admin.id_token },
method: 'POST',
url: '/apis/iam/v2/projects',
body: {
id: project1ID,
name: project1Name,
skip_policies: true
}
});
cy.request({
auth: { bearer: admin.id_token },
method: 'POST',
url: '/apis/iam/v2/projects',
body: {
id: project2ID,
name: project2Name,
skip_policies: true
}
});
// reload so we get projects in project filter
cy.reload(true);
cy.get('app-welcome-modal').invoke('hide');
});
cy.restoreStorage();
});
beforeEach(() => {
cy.restoreStorage();
});
afterEach(() => {
cy.saveStorage();
});
after(() => {
cy.cleanupIAMObjectsByIDPrefixes(cypressPrefix, ['projects', 'teams']);
});
describe('teams list page', () => {
const dropdownNameUntilEllipsisLen = 25;
const projectDropdownPrefix = 'app-team-management app-projects-dropdown';
it('lists system teams', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team');
cy.get('#table-container chef-th').contains('ID');
cy.get('#table-container chef-th').contains('Name');
const systemTeams = ['admins', 'editors', 'viewers'];
systemTeams.forEach(name => {
cy.get('#table-container chef-tr').contains(name)
.parent().parent().find('mat-select').as('control-menu');
});
});
it('can create a team with a default ID', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(teamName);
cy.get('[data-cy=id-label]').contains(generatedTeamID);
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal').should('not.be.visible');
// verify success notification and then dismiss it
// so it doesn't get in the way of subsequent interactions
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
cy.contains(teamName).should('exist');
cy.contains(generatedTeamID).should('exist');
});
it('can create a team with a custom ID', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(teamName);
cy.get('[data-cy=create-id]').should('not.be.visible');
cy.get('[data-cy=edit-button]').contains('Edit ID').click();
cy.get('[data-cy=id-label]').should('not.be.visible');
cy.get('[data-cy=create-id]').should('be.visible').clear().type(customTeamID);
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal').should('not.be.visible');
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
cy.contains(teamName).should('exist');
cy.contains(customTeamID).should('exist');
});
it('fails to create a team with a duplicate ID', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(teamName);
cy.get('[data-cy=id-label]').contains(generatedTeamID);
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal chef-error').contains('already exists')
.should('be.visible');
// here we exit with the chef-modal exit button in the top right corner
cy.get('app-team-management chef-modal chef-button.close').first().click();
});
it('can cancel creating a team', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('chef-button').contains('Cancel').should('be.visible').click();
// here we exit with the Cancel button
cy.get('app-team-management chef-modal').should('not.be.visible');
});
it('can delete a team', () => {
cy.get('app-team-management chef-td').contains(customTeamID).parent()
.find('.mat-select-trigger').as('controlMenu');
// we throw in a `should` so cypress retries until introspection allows menu to be shown
cy.get('@controlMenu').scrollIntoView().should('be.visible')
.click();
cy.get('[data-cy=delete-team]').should('be.visible')
.click();
// accept dialog
cy.get('app-team-management chef-button').contains('Delete Team').click();
// verify success notification and then dismiss it
cy.get('app-notification.info').contains('Deleted team');
cy.get('app-notification.info chef-icon').click();
cy.get('app-team-management chef-tbody chef-td')
.contains(customTeamID).should('not.exist');
});
context('when only the unassigned project is selected', () => {
beforeEach(() => {
cy.applyProjectsFilter([unassigned]);
});
it(`can create a team with no projects (unassigned)
and cannot access projects dropdown`, () => {
if (Cypress.$('app-welcome-modal').length) { // zero length means not found
cy.get('[data-cy=close-x]').click();
}
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(unassignedTeam1ID);
cy.get('[data-cy=id-label]').contains(unassignedTeam1ID);
// initial state of dropdown
cy.get(`${projectDropdownPrefix} #resources-selected`)
.contains(unassigned);
cy.get(`${projectDropdownPrefix} .dropdown-button`)
.should('have.attr', 'disabled');
// save team
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal').should('not.be.visible');
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
cy.contains(unassignedTeam1ID).should('exist');
cy.contains(unassigned).should('exist');
});
});
context(`when there are multiple custom projects selected in the
filter (including the unassigned project)`, () => {
beforeEach(() => {
cy.applyProjectsFilter([unassigned, project1Name, project2Name]);
if (Cypress.$('app-welcome-modal').length) { // zero length means not found
cy.get('[data-cy=close-x]').click();
}
});
it('can create a team with multiple projects', () => {
const projectSummary = '2 projects';
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(teamIDWithSomeProjects);
cy.get('[data-cy=id-label]').contains(teamIDWithSomeProjects);
// initial state of dropdown
cy.get(`${projectDropdownPrefix} #resources-selected`).contains(unassigned);
cy.get(`${projectDropdownPrefix} .dropdown-button`).should('not.have.attr', 'disabled');
// open projects dropdown
cy.get(`${projectDropdownPrefix} .dropdown-button`).click();
// dropdown contains both custom projects, click them both
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project1Name}"]`)
.should('have.attr', 'aria-checked', 'false').click();
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project2Name}"]`)
.should('have.attr', 'aria-checked', 'false').click();
// close projects dropdown
cy.get(`${projectDropdownPrefix} .dropdown-button`).click();
cy.get(`${projectDropdownPrefix} #resources-selected`)
.contains(projectSummary);
// save team
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal').should('not.be.visible');
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
cy.contains(teamIDWithSomeProjects).should('exist');
cy.contains(projectSummary).should('exist');
});
it('can create a team with one project selected', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(teamIDWithOneProject);
cy.get('[data-cy=id-label]').contains(teamIDWithOneProject);
// initial state of dropdown
cy.get(`${projectDropdownPrefix} #resources-selected`).contains(unassigned);
cy.get(`${projectDropdownPrefix} .dropdown-button`).should('not.have.attr', 'disabled');
// open projects dropdown
cy.get(`${projectDropdownPrefix} .dropdown-button`).click();
// dropdown contains both custom projects, click one
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project1Name}"]`)
.should('have.attr', 'aria-checked', 'false');
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project2Name}"]`)
.should('have.attr', 'aria-checked', 'false').click();
// close projects dropdown
cy.get(`${projectDropdownPrefix} .dropdown-button`).click();
cy.get(`${projectDropdownPrefix} #resources-selected`)
.contains(`${project2Name.substring(0, dropdownNameUntilEllipsisLen)}...`);
// save team
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management chef-modal').should('not.be.visible');
cy.get('#main-content-wrapper').scrollTo('top');
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
// TODO: find row
cy.contains(teamIDWithOneProject).should('exist');
cy.contains(project2ID).should('exist');
});
it('can create a team with no projects selected (unassigned)', () => {
cy.get('[data-cy=team-create-button]').contains('Create Team').click();
cy.get('app-team-management chef-modal').should('exist');
cy.get('[data-cy=create-name]').type(unassignedTeam2ID);
cy.get('[data-cy=id-label]').contains(unassignedTeam2ID);
// initial state of dropdown
cy.get(`${projectDropdownPrefix} #resources-selected`).contains(unassigned);
cy.get(`${projectDropdownPrefix} .dropdown-button`).should('not.have.attr', 'disabled');
// open projects dropdown
cy.get(`${projectDropdownPrefix} .dropdown-button`).click();
// dropdown contains both custom projects, none clicked
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project1Name}"]`)
.should('have.attr', 'aria-checked', 'false');
cy.get(`${projectDropdownPrefix} chef-checkbox[title="${project2Name}"]`)
.should('have.attr', 'aria-checked', 'false');
// close projects dropdown
cy.get('app-projects-dropdown .dropdown-button').click();
cy.get('app-projects-dropdown #resources-selected').contains(unassigned);
// save team
cy.get('[data-cy=save-button]').click();
cy.get('app-team-management app-team-management chef-modal').should('not.be.visible');
cy.get('#main-content-wrapper').scrollTo('top');
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
// TODO: find row
cy.contains(unassignedTeam2ID).should('exist');
cy.contains(unassigned).should('exist');
});
});
});
}); | the_stack |
import { CSSAttribute, css } from '../styles';
import { SerpHandler } from '../types';
import { handleSerp, hasDarkBackground, insertElement } from './helpers';
function getURLFromPing(selector: string): (root: HTMLElement) => string | null {
return root => {
const a = selector ? root.querySelector(selector) : root;
if (!(a instanceof HTMLAnchorElement) || !a.ping) {
return null;
}
try {
return new URL(a.ping, window.location.href).searchParams.get('url');
} catch {
return null;
}
};
}
function getURLFromQuery(selector: string): (root: HTMLElement) => string | null {
return root => {
const a = selector ? root.querySelector(selector) : root;
if (!(a instanceof HTMLAnchorElement)) {
return null;
}
const url = a.href;
if (!url) {
return null;
}
const u = new URL(url);
return u.origin === window.location.origin
? u.pathname === '/url'
? u.searchParams.get('q')
: u.pathname === '/imgres' || u.pathname === '/search'
? null
: url
: url;
};
}
const mobileGlobalStyle: CSSAttribute = {
'[data-ub-blocked="visible"]': {
backgroundColor: 'var(--ub-block-color, rgba(255, 192, 192, 0.5)) !important',
},
'.ub-button': {
color: 'var(--ub-link-color, rgb(25, 103, 210))',
},
};
const mobileColoredControlStyle: CSSAttribute = {
color: 'rgba(0, 0, 0, 0.54)',
};
const mobileRegularControlStyle: CSSAttribute = {
...mobileColoredControlStyle,
borderRadius: '8px',
boxShadow: '0 1px 6px rgba(32, 33, 36, 0.28)',
display: 'block',
marginBottom: '10px',
padding: '11px 16px',
};
const mobileImageControlStyle: CSSAttribute = {
...mobileColoredControlStyle,
backgroundColor: 'white',
borderRadius: '8px',
boxShadow: '0 1px 6px rgba(32, 33, 36, 0.18)',
display: 'block',
margin: '0 8px 10px',
padding: '11px 16px',
};
const mobileRegularActionStyle: CSSAttribute = {
display: 'block',
padding: '0 16px 12px',
};
const iOSButtonStyle: CSSAttribute = {
'& .ub-button': {
color: 'var(--ub-link-color, #1558d6)',
},
'[data-ub-dark="1"] & .ub-button': {
color: 'var(--ub-link-color, #609beb)',
},
};
const mobileSerpHandlers: Record<string, SerpHandler> = {
// All
'': handleSerp({
globalStyle: {
...mobileGlobalStyle,
'[data-ub-blocked] .ZINbbc, [data-ub-highlight] .ZINbbc, [data-ub-blocked] .D9l01, [data-ub-highlight] .D9l01':
{
backgroundColor: 'transparent !important',
},
},
controlHandlers: [
{
target: '#taw',
position: 'afterbegin',
style: root => {
const controlClass = css({
display: 'block',
fontSize: '14px',
padding: '12px 16px',
...iOSButtonStyle,
});
root.className = `mnr-c ${controlClass}`;
},
},
{
target: '#main > div:nth-child(4)',
position: 'beforebegin',
style: mobileRegularControlStyle,
},
],
entryHandlers: [
// Regular (iOS)
{
target: '.mnr-c.xpd',
level: target =>
// Web Result with Site Links
target.parentElement?.closest<HTMLElement>('.mnr-c.g') ||
(target.querySelector('.mnr-c.xpd') ? null : target),
url: getURLFromPing('a'),
title: '[role="heading"][aria-level="3"]',
actionTarget: '',
actionStyle: {
display: 'block',
fontSize: '14px',
padding: '0 16px 12px 16px',
...iOSButtonStyle,
},
},
// Video (iOS)
{
target: '.mnr-c.PHap3c',
url: getURLFromPing('a'),
title: '[role="heading"][aria-level="3"]',
actionTarget: '',
actionStyle: {
display: 'block',
fontSize: '14px',
marginTop: '12px',
padding: '0 16px',
...iOSButtonStyle,
},
},
// YouTube Channel (iOS)
{
target: '.XqIXXe > .mnr-c h3 > a',
level: '.mnr-c',
url: getURLFromPing('h3 > a'),
title: 'h3',
actionTarget: '',
actionStyle: {
display: 'block',
fontSize: '14px',
padding: '0 16px 12px 16px',
...iOSButtonStyle,
},
},
// Regular, Featured Snippet, Video
{
target: '.xpd',
url: getURLFromQuery(':scope > .kCrYT > a'),
title: '.vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
// Latest, Top Story (Horizontal), Twitter Search
{
target: '.BVG0Nb',
level: target => (target.closest('.xpd')?.querySelector('.AzGoi') ? null : target),
url: getURLFromQuery(''),
title: '.s3v9rd, .vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
// People Also Ask
{
target: '.xpc > .qxDOhb > div',
level: 2,
url: getURLFromQuery('.kCrYT > a'),
title: '.vvjwJb',
actionTarget: '.xpd',
actionStyle: mobileRegularActionStyle,
},
// Top Story (Vertical)
{
target: '.X7NTVe',
url: getURLFromQuery('.tHmfQe:last-child'), // `:last-child` avoids "Authorized vaccines"
title: '.deIvCb',
actionTarget: '.tHmfQe',
actionStyle: {
display: 'block',
paddingTop: '12px',
},
},
// Twitter
{
target: '.xpd',
level: target =>
target.querySelector(':scope > div:first-child > a > .kCrYT') ? target : null,
url: getURLFromQuery('a'),
title: '.vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
],
pagerHandlers: [
// iOS
{
target: '[id^="arc-srp_"] > div',
innerTargets: '.mnr-c',
},
],
}),
// Books
bks: handleSerp({
globalStyle: mobileGlobalStyle,
controlHandlers: [
{
target: '#main > div:nth-child(4)',
position: 'beforebegin',
style: mobileRegularControlStyle,
},
],
entryHandlers: [
{
target: '.xpd',
url: '.kCrYT > a',
title: '.vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
],
}),
// Images
isch: handleSerp({
globalStyle: {
...mobileGlobalStyle,
'[data-ub-blocked="visible"] .iKjWAf': {
backgroundColor: 'transparent !important',
},
},
controlHandlers: [
{
target: '.T1diZc',
position: 'afterbegin',
style: {
backgroundColor: '#fff',
color: '#4d5156',
display: 'block',
fontSize: '12px',
marginBottom: '19px',
padding: '4px 12px 12px',
'[data-ub-dark="1"] &': {
backgroundColor: '#303134',
color: '#e8eaed',
},
...iOSButtonStyle,
},
},
{
target: '.dmFHw',
position: 'beforebegin',
style: mobileImageControlStyle,
},
{
target: '#uGbavf',
position: target =>
document.querySelector('.dmFHw') ? null : insertElement('span', target, 'beforebegin'),
style: mobileImageControlStyle,
},
],
entryHandlers: [
{
target: '.isv-r, .isv-r > .VFACy',
level: '.isv-r',
url: '.VFACy',
title: root => {
const a = root.querySelector<HTMLElement>('.VFACy');
return a?.firstChild?.textContent ?? null;
},
actionTarget: '',
actionStyle: {
display: 'block',
fontSize: '12px',
margin: '-8px 0 8px',
overflow: 'hidden',
padding: '0 4px',
position: 'relative',
...iOSButtonStyle,
},
},
{
target: '.isv-r',
url: getURLFromQuery('.iKjWAf'),
title: '.mVDMnf',
actionTarget: '',
actionStyle: {
display: 'block',
fontSize: '11px',
lineHeight: '20px',
margin: '-4px 0 4px',
padding: '0 4px',
},
},
],
}),
// News
nws: handleSerp({
globalStyle: mobileGlobalStyle,
controlHandlers: [
{
target: '#taw',
position: 'afterbegin',
style: root => {
const controlClass = css({
display: 'block',
fontSize: '12px',
padding: '12px',
...iOSButtonStyle,
});
root.className = `mnr-c ${controlClass}`;
},
},
{
target: '#main > div:nth-child(4)',
position: 'beforebegin',
style: mobileRegularControlStyle,
},
],
entryHandlers: [
{
target: '.S1FAPd',
level: '.WlydOe',
url: getURLFromPing(''),
title: '[role="heading"][aria-level="3"]',
actionTarget: '.S1FAPd',
actionStyle: {
display: 'inline-block',
fontSize: '12px',
marginLeft: '4px',
width: 0,
...iOSButtonStyle,
},
},
{
target: '.xpd',
url: getURLFromQuery('.kCrYT > a'),
title: '.vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
],
}),
// Videos
vid: handleSerp({
globalStyle: {
'.ucBsPc': {
height: '108px',
},
...mobileGlobalStyle,
},
controlHandlers: [
{
target: '#taw',
position: 'afterbegin',
style: root => {
const controlClass = css({
display: 'block',
fontSize: '12px',
padding: '12px',
...iOSButtonStyle,
});
root.className = `mnr-c ${controlClass}`;
},
},
{
target: '#main > div:nth-child(4)',
position: 'beforebegin',
style: mobileRegularControlStyle,
},
],
entryHandlers: [
{
target: 'video-voyager',
url: 'a',
title: '.V82bz',
actionTarget: '.b5ZQcf',
actionStyle: {
display: 'block',
fontSize: '12px',
marginTop: '4px',
...iOSButtonStyle,
},
},
{
target: '.xpd',
url: getURLFromQuery('.kCrYT > a'),
title: '.vvjwJb',
actionTarget: '',
actionStyle: mobileRegularActionStyle,
},
],
pagerHandlers: [
// iOS
{
target: '[id^="arc-srp_"] > div',
innerTargets: 'video-voyager',
},
],
}),
};
export function getMobileSerpHandler(tbm: string): SerpHandler | null {
const serpHandler = mobileSerpHandlers[tbm];
if (!serpHandler) {
return null;
}
if (tbm === 'isch') {
const inspectBodyStyle = () => {
if (!document.body) {
return;
}
if (hasDarkBackground(document.body)) {
document.documentElement.dataset.ubDark = '1';
} else {
delete document.documentElement.dataset.ubDark;
}
};
const observeStyleElement = (styleElement: HTMLStyleElement): void => {
new MutationObserver(() => inspectBodyStyle()).observe(styleElement, { childList: true });
};
return {
...serpHandler,
onSerpStart() {
inspectBodyStyle();
const styleElement = document.querySelector<HTMLStyleElement>(
'style[data-href^="https://www.gstatic.com"]',
);
if (styleElement) {
observeStyleElement(styleElement);
}
return serpHandler.onSerpStart();
},
onSerpElement(element: HTMLElement) {
if (
element instanceof HTMLStyleElement &&
element.dataset.href?.startsWith('https://www.gstatic.com')
) {
inspectBodyStyle();
observeStyleElement(element);
} else if (element === document.body) {
inspectBodyStyle();
}
return serpHandler.onSerpElement(element);
},
getDialogTheme() {
return document.documentElement.dataset.ubDark === '1' ? 'dark' : 'light';
},
};
} else {
return {
...serpHandler,
onSerpStart() {
if (document.querySelector('meta[name="color-scheme"][content="dark"]')) {
document.documentElement.dataset.ubDark = '1';
}
return serpHandler.onSerpStart();
},
onSerpElement(element) {
if (
element instanceof HTMLMetaElement &&
element.name === 'color-scheme' &&
element.content === 'dark'
) {
document.documentElement.dataset.ubDark = '1';
}
return serpHandler.onSerpElement(element);
},
getDialogTheme() {
return document.documentElement.dataset.ubDark === '1' ? 'dark' : 'light';
},
};
}
} | the_stack |
import * as uuid from 'uuid';
import * as Tp from 'thingpedia';
import { ObjectSet } from 'thingpedia';
import { SchemaRetriever } from 'thingtalk';
import { AbstractDatabase } from '../db';
import SyncDatabase from '../db/syncdb';
import SyncManager from '../sync/manager';
// check for updates of all devices every 3 hours
// this is to catch bug fixes quickly
// we'll lower this to 24 hours after the alpha release
const UPDATE_FREQUENCY = 3 * 3600 * 1000;
/**
* The collection of all configured Thingpedia devices.
*/
export default class DeviceDatabase extends ObjectSet.Base<Tp.BaseDevice> {
private _factory : Tp.DeviceFactory;
private schemas : SchemaRetriever;
private _devices : Map<string, Tp.BaseDevice>;
private _byDescriptor : Map<string, Tp.BaseDevice>;
private _syncManager : SyncManager;
private _syncdb : SyncDatabase<"device">;
private _subdeviceAddedListener : (device : Tp.BaseDevice) => void;
private _subdeviceRemovedListener : (device : Tp.BaseDevice) => void;
private _objectAddedHandler : (uniqueId : string, row : any) => void;
private _objectDeletedHandler : (uniqueId : string) => void;
private _isUpdatingState : boolean;
private _updateTimer : NodeJS.Timeout|null;
/**
* Construct the device database for this engine.
*
* There is only one device database instance per engine,
* and it is accessible as {@link AssistantEngine.devices}.
*
* @param platform - the platform associated with the engine
* @param syncManager - the tier manager to use for device synchronization
* @param factory - the factory to load and construct Thingpedia devices
* @param schemas - the schema retriever to typecheck ThingTalk code
* @internal
*/
constructor(platform : Tp.BasePlatform,
db : AbstractDatabase,
syncManager : SyncManager,
factory : Tp.DeviceFactory,
schemas : SchemaRetriever) {
super();
this.setMaxListeners(0);
this._factory = factory;
this.schemas = schemas;
this._devices = new Map;
this._byDescriptor = new Map;
this._syncManager = syncManager;
this._syncdb = new SyncDatabase(platform, db, 'device', syncManager);
this._subdeviceAddedListener = this._notifySubdeviceAdded.bind(this);
this._subdeviceRemovedListener = this._notifySubdeviceRemoved.bind(this);
this._objectAddedHandler = this._onObjectAdded.bind(this);
this._objectDeletedHandler = this._onObjectDeleted.bind(this);
this._isUpdatingState = false;
this._updateTimer = null;
}
async loadOneDevice(serializedDevice : Tp.BaseDevice.DeviceState & { uniqueId ?: string },
addToDB : boolean) {
if (addToDB)
console.log('loadOneDevice(..., true) is deprecated; from inside a BaseDevice, return the instance directly; from a platform layer, use addDevice');
const uniqueId = serializedDevice.uniqueId!;
delete serializedDevice.uniqueId;
try {
const device = await this._factory.loadSerialized(serializedDevice.kind, serializedDevice);
return await this._addDeviceInternal(device, uniqueId, addToDB);
} catch(e) {
console.error('Failed to load device ' + uniqueId + ': ' + e);
console.error(e.stack);
if (addToDB)
throw e;
else
await this._syncdb.deleteOne(uniqueId);
return null;
}
}
async start() {
this._syncdb.on('object-added', this._objectAddedHandler);
this._syncdb.on('object-deleted', this._objectDeletedHandler);
this._syncdb.open();
const rows = await this._syncdb.getAll();
await Promise.all(rows.map(async (row : any) => {
try {
const serializedDevice = JSON.parse(row.state);
serializedDevice.uniqueId = row.uniqueId;
await this.loadOneDevice(serializedDevice, false);
} catch(e) {
console.error('Failed to load one device: ' + e);
}
}));
this._updateTimer = setInterval(() => this._updateAll(), UPDATE_FREQUENCY);
}
private _onObjectAdded(uniqueId : string, row : any) {
const serializedDevice = JSON.parse(row.state);
if (this._devices.has(uniqueId)) {
this._isUpdatingState = true;
this._devices.get(uniqueId)!.updateState(serializedDevice);
this._isUpdatingState = false;
} else {
serializedDevice.uniqueId = uniqueId;
this.loadOneDevice(serializedDevice, false);
}
}
private _onObjectDeleted(uniqueId : string) {
const device = this._devices.get(uniqueId);
if (device !== undefined) {
this._removeDeviceFromCache(device);
this._notifyDeviceRemoved(device);
}
}
async stop() {
await this._syncdb.close();
if (this._updateTimer)
clearInterval(this._updateTimer);
this._updateTimer = null;
await Promise.all(this.values().map(async (device) => {
if (device.ownerTier === this._syncManager.ownTier + this._syncManager.ownIdentity ||
device.ownerTier === 'global') {
try {
await device.stop();
} catch(e) {
console.error('Device failed to stop: ' + e.message);
console.error(e.stack);
}
}
}));
}
// return all devices directly stored in the database
values() {
return Array.from(this._devices.values());
}
private _getValuesOfExactKind(kind : string) {
return this.values().filter((d) => d.kind === kind);
}
/**
* Return all devices, and expand collection devices into concrete devices.
*
* The result of this call might change without an object-added/object-removed
* event. Use DeviceView to track all the devices that match a selector.
*
* @param kind - if specified, only devices with `hasKind(kind)` will be returned.
* */
getAllDevices(kind ?: string) {
const devices : Tp.BaseDevice[] = [];
function addContext(ctx : Tp.ObjectSet.Base<Tp.BaseDevice>) {
for (const d of ctx.values()) {
if (kind === undefined || d.hasKind(kind))
devices.push(d);
try {
const subview = d.queryInterface('subdevices');
if (subview !== null)
addContext(subview);
} catch(e) {
console.error('Failed to query device ' + d.uniqueId + ' for subdevices', e);
}
}
}
addContext(this);
return devices;
}
getAllDevicesOfKind(kind ?: string) {
return this.getAllDevices(kind);
}
getDeviceByDescriptor(descriptor : string) {
return this._byDescriptor.get(descriptor);
}
private _notifySubdeviceAdded(subdevice : Tp.BaseDevice) {
// emit only device-added, not object-added
//
// object-added is used for cloud synchronization,
// and refers only to objects in the top-most level
// of the device tree; it pairs with .values()
// object-added is also used by DeviceView, which
// does its subdevice tracking
//
// device-added is used by the UI layers for
// My Goods, and provides a flat view of all devices;
// it pairs with getAllDevices(), which is also flat
this.emit('device-added', subdevice);
// recursively check for subdevices
const subsubdevices = subdevice.queryInterface('subdevices');
if (subsubdevices !== null)
this._startSubdevices(subsubdevices);
}
private _notifySubdeviceRemoved(subdevice : Tp.BaseDevice) {
this.emit('device-removed', subdevice);
// recursively check for subdevices
const subsubdevices = subdevice.queryInterface('subdevices');
if (subsubdevices !== null)
this._stopSubdevices(subsubdevices);
}
private _startSubdevices(subdevices : Tp.ObjectSet.Base<Tp.BaseDevice>) {
subdevices.on('object-added', this._subdeviceAddedListener);
subdevices.on('object-removed', this._subdeviceRemovedListener);
for (const subdevice of subdevices.values())
this._notifySubdeviceAdded(subdevice);
}
private _stopSubdevices(subdevices : Tp.ObjectSet.Base<Tp.BaseDevice>) {
subdevices.removeListener('object-added', this._subdeviceAddedListener);
subdevices.removeListener('object-removed', this._subdeviceRemovedListener);
for (const subdevice of subdevices.values())
this._notifySubdeviceRemoved(subdevice);
}
private async _notifyDeviceAdded(device : Tp.BaseDevice) {
console.log('Added device ' + device.uniqueId);
// for compat, emit it first
this.emit('device-added', device);
this.objectAdded(device);
const subdevices = device.queryInterface('subdevices');
if (subdevices !== null)
this._startSubdevices(subdevices);
if (device.ownerTier === this._syncManager.ownTier + this._syncManager.ownIdentity ||
device.ownerTier === 'global')
await device.start();
return device;
}
private async _notifyDeviceRemoved(device : Tp.BaseDevice) {
this.emit('device-removed', device);
this.objectRemoved(device);
const subdevices = device.queryInterface('subdevices');
if (subdevices !== null)
this._stopSubdevices(subdevices);
if (device.ownerTier === this._syncManager.ownTier + this._syncManager.ownIdentity ||
device.ownerTier === 'global') {
try {
await device.stop();
} catch(e) {
console.error('Device failed to stop: ' + e.message);
console.error(e.stack);
}
}
}
private async _saveDevice(device : Tp.BaseDevice) {
this.emit('device-changed', device);
if (device.isTransient)
return;
const state = device.serialize();
const uniqueId = device.uniqueId!;
await this._syncdb.insertOne(uniqueId, { state: JSON.stringify(state) });
}
private async _addDeviceInternal(device : Tp.BaseDevice, uniqueId : string|undefined, addToDB : boolean) {
if (device.uniqueId === undefined) {
if (uniqueId === undefined)
device.uniqueId = device.kind + '-' + uuid.v4();
else
device.uniqueId = uniqueId;
} else {
if (uniqueId !== undefined &&
device.uniqueId !== uniqueId)
throw new Error('Device unique id is different from stored value (old ' + uniqueId + ', new ' + device.uniqueId + ')');
}
if (this._devices.has(device.uniqueId)) {
const existing = this._devices.get(device.uniqueId)!;
this._isUpdatingState = true;
existing.updateState(device.serialize());
this._isUpdatingState = false;
await this._saveDevice(device);
return existing;
}
device.on('state-changed', () => {
if (this._isUpdatingState)
return;
this._saveDevice(device);
});
this._devices.set(device.uniqueId, device);
device.descriptors.forEach((descriptor) => {
this._byDescriptor.set(descriptor, device);
});
if (addToDB)
await this._saveDevice(device);
return this._notifyDeviceAdded(device);
}
async addDevice(device : Tp.BaseDevice) {
// Check if the device was already added, if so, do nothing
// This is compatibility code to handle both the old and the new way to configure devices:
// the old way required each device to add themselves to the database,
// in the new way the device just configures itself and expects the calling
// code to save it
if (device.uniqueId !== undefined && this._devices.get(device.uniqueId) === device)
return;
await this._addDeviceInternal(device, undefined, true);
}
async addSerialized(state : Tp.BaseDevice.DeviceState) {
const instance = await this._factory.loadSerialized(state.kind, state);
await this.addDevice(instance);
return instance;
}
addFromOAuth(kind : string) {
return this._factory.loadFromOAuth(kind);
}
async completeOAuth(kind : string, url : string, session : Record<string, string>) {
const instance = await this._factory.completeOAuth(kind, url, session);
if (!instance)
return null;
await this.addDevice(instance);
return instance;
}
addFromDiscovery(kind : string, publicData : Record<string, unknown>, privateData : Record<string, unknown>) {
return this._factory.loadFromDiscovery(kind, publicData, privateData);
}
async completeDiscovery(instance : Tp.BaseDevice, delegate : Tp.ConfigDelegate) {
await instance.completeDiscovery(delegate);
await this.addDevice(instance);
return instance;
}
async addInteractively(kind : string, delegate : Tp.ConfigDelegate) {
const instance = await this._factory.loadInteractively(kind, delegate);
await this.addDevice(instance);
return instance;
}
private _removeDeviceFromCache(device : Tp.BaseDevice) {
this._devices.delete(device.uniqueId!);
device.descriptors.forEach((descriptor) => {
this._byDescriptor.delete(descriptor);
});
}
async removeDevice(device : Tp.BaseDevice) {
this._removeDeviceFromCache(device);
if (!device.isTransient)
await this._syncdb.deleteOne(device.uniqueId!);
return this._notifyDeviceRemoved(device);
}
hasDevice(uniqueId : string) {
return this._devices.has(uniqueId);
}
getDevice(uniqueId : string) {
return this._devices.get(uniqueId);
}
async reloadDevice(device : Tp.BaseDevice) {
const state = device.serialize();
await this._removeDeviceFromCache(device);
await this._notifyDeviceRemoved(device);
await this.loadOneDevice(state, false);
}
getCachedDeviceClasses() {
return this._factory.getCachedDeviceClasses();
}
async updateDevicesOfKind(kind : string) {
this.schemas.removeFromCache(kind);
await this._factory.updateDeviceClass(kind);
await this._reloadAllDevices(kind);
}
private async _reloadAllDevices(kind : string) {
const devices = this._getValuesOfExactKind(kind);
return Promise.all(devices.map((d) => {
return this.reloadDevice(d);
}));
}
private async _updateAll() {
const kinds = new Map; // from kind to version
for (const dev of this._devices.values())
kinds.set(dev.kind, (dev.constructor as typeof Tp.BaseDevice).metadata.version);
for (const [kind, oldVersion] of kinds) {
if (kind.startsWith('org.thingpedia.builtin'))
continue;
this.schemas.removeFromCache(kind);
await this._factory.updateDeviceClass(kind);
const newClass = await this._factory.getDeviceClass(kind);
if (newClass.metadata.version !== oldVersion)
await this._reloadAllDevices(kind);
}
}
} | the_stack |
import {NeovimElement, Neovim} from 'neovim-component';
import {remote, shell, ipcRenderer as ipc} from 'electron';
import {join, basename} from 'path';
import {readdirSync} from 'fs';
import {Nvim, RPCValue} from 'promised-neovim-client';
class ComponentLoader {
initially_loaded: boolean;
component_paths: string[];
nyaovim_plugin_paths: string[];
constructor() {
this.initially_loaded = false;
this.component_paths = [];
}
loadComponent(path: string) {
const link: HTMLLinkElement = document.createElement('link');
link.rel = 'import';
link.href = path;
document.head.appendChild(link);
this.component_paths.push(path);
}
loadPluginDir(dir: string) {
const nyaovim_plugin_dir = join(dir, 'nyaovim-plugin');
try {
for (const entry of readdirSync(nyaovim_plugin_dir)) {
if (entry.endsWith('.html')) {
this.loadComponent(join(nyaovim_plugin_dir, entry));
}
}
this.nyaovim_plugin_paths.push(dir);
} catch (err) {
// 'nyaovim-plugin' doesn't exist
}
}
loadFromRTP(runtimepaths: string[]) {
for (const rtp of runtimepaths) {
this.loadPluginDir(rtp);
}
}
}
class RuntimeApi {
private client: Nvim;
constructor(private readonly definitions: {[name: string]: (...args: any[]) => void}) {
this.client = null;
}
subscribe(client: Nvim) {
client.on('notification', this.call.bind(this));
for (const name in this.definitions) {
client.subscribe(name).catch();
}
this.client = client;
}
unsubscribe() {
if (this.client) {
for (const name in this.definitions) {
this.client.unsubscribe(name);
}
}
}
call(func_name: string, args: RPCValue[]) {
const func = this.definitions[func_name];
if (!func) {
return null;
}
return func.apply(func, args);
}
}
const component_loader = new ComponentLoader();
const ThisBrowserWindow = remote.getCurrentWindow();
const runtime_api = new RuntimeApi({
'nyaovim:load-path': (html_path: string) => {
component_loader.loadComponent(html_path);
},
'nyaovim:load-plugin-dir': (dir_path: string) => {
component_loader.loadPluginDir(dir_path);
},
'nyaovim:edit-start': (file_path: string) => {
ThisBrowserWindow.setRepresentedFilename(file_path);
remote.app.addRecentDocument(file_path);
},
'nyaovim:require-script-file': (script_path: string) => {
require(script_path);
},
'nyaovim:call-global-function': (func_name: string, args: RPCValue[]) => {
const func = (window as any)[func_name];
if (func /*&& func is Function*/) {
func.apply(window, args);
}
},
'nyaovim:open-devtools': (mode: 'right' | 'bottom' | 'undocked' | 'detach') => {
const contents = remote.getCurrentWebContents();
contents.openDevTools({mode});
},
'nyaovim:execute-javascript': (code: string) => {
if (typeof code !== 'string') {
console.error('nyaovim:execute-javascript: Not a string', code);
return;
}
try {
/* tslint:disable */
eval(code);
/* tslint:enable */
} catch (e) {
console.error('While executing javascript:', e, ' Code:', code);
}
},
'nyaovim:browser-window': (method: string, args: RPCValue[]) => {
try {
(ThisBrowserWindow as any)[method].apply(ThisBrowserWindow, args);
} catch (e) {
console.error("Error while executing 'nyaovim:browser-window':", e, ' Method:', method, ' Args:', args);
}
},
});
function prepareIpc(client: Nvim) {
ipc.on('nyaovim:exec-commands', (_: any, cmds: string[]) => {
for (const c of cmds) {
client.command(c);
}
});
ipc.on('nyaovim:copy', () => {
// get current vim mode
client.eval('mode()').then((value: string) => {
if (value.length === 0) {
return undefined;
}
const ch = value[0];
const code = value.charCodeAt(0);
if (ch === 'v' // visual mode
|| ch === 'V' // visual line mode
|| code === 22 // visual block mode. 22 is returned by ':echo char2nr("\<C-v>")'
) {
client.input('"+y');
}
});
});
ipc.on('nyaovim:select-all', () => {
// get current vim mode.
client.eval('mode()').then((value: string) => {
if (value.length === 0) {
return undefined;
}
const command = value[0] === 'n' ? 'ggVG' : '<Esc>ggVG';
client.input(command);
});
});
ipc.on('nyaovim:cut', () => {
// get current vim mode
client.eval('mode()').then((value: string) => {
if (value.length === 0) {
return undefined;
}
const ch = value[0];
const num = value.charCodeAt(0);
if (ch === 'v' // visual mode
|| ch === 'V' // visual line mode
|| num === 22 // visual block mode
) {
client.input('"+x');
}
});
});
ipc.on('nyaovim:paste', () => {
// get current vim mode
client.eval('mode()').then((value: string) => {
if (value.length === 0) {
return undefined;
}
let command: string;
const ch = value[0];
const code = value.charCodeAt(0);
if (ch === 'v') {
// visual mode
// deleting the highlighted area
// to prevent vim from copying the area to the pasteboard
command = '"_d"+P';
} else if (ch === 'V') {
// visual line mode
command = '"_d"+p';
} else if (code === 22 || ch === 'n') {
// visual block mode
// the "_d trick doesn't work here
// because the visual selection will disappear after "_d command
// or normal mode
command = '"+p';
} else if (ch === 'i') {
// insert mode
// gp will move cursor to the last of pasted content
command = '"+gp';
} else if (ch === 'c') {
// command line mode
command = '<C-r>+';
}
if (command) {
client.command(`normal! ${command}`);
}
});
});
}
class NyaoVimApp extends Polymer.Element {
static get is() {
return 'nyaovim-app';
}
static get properties() {
return {
argv: {
type: Array,
value() {
// Handle the arguments of the standalone Nyaovim.app
// The first argument of standalone distribution is the binary path
let electron_argc = 1;
// When application is executed via 'electron' ('Electron' on darwin) executable.
if ('electron' === basename(remote.process.argv[0]).toLowerCase()) {
// Note:
// The first argument is a path to Electron executable.
// The second argument is the path to main.js
electron_argc = 2;
}
// Note:
// First and second arguments are related to Electron
// XXX:
// Spectron additionally passes many specific arguments to process and 'nvim' process
// will fail because of them. As a workaround, we stupidly ignore arguments on E2E tests.
const a = process.env.NYAOVIM_E2E_TEST_RUNNING ? [] : remote.process.argv.slice(electron_argc);
a.unshift(
'--cmd', `let\ g:nyaovim_version="${remote.app.getVersion()}"`,
'--cmd', `set\ rtp+=${join(__dirname, '..', 'runtime').replace(' ', '\ ')}`,
);
// XXX:
// Swap files are disabled because it shows message window on start up but frontend can't detect it.
a.unshift('-n');
return a;
},
},
editor: Object,
};
}
argv: string[];
editor: Neovim;
ready() {
super.ready();
(global as any).hello = this;
const element = this.$['nyaovim-editor'] as NeovimElement;
const editor = element.editor;
editor.on('error', (err: Error) => alert(err.message));
editor.on('quit', () => ThisBrowserWindow.close());
this.editor = editor;
editor.store.on('beep', () => shell.beep());
editor.store.on('title-changed', () => {
document.title = editor.store.title;
});
editor.on('process-attached', () => {
const client = editor.getClient();
client.listRuntimePaths()
.then((rtp: string[]) => {
component_loader.loadFromRTP(rtp);
component_loader.initially_loaded = true;
});
runtime_api.subscribe(client);
element.addEventListener('drop', e => {
e.preventDefault();
const f = e.dataTransfer.files[0];
if (f) {
client.command('edit! ' + f.path);
}
});
remote.app.on('open-file', (e: Event, p: string) => {
e.preventDefault();
client.command('edit! ' + p);
});
prepareIpc(client);
});
element.addEventListener('dragover', e => e.preventDefault());
window.addEventListener('keydown', e => {
if (e.keyCode === 0x1b && !editor.store.focused) {
// Note: Global shortcut to make focus back to screen
editor.focus();
}
});
}
// TODO: Remove all listeners when detached
}
customElements.define(NyaoVimApp.is, NyaoVimApp); | the_stack |
import {
applyBindings
} from '@tko/bind'
import {
computed
} from '@tko/computed'
import {
observable
} from '@tko/observable'
import {
triggerEvent, options
} from '@tko/utils'
import { DataBindProvider } from '@tko/provider.databind'
import { bindings as coreBindings } from '../dist'
const DEBUG = true
import '@tko/utils/helpers/jasmine-13-helper'
describe('Binding: TextInput', function () {
var bindingHandlers
beforeEach(jasmine.prepareTestNode)
beforeEach(function () {
var provider = new DataBindProvider()
options.bindingProviderInstance = provider
bindingHandlers = provider.bindingHandlers
bindingHandlers.set(coreBindings)
})
it('Should assign the value to the node', function () {
testNode.innerHTML = "<input data-bind='textInput:123' />"
applyBindings(null, testNode)
expect(testNode.childNodes[0].value).toEqual('123')
})
it('Should treat null values as empty strings', function () {
testNode.innerHTML = "<input data-bind='textInput:myProp' />"
applyBindings({ myProp: observable(0) }, testNode)
expect(testNode.childNodes[0].value).toEqual('0')
})
it('Should assign an empty string as value if the model value is null', function () {
testNode.innerHTML = "<input data-bind='textInput:(null)' />"
applyBindings(null, testNode)
expect(testNode.childNodes[0].value).toEqual('')
})
it('Should assign an empty string as value if the model value is undefined', function () {
testNode.innerHTML = "<input data-bind='textInput:undefined' />"
applyBindings(null, testNode)
expect(testNode.childNodes[0].value).toEqual('')
})
it('For observable values, should unwrap the value and update on change', function () {
var myObservable = observable(123)
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
expect(testNode.childNodes[0].value).toEqual('123')
myObservable(456)
expect(testNode.childNodes[0].value).toEqual('456')
})
it('For observable values, should update on change if new value is \'strictly\' different from previous value', function () {
var myObservable = observable('+123')
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
expect(testNode.childNodes[0].value).toEqual('+123')
myObservable(123)
expect(testNode.childNodes[0].value).toEqual('123')
})
it('For writeable observable values, should catch the node\'s onchange and write values back to the observable', function () {
var myObservable = observable(123)
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
testNode.childNodes[0].value = 'some user-entered value'
triggerEvent(testNode.childNodes[0], 'change')
expect(myObservable()).toEqual('some user-entered value')
})
it('For writeable observable values, when model rejects change, update view to match', function () {
var validValue = observable(123)
var isValid = observable(true)
var valueForEditing = computed({
read: validValue,
write: function (newValue) {
if (!isNaN(newValue)) {
isValid(true)
validValue(newValue)
} else {
isValid(false)
}
}
})
testNode.innerHTML = "<input data-bind='textInput: valueForEditing' />"
applyBindings({ valueForEditing: valueForEditing }, testNode)
// set initial valid value
testNode.childNodes[0].value = '1234'
triggerEvent(testNode.childNodes[0], 'change')
expect(validValue()).toEqual('1234')
expect(isValid()).toEqual(true)
expect(testNode.childNodes[0].value).toEqual('1234')
// set to an invalid value
testNode.childNodes[0].value = '1234a'
triggerEvent(testNode.childNodes[0], 'change')
expect(validValue()).toEqual('1234')
expect(isValid()).toEqual(false)
expect(testNode.childNodes[0].value).toEqual('1234a')
// set to a valid value where the current value of the writeable computed is the same as the written value
testNode.childNodes[0].value = '1234'
triggerEvent(testNode.childNodes[0], 'change')
expect(validValue()).toEqual('1234')
expect(isValid()).toEqual(true)
expect(testNode.childNodes[0].value).toEqual('1234')
})
it('Should ignore node changes when bound to a read-only observable', function () {
var computedValue = computed(function () { return 'zzz' })
var vm = { prop: computedValue }
testNode.innerHTML = "<input data-bind='textInput: prop' />"
applyBindings(vm, testNode)
expect(testNode.childNodes[0].value).toEqual('zzz')
// Change the input value and trigger change event; verify that the view model wasn't changed
testNode.childNodes[0].value = 'yyy'
triggerEvent(testNode.childNodes[0], 'change')
expect(vm.prop).toEqual(computedValue)
expect(computedValue()).toEqual('zzz')
})
it('For non-observable property values, should catch the node\'s onchange and write values back to the property', function () {
var model = { modelProperty123: 456 }
testNode.innerHTML = "<input data-bind='textInput: modelProperty123' />"
applyBindings(model, testNode)
expect(testNode.childNodes[0].value).toEqual('456')
testNode.childNodes[0].value = 789
triggerEvent(testNode.childNodes[0], 'change')
expect(model.modelProperty123).toEqual('789')
})
it('Should support alias "textinput"', function () {
testNode.innerHTML = "<input data-bind='textinput:123' />"
applyBindings(null, testNode)
expect(testNode.childNodes[0].value).toEqual('123')
})
it('Should write to non-observable property values using "textinput" alias', function () {
var model = { modelProperty123: 456 }
testNode.innerHTML = "<input data-bind='textinput: modelProperty123' />"
applyBindings(model, testNode)
expect(testNode.childNodes[0].value).toEqual('456')
testNode.childNodes[0].value = 789
triggerEvent(testNode.childNodes[0], 'change')
expect(model.modelProperty123).toEqual('789')
})
it('Should be able to read and write to a property of an object returned by a function', function () {
var mySetter = { set: 666 }
var model = {
getSetter: function () {
return mySetter
}
}
testNode.innerHTML =
"<input data-bind='textInput: getSetter().set' />" +
"<input data-bind='textInput: getSetter()[\"set\"]' />" +
"<input data-bind=\"textInput: getSetter()['set']\" />"
applyBindings(model, testNode)
expect(testNode.childNodes[0].value).toEqual('666')
expect(testNode.childNodes[1].value).toEqual('666')
expect(testNode.childNodes[2].value).toEqual('666')
// .property
testNode.childNodes[0].value = 667
triggerEvent(testNode.childNodes[0], 'change')
expect(mySetter.set).toEqual('667')
// ["property"]
testNode.childNodes[1].value = 668
triggerEvent(testNode.childNodes[1], 'change')
expect(mySetter.set).toEqual('668')
// ['property']
testNode.childNodes[0].value = 669
triggerEvent(testNode.childNodes[0], 'change')
expect(mySetter.set).toEqual('669')
})
it('Should be able to write to observable subproperties of an observable, even after the parent observable has changed', function () {
// This spec represents https://github.com/SteveSanderson/knockout/issues#issue/13
var originalSubproperty = observable('original value')
var newSubproperty = observable()
var model = { myprop: observable({ subproperty: originalSubproperty }) }
// Set up a text box whose value is linked to the subproperty of the observable's current value
testNode.innerHTML = "<input data-bind='textInput: myprop().subproperty' />"
applyBindings(model, testNode)
expect(testNode.childNodes[0].value).toEqual('original value')
model.myprop({ subproperty: newSubproperty }) // Note that myprop (and hence its subproperty) is changed *after* the bindings are applied
testNode.childNodes[0].value = 'Some new value'
triggerEvent(testNode.childNodes[0], 'change')
// Verify that the change was written to the *new* subproperty, not the one referenced when the bindings were first established
expect(newSubproperty()).toEqual('Some new value')
expect(originalSubproperty()).toEqual('original value')
})
it('Should update observable on input event (on supported browsers) or propertychange event (on old IE)', function () {
var myObservable = observable(123)
testNode.innerHTML = "<input data-bind='textInput: someProp' />"
applyBindings({ someProp: myObservable }, testNode)
expect(testNode.childNodes[0].value).toEqual('123')
testNode.childNodes[0].value = 'some user-entered value' // setting the value triggers the propertychange event on IE
if (!jasmine.ieVersion || jasmine.ieVersion >= 9) {
triggerEvent(testNode.childNodes[0], 'input')
}
if (jasmine.ieVersion === 9) {
// IE 9 responds to the event asynchronously (see #1788)
waitsFor(function () {
return myObservable() === 'some user-entered value'
}, 50)
} else {
expect(myObservable()).toEqual('some user-entered value')
}
})
it('Should update observable on blur event', function () {
var myobservable = observable(123)
testNode.innerHTML = "<input data-bind='textInput: someProp' /><input />"
applyBindings({ someProp: myobservable }, testNode)
expect(testNode.childNodes[0].value).toEqual('123')
testNode.childNodes[0].focus()
testNode.childNodes[0].value = 'some user-entered value'
testNode.childNodes[1].focus() // focus on a different input to blur the previous one
triggerEvent(testNode.childNodes[0], 'blur')
expect(myobservable()).toEqual('some user-entered value')
})
it('Should write only changed values to model', function () {
var model = { writtenValue: '' }
testNode.innerHTML = "<input data-bind='textInput: writtenValue' />"
applyBindings(model, testNode)
testNode.childNodes[0].value = '1234'
triggerEvent(testNode.childNodes[0], 'change')
expect(model.writtenValue).toEqual('1234')
// trigger change event with the same value
model.writtenValue = undefined
triggerEvent(testNode.childNodes[0], 'change')
expect(model.writtenValue).toBeUndefined()
})
it('Should not write to model other than for user input', function () {
// In html5, the value returned by element.value is normalized and CR characters are transformed,
// See http://www.w3.org/TR/html5/forms.html#the-textarea-element, https://github.com/knockout/knockout/issues/2281
const originalValue = '12345\r\n67890'
const model = { writtenValue: observable(originalValue) }
testNode.innerHTML = "<textarea data-bind='textInput: writtenValue'></textarea>"
applyBindings(model, testNode)
// No user change; verify that model isn't changed (note that the view's value may be different)
triggerEvent(testNode.childNodes[0], 'blur')
expect(model.writtenValue()).toEqual(originalValue)
// A change by the user is written to the model
testNode.childNodes[0].value = '1234'
triggerEvent(testNode.childNodes[0], 'change')
expect(model.writtenValue()).toEqual('1234')
// A change from the model; the model isn't updated even if the view's value is different
model.writtenValue(originalValue)
triggerEvent(testNode.childNodes[0], 'blur')
expect(model.writtenValue()).toEqual(originalValue)
})
if (typeof DEBUG !== 'undefined' && DEBUG) {
// The textInput binds to different events depending on the browser.
// But the DEBUG version allows us to force it to bind to specific events for testing purposes.
describe('Event processing', function () {
beforeEach(function () {
options.debug = true
this.restoreAfter(bindingHandlers.textInput, '_forceUpdateOn')
bindingHandlers.textInput._forceUpdateOn = ['afterkeydown']
jasmine.Clock.useMock()
})
afterEach(function () {
options.debug = false
})
it('Should update observable asynchronously', function () {
var myObservable = observable('123')
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
triggerEvent(testNode.childNodes[0], 'keydown')
testNode.childNodes[0].value = 'some user-entered value'
expect(myObservable()).toEqual('123') // observable is not changed yet
jasmine.Clock.tick(20)
expect(myObservable()).toEqual('some user-entered value') // it's changed after a delay
})
it('Should ignore "unchanged" notifications from observable during delayed event processing', function () {
var myObservable = observable('123')
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
triggerEvent(testNode.childNodes[0], 'keydown')
testNode.childNodes[0].value = 'some user-entered value'
// Notification of previous value (unchanged) is ignored
myObservable.valueHasMutated()
expect(testNode.childNodes[0].value).toEqual('some user-entered value')
// Observable is updated to new element value
jasmine.Clock.tick(20)
expect(myObservable()).toEqual('some user-entered value')
})
it('Should not ignore actual change notifications from observable during delayed event processing', function () {
var myObservable = observable('123')
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings({ someProp: myObservable }, testNode)
triggerEvent(testNode.childNodes[0], 'keydown')
testNode.childNodes[0].value = 'some user-entered value'
// New value is written to input element
myObservable('some value from the server')
expect(testNode.childNodes[0].value).toEqual('some value from the server')
// New value remains when event is processed
jasmine.Clock.tick(20)
expect(myObservable()).toEqual('some value from the server')
})
it('Should update model property using earliest available event', function () {
var model = { someProp: '123' }
testNode.innerHTML = "<input data-bind='textInput:someProp' />"
applyBindings(model, testNode)
triggerEvent(testNode.childNodes[0], 'keydown')
testNode.childNodes[0].value = 'some user-entered value'
triggerEvent(testNode.childNodes[0], 'change')
expect(model.someProp).toEqual('some user-entered value') // it's changed immediately
expect(testNode.childNodes[0]._ko_textInputProcessedEvent).toEqual('change') // using the change event
// even after a delay, the keydown event isn't processed
model.someProp = undefined
jasmine.Clock.tick(20)
expect(model.someProp).toBeUndefined()
expect(testNode.childNodes[0]._ko_textInputProcessedEvent).toEqual('change')
})
})
}
}) | the_stack |
import assert from "assert";
import { ReadableStream } from "stream/web";
import {
KVGetValueType,
KVListOptions,
KVNamespace,
KVPutOptions,
KVPutValueType,
} from "@miniflare/kv";
import {
RequestContext,
Storage,
StoredKeyMeta,
StoredValueMeta,
base64Encode,
} from "@miniflare/shared";
import {
TIME_EXPIRED,
TIME_EXPIRING,
TIME_NOW,
getObjectProperties,
testClock,
utf8Decode,
utf8Encode,
waitsForInputGate,
waitsForOutputGate,
} from "@miniflare/shared-test";
import { MemoryStorage } from "@miniflare/storage-memory";
import anyTest, { Macro, TestInterface, ThrowsExpectation } from "ava";
interface Context {
storage: Storage;
ns: KVNamespace;
}
const test = anyTest as TestInterface<Context>;
test.beforeEach((t) => {
const storage = new MemoryStorage(undefined, testClock);
const ns = new KVNamespace(storage, { clock: testClock });
t.context = { storage, ns };
});
const validatesKeyMacro: Macro<
[
method: string,
httpMethod: string,
func: (ns: KVNamespace, key?: any) => Promise<void>
],
Context
> = async (t, method, httpMethod, func) => {
const { ns } = t.context;
await t.throwsAsync(func(ns), {
instanceOf: TypeError,
message: `Failed to execute '${method}' on 'KvNamespace': parameter 1 is not of type 'string'.`,
});
await t.throwsAsync(func(ns, 0), {
instanceOf: TypeError,
message: `Failed to execute '${method}' on 'KvNamespace': parameter 1 is not of type 'string'.`,
});
await t.throwsAsync(func(ns, ""), {
instanceOf: TypeError,
message: "Key name cannot be empty.",
});
await t.throwsAsync(func(ns, "."), {
instanceOf: TypeError,
message: '"." is not allowed as a key name.',
});
await t.throwsAsync(func(ns, ".."), {
instanceOf: TypeError,
message: '".." is not allowed as a key name.',
});
await t.throwsAsync(func(ns, "".padStart(513, "x")), {
instanceOf: Error,
message: `KV ${httpMethod} failed: 414 UTF-8 encoded length of 513 exceeds key length limit of 512.`,
});
};
validatesKeyMacro.title = (providedTitle, method) => `${method}: validates key`;
const validateGetMacro: Macro<
[func: (ns: KVNamespace, cacheTtl?: number, type?: string) => Promise<void>],
Context
> = async (t, func) => {
const { ns } = t.context;
await t.throwsAsync(func(ns, "not a number" as any), {
instanceOf: Error,
message:
"KV GET failed: 400 Invalid cache_ttl of not a number. Cache TTL must be at least 60.",
});
await t.throwsAsync(func(ns, 10), {
instanceOf: Error,
message:
"KV GET failed: 400 Invalid cache_ttl of 10. Cache TTL must be at least 60.",
});
await t.throwsAsync(func(ns, 120, "map"), {
instanceOf: TypeError,
message:
'Unknown response type. Possible types are "text", "arrayBuffer", "json", and "stream".',
});
};
validateGetMacro.title = (providedTitle) =>
`${providedTitle}: validates get options`;
const getMacro: Macro<
[{ value: string; type?: KVGetValueType; expected: any }],
Context
> = async (t, { value, type, expected }) => {
const { storage, ns } = t.context;
await storage.put("key", { value: utf8Encode(value) });
// Test both ways of specifying the type
t.deepEqual(await ns.get("key", type as any), expected);
t.deepEqual(await ns.get("key", { type: type as any }), expected);
};
getMacro.title = (providedTitle) => `get: gets ${providedTitle}`;
test("text by default", getMacro, {
value: "value",
expected: "value",
});
test("text", getMacro, {
value: "value",
type: "text",
expected: "value",
});
test("json", getMacro, {
value: '{"field":"value"}',
type: "json",
expected: { field: "value" },
});
test("array buffers", getMacro, {
value: "\x01\x02\x03",
type: "arrayBuffer",
expected: new Uint8Array([1, 2, 3]).buffer,
});
test("get: gets streams", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", { value: new Uint8Array([1, 2, 3]) });
const value = await ns.get("key", "stream");
if (value === null) return t.fail();
const reader = value.getReader();
let read = await reader.read();
t.false(read.done);
t.deepEqual(read.value, new Uint8Array([1, 2, 3]));
read = await reader.read();
t.true(read.done);
t.is(read.value, undefined);
});
test("get: returns null for non-existent keys", async (t) => {
const { ns } = t.context;
t.is(await ns.get("key"), null);
});
test("get: returns null for expired keys", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", {
value: utf8Encode("value"),
expiration: TIME_EXPIRED,
});
t.is(await ns.get("key"), null);
});
test("get: ignores cache ttl", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", { value: utf8Encode('{"field":"value"}') });
t.is(
await ns.get("key", { type: undefined, cacheTtl: 3600 }),
'{"field":"value"}'
);
t.deepEqual(await ns.get("key", { type: "json", cacheTtl: 3600 }), {
field: "value",
});
});
test("get: waits for input gate to open before returning", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
await waitsForInputGate(t, () => ns.get("key"));
});
test("get: waits for input gate to open before returning with non-existent key", async (t) => {
const { ns } = t.context;
await waitsForInputGate(t, () => ns.get("key"));
});
test("get: waits for input gate to open before returning stream chunk", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
const stream = await waitsForInputGate(t, () => ns.get("key", "stream"));
assert(stream);
const chunk = await waitsForInputGate(t, () => stream.getReader().read());
t.is(utf8Decode(chunk.value), "value");
});
test(validatesKeyMacro, "get", "GET", async (ns, key) => {
await ns.get(key);
});
test("get", validateGetMacro, async (ns, cacheTtl, type) => {
await ns.get("key", { cacheTtl, type: type as any });
});
const getWithMetadataMacro: Macro<
[{ value: string; type?: KVGetValueType; expected: any }],
Context
> = async (t, { value, type, expected }) => {
const { storage, ns } = t.context;
await storage.put("key", {
value: utf8Encode(value),
metadata: { testing: true },
});
// Test both ways of specifying the type
t.deepEqual(await ns.getWithMetadata("key", type as any), {
value: expected,
metadata: { testing: true },
});
t.deepEqual(await ns.getWithMetadata("key", { type: type as any }), {
value: expected,
metadata: { testing: true },
});
};
getWithMetadataMacro.title = (providedTitle) =>
`getWithMetadata: gets ${providedTitle} with metadata`;
test("text by default", getWithMetadataMacro, {
value: "value",
expected: "value",
});
test("text", getWithMetadataMacro, {
value: "value",
type: "text",
expected: "value",
});
test("json", getWithMetadataMacro, {
value: '{"field":"value"}',
type: "json",
expected: { field: "value" },
});
test("array buffers", getWithMetadataMacro, {
value: "\x01\x02\x03",
type: "arrayBuffer",
expected: new Uint8Array([1, 2, 3]).buffer,
});
test("getWithMetadata: gets streams with metadata", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", {
value: new Uint8Array([1, 2, 3]),
metadata: { testing: true },
});
const { value, metadata } = await ns.getWithMetadata("key", "stream");
if (value === null) return t.fail();
// Check stream contents
const reader = value.getReader();
let read = await reader.read();
t.false(read.done);
t.deepEqual(read.value, new Uint8Array([1, 2, 3]));
read = await reader.read();
t.true(read.done);
t.is(read.value, undefined);
// Check metadata
t.deepEqual(metadata, { testing: true });
});
test("getWithMetadata: returns null for non-existent keys with metadata", async (t) => {
const { ns } = t.context;
t.deepEqual(await ns.getWithMetadata("key"), { value: null, metadata: null });
});
test("getWithMetadata: returns null for expired keys with metadata", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", {
value: utf8Encode("value"),
expiration: TIME_EXPIRED,
metadata: { testing: true },
});
t.deepEqual(await ns.getWithMetadata("key"), { value: null, metadata: null });
});
test("getWithMetadata: ignores cache ttl", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", {
value: utf8Encode('{"field":"value"}'),
metadata: { testing: true },
});
t.deepEqual(
await ns.getWithMetadata("key", { type: undefined, cacheTtl: 3600 }),
{
value: '{"field":"value"}',
metadata: { testing: true },
}
);
t.deepEqual(
await ns.getWithMetadata("key", { type: "json", cacheTtl: 3600 }),
{
value: { field: "value" },
metadata: { testing: true },
}
);
});
test("getWithMetadata: waits for input gate to open before returning", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
await waitsForInputGate(t, () => ns.getWithMetadata("key"));
});
test("getWithMetadata: waits for input gate to open before returning with non-existent key", async (t) => {
const { ns } = t.context;
await waitsForInputGate(t, () => ns.getWithMetadata("key"));
});
test("getWithMetadata: waits for input gate to open before returning stream chunk", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
const { value } = await waitsForInputGate(t, () =>
ns.getWithMetadata("key", "stream")
);
assert(value);
const chunk = await waitsForInputGate(t, () => value.getReader().read());
t.is(utf8Decode(chunk.value), "value");
});
test(validatesKeyMacro, "getWithMetadata", "GET", async (ns, key) => {
await ns.getWithMetadata(key);
});
test("getWithMetadata", validateGetMacro, async (ns, cacheTtl, type) => {
await ns.getWithMetadata("key", { cacheTtl, type: type as any });
});
const putMacro: Macro<
[
{ value: KVPutValueType; options?: KVPutOptions; expected: StoredValueMeta }
],
Context
> = async (t, { value, options, expected }) => {
const { storage, ns } = t.context;
await ns.put("key", value, options);
t.deepEqual(await storage.get("key"), {
value: expected.value,
// Make sure expiration and metadata are in expected result if undefined
expiration: expected.expiration,
metadata: expected.metadata,
});
};
putMacro.title = (providedTitle) => `put: puts ${providedTitle}`;
test("text", putMacro, {
value: "value",
expected: { value: utf8Encode("value") },
});
test("streams", putMacro, {
value: new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([1, 2, 3]));
controller.close();
},
}),
expected: { value: new Uint8Array([1, 2, 3]) },
});
test("array buffers", putMacro, {
value: new Uint8Array([1, 2, 3]).buffer,
expected: { value: new Uint8Array([1, 2, 3]) },
});
test("array buffer views", putMacro, {
value: new DataView(new Uint8Array([1, 2, 3]).buffer),
expected: { value: new Uint8Array([1, 2, 3]) },
});
test("text with expiration", putMacro, {
value: "value",
options: { expiration: TIME_EXPIRING },
expected: { value: utf8Encode("value"), expiration: TIME_EXPIRING },
});
test("text with string expiration", putMacro, {
value: "value",
options: { expiration: TIME_EXPIRING.toString() },
expected: { value: utf8Encode("value"), expiration: TIME_EXPIRING },
});
test("text with expiration ttl", putMacro, {
value: "value",
options: { expirationTtl: 1000 },
expected: { value: utf8Encode("value"), expiration: TIME_NOW + 1000 },
});
test("text with string expiration ttl", putMacro, {
value: "value",
options: { expirationTtl: "1000" },
expected: { value: utf8Encode("value"), expiration: TIME_NOW + 1000 },
});
test("text with metadata", putMacro, {
value: "value",
options: { metadata: { testing: true } },
expected: { value: utf8Encode("value"), metadata: { testing: true } },
});
test("text with expiration and metadata", putMacro, {
value: "value",
options: { expiration: TIME_EXPIRING, metadata: { testing: true } },
expected: {
value: utf8Encode("value"),
expiration: TIME_EXPIRING,
metadata: { testing: true },
},
});
test("text with expiration ttl and metadata", putMacro, {
value: "value",
options: { expirationTtl: 1000, metadata: { testing: true } },
expected: {
value: utf8Encode("value"),
expiration: TIME_NOW + 1000,
metadata: { testing: true },
},
});
test("put: overrides existing keys", async (t) => {
const { storage, ns } = t.context;
await ns.put("key", "value1");
await ns.put("key", "value2", {
expiration: TIME_EXPIRING,
metadata: { testing: true },
});
t.deepEqual(await storage.get("key"), {
value: utf8Encode("value2"),
expiration: TIME_EXPIRING,
metadata: { testing: true },
});
});
test("put: waits for output gate to open before storing", async (t) => {
const { ns } = t.context;
await waitsForOutputGate(
t,
() => ns.put("key", "value"),
() => ns.get("key")
);
});
test("put: waits for input gate to open before returning", async (t) => {
const { ns } = t.context;
await waitsForInputGate(t, () => ns.put("key", "value"));
});
test(validatesKeyMacro, "put", "PUT", async (ns, key) => {
await ns.put(key, "value");
});
test("put: validates value type", async (t) => {
const { ns } = t.context;
await t.throwsAsync(ns.put("key", new Map() as any), {
instanceOf: TypeError,
message:
"KV put() accepts only strings, ArrayBuffers, ArrayBufferViews, and ReadableStreams as values.",
});
});
test("put: validates expiration ttl", async (t) => {
const { ns } = t.context;
await t.throwsAsync(ns.put("key", "value", { expirationTtl: "nan" }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration_ttl of nan. Please specify integer greater than 0.",
});
await t.throwsAsync(ns.put("key", "value", { expirationTtl: 0 }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration_ttl of 0. Please specify integer greater than 0.",
});
await t.throwsAsync(ns.put("key", "value", { expirationTtl: 30 }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration_ttl of 30. Expiration TTL must be at least 60.",
});
});
test("put: validates expiration", async (t) => {
const { ns } = t.context;
await t.throwsAsync(ns.put("key", "value", { expiration: "nan" }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration of nan. Please specify integer greater than the current number of seconds since the UNIX epoch.",
});
// testClock sets current time to 750s since UNIX epoch
await t.throwsAsync(ns.put("key", "value", { expiration: 750 }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration of 750. Please specify integer greater than the current number of seconds since the UNIX epoch.",
});
await t.throwsAsync(ns.put("key", "value", { expiration: 780 }), {
instanceOf: Error,
message:
"KV PUT failed: 400 Invalid expiration of 780. Expiration times must be at least 60 seconds in the future.",
});
});
test("put: validates value size", async (t) => {
const { ns } = t.context;
const maxValueSize = 25 * 1024 * 1024;
const byteLength = maxValueSize + 1;
await t.throwsAsync(ns.put("key", new Uint8Array(byteLength)), {
instanceOf: Error,
message: `KV PUT failed: 413 Value length of ${byteLength} exceeds limit of ${maxValueSize}.`,
});
});
test("put: validates metadata size", async (t) => {
const { ns } = t.context;
const maxMetadataSize = 1024;
await t.throwsAsync(
ns.put("key", "value", {
metadata: {
key: "".padStart(maxMetadataSize - `{\"key\":\"\"}`.length + 1, "x"),
},
}),
{
instanceOf: Error,
message: `KV PUT failed: 413 Metadata length of ${
maxMetadataSize + 1
} exceeds limit of ${maxMetadataSize}.`,
}
);
});
test("delete: deletes existing keys", async (t) => {
const { storage, ns } = t.context;
await storage.put("key", { value: utf8Encode("value") });
t.not(await storage.get("key"), undefined);
await ns.delete("key");
t.is(await storage.get("key"), undefined);
});
test("delete: does nothing for non-existent keys", async (t) => {
const { ns } = t.context;
await ns.delete("key");
await t.pass();
});
test("delete: waits for output gate to open before deleting", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
await waitsForOutputGate(
t,
() => ns.delete("key"),
async () => !(await ns.get("key"))
);
});
test("delete: waits for input gate to open before returning", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
await waitsForInputGate(t, () => ns.delete("key"));
});
test(validatesKeyMacro, "delete", "DELETE", async (ns, key) => {
await ns.delete(key);
});
const listMacro: Macro<
[
{
values: Record<string, StoredValueMeta>;
options?: KVListOptions;
pages: StoredKeyMeta[][];
}
],
Context
> = async (t, { values, options = {}, pages }) => {
const { storage, ns } = t.context;
for (const [key, value] of Object.entries(values)) {
await storage.put(key, value);
}
let lastCursor = "";
for (let i = 0; i < pages.length; i++) {
const { keys, list_complete, cursor } = await ns.list({
prefix: options.prefix,
limit: options.limit,
cursor: options.cursor ?? lastCursor,
});
t.deepEqual(
keys,
pages[i].map((value) => ({
expiration: undefined,
metadata: undefined,
...value,
}))
);
if (i === pages.length - 1) {
// Last Page
t.true(list_complete);
t.is(cursor, "");
} else {
t.false(list_complete);
t.not(cursor, "");
}
lastCursor = cursor;
}
};
listMacro.title = (providedTitle) => `list: ${providedTitle}`;
test("lists keys in sorted order", listMacro, {
values: {
key3: { value: utf8Encode("value3") },
key1: { value: utf8Encode("value1") },
key2: { value: utf8Encode("value2") },
},
pages: [[{ name: "key1" }, { name: "key2" }, { name: "key3" }]],
});
test("lists keys matching prefix", listMacro, {
values: {
section1key1: { value: utf8Encode("value11") },
section1key2: { value: utf8Encode("value12") },
section2key1: { value: utf8Encode("value21") },
},
options: { prefix: "section1" },
pages: [[{ name: "section1key1" }, { name: "section1key2" }]],
});
test("lists keys with expiration", listMacro, {
values: {
key1: { value: utf8Encode("value1"), expiration: TIME_EXPIRING },
key2: { value: utf8Encode("value2"), expiration: TIME_EXPIRING + 100 },
key3: { value: utf8Encode("value3"), expiration: TIME_EXPIRING + 200 },
},
pages: [
[
{ name: "key1", expiration: TIME_EXPIRING },
{ name: "key2", expiration: TIME_EXPIRING + 100 },
{ name: "key3", expiration: TIME_EXPIRING + 200 },
],
],
});
test("lists keys with metadata", listMacro, {
values: {
key1: { value: utf8Encode("value1"), metadata: { testing: 1 } },
key2: { value: utf8Encode("value2"), metadata: { testing: 2 } },
key3: { value: utf8Encode("value3"), metadata: { testing: 3 } },
},
pages: [
[
{ name: "key1", metadata: { testing: 1 } },
{ name: "key2", metadata: { testing: 2 } },
{ name: "key3", metadata: { testing: 3 } },
],
],
});
test("lists keys with expiration and metadata", listMacro, {
values: {
key1: {
value: utf8Encode("value1"),
expiration: TIME_EXPIRING,
metadata: { testing: 1 },
},
key2: {
value: utf8Encode("value2"),
expiration: TIME_EXPIRING + 100,
metadata: { testing: 2 },
},
key3: {
value: utf8Encode("value3"),
expiration: TIME_EXPIRING + 200,
metadata: { testing: 3 },
},
},
pages: [
[
{
name: "key1",
expiration: TIME_EXPIRING,
metadata: { testing: 1 },
},
{
name: "key2",
expiration: TIME_EXPIRING + 100,
metadata: { testing: 2 },
},
{
name: "key3",
expiration: TIME_EXPIRING + 200,
metadata: { testing: 3 },
},
],
],
});
test("returns an empty list with no keys", listMacro, {
values: {},
pages: [[]],
});
test("returns an empty list with no matching keys", listMacro, {
values: {
key1: { value: utf8Encode("value1") },
key2: { value: utf8Encode("value2") },
key3: { value: utf8Encode("value3") },
},
options: { prefix: "none" },
pages: [[]],
});
test("returns an empty list with an invalid cursor", listMacro, {
values: {
key1: { value: utf8Encode("value1") },
key2: { value: utf8Encode("value2") },
key3: { value: utf8Encode("value3") },
},
options: { cursor: base64Encode("bad") },
pages: [[]],
});
test("paginates keys", listMacro, {
values: {
key1: { value: utf8Encode("value1") },
key2: { value: utf8Encode("value2") },
key3: { value: utf8Encode("value3") },
},
options: { limit: 2 },
pages: [[{ name: "key1" }, { name: "key2" }], [{ name: "key3" }]],
});
test("paginates keys matching prefix", listMacro, {
values: {
section1key1: { value: utf8Encode("value11") },
section1key2: { value: utf8Encode("value12") },
section1key3: { value: utf8Encode("value13") },
section2key1: { value: utf8Encode("value21") },
},
options: { prefix: "section1", limit: 2 },
pages: [
[{ name: "section1key1" }, { name: "section1key2" }],
[{ name: "section1key3" }],
],
});
test("list: paginates with variable limit", async (t) => {
const { storage, ns } = t.context;
await storage.put("key1", { value: utf8Encode("value1") });
await storage.put("key2", { value: utf8Encode("value2") });
await storage.put("key3", { value: utf8Encode("value3") });
// Get first page
let page = await ns.list({ limit: 1 });
t.deepEqual(page.keys, [
{ name: "key1", expiration: undefined, metadata: undefined },
]);
t.false(page.list_complete);
t.not(page.cursor, "");
// Get second page with different limit
page = await ns.list({ limit: 2, cursor: page.cursor });
t.deepEqual(page.keys, [
{ name: "key2", expiration: undefined, metadata: undefined },
{ name: "key3", expiration: undefined, metadata: undefined },
]);
t.true(page.list_complete);
t.is(page.cursor, "");
});
test("list: returns keys inserted whilst paginating", async (t) => {
const { storage, ns } = t.context;
await storage.put("key1", { value: utf8Encode("value1") });
await storage.put("key3", { value: utf8Encode("value3") });
await storage.put("key5", { value: utf8Encode("value5") });
// Get first page
let page = await ns.list({ limit: 2 });
t.deepEqual(page.keys, [
{ name: "key1", expiration: undefined, metadata: undefined },
{ name: "key3", expiration: undefined, metadata: undefined },
]);
t.false(page.list_complete);
t.not(page.cursor, "");
// Insert key2 and key4
await storage.put("key2", { value: utf8Encode("value2") });
await storage.put("key4", { value: utf8Encode("value4") });
// Get second page, expecting to see key4 but not key2
page = await ns.list({ limit: 2, cursor: page.cursor });
t.deepEqual(page.keys, [
{ name: "key4", expiration: undefined, metadata: undefined },
{ name: "key5", expiration: undefined, metadata: undefined },
]);
t.true(page.list_complete);
t.is(page.cursor, "");
});
test("list: ignores expired keys", async (t) => {
const { storage, ns } = t.context;
for (let i = 1; i <= 3; i++) {
await storage.put(`key${i}`, {
value: utf8Encode(`value${i}`),
expiration: i * 100,
});
}
t.deepEqual(await ns.list(), { keys: [], list_complete: true, cursor: "" });
});
test("list: waits for input gate to open before returning", async (t) => {
const { ns } = t.context;
await ns.put("key", "value");
await waitsForInputGate(t, () => ns.list());
});
test("list: validates limit", async (t) => {
const { ns } = t.context;
await t.throwsAsync(ns.list({ limit: "nan" as any }), {
instanceOf: Error,
message:
"KV GET failed: 400 Invalid key_count_limit of nan. Please specify an integer greater than 0.",
});
await t.throwsAsync(ns.list({ limit: 0 }), {
instanceOf: Error,
message:
"KV GET failed: 400 Invalid key_count_limit of 0. Please specify an integer greater than 0.",
});
await t.throwsAsync(ns.list({ limit: 1001 }), {
instanceOf: Error,
message:
"KV GET failed: 400 Invalid key_count_limit of 1001. Please specify an integer less than 1000.",
});
});
test("hides implementation details", (t) => {
const { ns } = t.context;
t.deepEqual(getObjectProperties(ns), [
"delete",
"get",
"getWithMetadata",
"list",
"put",
]);
});
test("operations throw outside request handler", async (t) => {
const ns = new KVNamespace(new MemoryStorage(), { blockGlobalAsyncIO: true });
const ctx = new RequestContext();
const expectations: ThrowsExpectation = {
instanceOf: Error,
message: /^Some functionality, such as asynchronous I\/O/,
};
await t.throwsAsync(ns.get("key"), expectations);
await t.throwsAsync(ns.getWithMetadata("key"), expectations);
await t.throwsAsync(ns.put("key", "value"), expectations);
await t.throwsAsync(ns.delete("key"), expectations);
await t.throwsAsync(ns.list(), expectations);
await ctx.runWith(() => ns.get("key"));
await ctx.runWith(() => ns.getWithMetadata("key"));
await ctx.runWith(() => ns.put("key", "value"));
await ctx.runWith(() => ns.delete("key"));
await ctx.runWith(() => ns.list());
}); | the_stack |
import type { ITableOrView, ITable, IWithView } from "../utils/ITableOrView"
import type { BooleanValueSource, NumberValueSource, IntValueSource, IValueSource, __OptionalRule, IfValueSource, IExecutableSelectQuery } from "../expressions/values"
import type { int } from "ts-extended-types"
import type { DefaultTypeAdapter, TypeAdapter } from "../TypeAdapter"
import type { OrderByMode, SelectCustomization } from "../expressions/select"
import type { Column } from "../utils/Column"
import type { QueryRunner } from "../queryRunners/QueryRunner"
import type { ConnectionConfiguration } from "../utils/ConnectionConfiguration"
import type { UpdateCustomization } from "../expressions/update"
import type { DeleteCustomization } from "../expressions/delete"
import type { InsertCustomization } from "../expressions/insert"
export interface WithData {
__name: string
__as?: string
__selectData: SelectData
__optionalRule: __OptionalRule
__recursive?: boolean
}
export function getWithData(withView: IWithView<any>): WithData {
return withView as any
}
export interface JoinData {
__joinType: 'join' | 'innerJoin' | 'leftJoin' | 'leftOuterJoin'
__tableOrView: ITableOrView<any>
__on?: BooleanValueSource<any, any> | IfValueSource<any, any>
__optional?: boolean
}
export interface WithQueryData {
__withs: Array<IWithView<any>>
__customization?: SelectCustomization<any>
}
export type SelectData = PlainSelectData | CompoundSelectData
export interface PlainSelectData extends WithQueryData {
__type: 'plain'
__distinct: boolean
__columns: { [property: string]: IValueSource<any, any> }
__tablesOrViews: Array<ITableOrView<any>>
__joins: Array<JoinData>
__where?: BooleanValueSource<any, any> | IfValueSource<any, any>
__having?: BooleanValueSource<any, any> | IfValueSource<any, any>
__groupBy: Array<IValueSource<any, any>>
__orderBy?: { [property: string]: OrderByMode | null | undefined }
__limit?: int | number | NumberValueSource<any, any> | IntValueSource<any, any>
__offset?: int | number | NumberValueSource<any, any> | IntValueSource<any, any>
__requiredTablesOrViews?: Set<ITableOrView<any>>
}
export type CompoundOperator = 'union' | 'unionAll' | 'intersect' | 'intersectAll' | 'except' | 'exceptAll' | 'minus' | 'minusAll'
export interface CompoundSelectData extends WithQueryData {
__type: 'compound'
__firstQuery: SelectData
__compoundOperator: CompoundOperator
__secondQuery: SelectData
__columns: { [property: string]: IValueSource<any, any> }
__orderBy?: { [property: string]: OrderByMode | null | undefined }
__limit?: int | number | NumberValueSource<any, any> | IntValueSource<any, any>
__offset?: int | number | NumberValueSource<any, any> | IntValueSource<any, any>
}
export interface InsertData extends WithQueryData {
__table: ITable<any>
__sets: { [property: string]: any }
__multiple?: { [property: string]: any }[]
__idColumn?: Column
__from?: SelectData
__customization?: InsertCustomization<any>
__columns?: { [property: string]: IValueSource<any, any> }
}
export interface UpdateData extends WithQueryData {
__table: ITable<any>
__sets: { [property: string] : any}
__where?: BooleanValueSource<any, any> | IfValueSource<any, any>
__allowNoWhere: boolean
__customization?: UpdateCustomization<any>
__columns?: { [property: string]: IValueSource<any, any> }
__oldValues?: ITableOrView<any>
__froms?: Array<ITableOrView<any>>
__joins?: Array<JoinData>
}
export interface DeleteData extends WithQueryData {
__table: ITable<any>,
__where?: BooleanValueSource<any, any> | IfValueSource<any, any>
__allowNoWhere: boolean
__customization?: DeleteCustomization<any>
__columns?: { [property: string]: IValueSource<any, any> }
__using?: Array<ITableOrView<any>>
__joins?: Array<JoinData>
}
export interface SqlBuilder extends SqlOperation, __OptionalRule {
_defaultTypeAdapter: DefaultTypeAdapter
_queryRunner: QueryRunner
_connectionConfiguration: ConnectionConfiguration
_isValue(value: any): boolean
_isReservedKeyword(word: string): boolean
_forceAsIdentifier(identifier: string): string
_appendColumnName(column: Column, params: any[]): string
_appendColumnNameForCondition(column: Column, params: any[]): string
_buildSelect(query: SelectData, params: any[]): string
_buildInsertDefaultValues(query: InsertData, params: any[]): string
_buildInsert(query: InsertData, params: any[]): string
_buildInsertFromSelect(query: InsertData, params: any[]): string
_buildInsertMultiple(query: InsertData, params: any[]): string
_buildUpdate(query: UpdateData, params: any[]): string
_buildDelete(query: DeleteData, params: any[]): string
_buildCallProcedure(params: any[], procedureName: string, procedureParams: IValueSource<any, any>[]): string
_buildCallFunction(params: any[], functionName: string, functionParams: IValueSource<any, any>[]): string
_generateUnique(): number
_resetUnique(): void
_rawFragment(params: any[], sql: TemplateStringsArray, sqlParams: Array<IValueSource<any, any> | IExecutableSelectQuery<any, any, any, any>>): string
_rawFragmentTableName(params: any[], tableOrView: ITableOrView<any>): string
_rawFragmentTableAlias(params: any[], tableOrView: ITableOrView<any>): string
_inlineSelectAsValue(query: SelectData, params: any[]): string
_inlineSelectAsValueForCondition(query: SelectData, params: any[]): string
}
export interface ToSql {
__toSql(sqlBuilder: SqlBuilder, params: any[]): string
__toSqlForCondition(sqlBuilder: SqlBuilder, params: any[]): string
}
export function hasToSql(value: any): value is ToSql {
if (value === undefined || value === null) {
return false
}
if (typeof value === 'object') {
return typeof value.__toSql === 'function'
}
return false
}
export interface HasOperation {
__operation: keyof SqlOperation
}
export function operationOf(value: any): keyof SqlOperation | null {
if (value === undefined || value === null) {
return null
}
if (typeof value.__operation === 'string') {
return value.__operation as keyof SqlOperation
}
return null
}
export interface SqlComparator0 {
_isNull(params: any[], valueSource: ToSql): string
_isNotNull(params: any[], valueSource: ToSql): string
}
export interface SqlComparator1 {
_equals(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notEquals(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_is(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_isNot(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_equalsInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notEqualsInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_lessThan(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_greaterThan(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_lessOrEquals(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_greaterOrEquals(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_in(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notIn(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_like(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notLike(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_likeInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notLikeInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_startsWith(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notStartsWith(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_endsWith(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notEndsWith(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_startsWithInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notStartsWithInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_endsWithInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notEndsWithInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_contains(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notContains(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_containsInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notContainsInsensitive(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
}
export interface SqlComparator2 {
_between(params: any[], valueSource: ToSql, value: any, value2: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notBetween(params: any[], valueSource: ToSql, value: any, value2: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
}
export interface SqlFunctionStatic0 {
_pi(params: any): string
_random(params: any): string
_currentDate(params: any): string
_currentTime(params: any): string
_currentTimestamp(params: any): string
_default(params: any): string
_true(params: any): string
_false(params: any): string
_trueForCondition(params: any): string
_falseForCondition(params: any): string
}
export interface SqlFunctionStatic1 {
_const(params: any[], value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_constForCondition(params: any[], value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_exists(params: any[], value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_notExists(params: any[], value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_escapeLikeWildcard(params: any[], value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
}
export interface SqlFunction0 {
// Boolean
_negate(params: any[], valueSource: ToSql): string
// String
_toLowerCase(params: any[], valueSource: ToSql): string
_toUpperCase(params: any[], valueSource: ToSql): string
_length(params: any[], valueSource: ToSql): string
_trim(params: any[], valueSource: ToSql): string
_trimLeft(params: any[], valueSource: ToSql): string
_trimRight(params: any[], valueSource: ToSql): string
_reverse(params: any[], valueSource: ToSql): string
// Number functions
_asDouble(params: any[], valueSource: ToSql): string
_abs(params: any[], valueSource: ToSql): string
_ceil(params: any[], valueSource: ToSql): string
_floor(params: any[], valueSource: ToSql): string
_round(params: any[], valueSource: ToSql): string
_exp(params: any[], valueSource: ToSql): string
_ln(params: any[], valueSource: ToSql): string
_log10(params: any[], valueSource: ToSql): string
_sqrt(params: any[], valueSource: ToSql): string
_cbrt(params: any[], valueSource: ToSql): string
_sign(params: any[], valueSource: ToSql): string
// Trigonometric Functions
_acos(params: any[], valueSource: ToSql): string
_asin(params: any[], valueSource: ToSql): string
_atan(params: any[], valueSource: ToSql): string
_cos(params: any[], valueSource: ToSql): string
_cot(params: any[], valueSource: ToSql): string
_sin(params: any[], valueSource: ToSql): string
_tan(params: any[], valueSource: ToSql): string
// Date Functions
_getDate(params: any[], valueSource: ToSql): string
_getTime(params: any[], valueSource: ToSql): string
_getFullYear(params: any[], valueSource: ToSql): string
_getMonth(params: any[], valueSource: ToSql): string
_getDay(params: any[], valueSource: ToSql): string
_getHours(params: any[], valueSource: ToSql): string
_getMinutes(params: any[], valueSource: ToSql): string
_getSeconds(params: any[], valueSource: ToSql): string
_getMilliseconds(params: any[], valueSource: ToSql): string
}
export interface SqlFunction1 {
_valueWhenNull(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
// Boolean
_and(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_or(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
// String
_concat(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_substrToEnd(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_substringToEnd(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
// Number
_power(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_logn(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_roundn(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_minValue(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_maxValue(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
// Number operators
_add(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_substract(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_multiply(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_divide(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_modulo(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string // %
// Trigonometric Functions
_atan2(params: any[], valueSource: ToSql, value: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
}
// avg, count, max, median, min,
// greatest, least
// regexp_count, remainder
export interface SqlFunction2 {
// String
_substr(params: any[], valueSource: ToSql, value: any, value2: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_substring(params: any[], valueSource: ToSql, value: any, value2: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
_replaceAll(params: any[], valueSource: ToSql, value: any, value2: any, columnType: string, typeAdapter: TypeAdapter | undefined): string
}
export interface SqlSequenceOperation {
_nextSequenceValue(params: any[], sequenceName: string): string
_currentSequenceValue(params: any[], sequenceName: string): string
}
export interface SqlFragmentOperation {
_fragment(params: any[], sql: TemplateStringsArray, sqlParams: IValueSource<any, any>[]): string
}
export interface AggregateFunctions0 {
_countAll(params: any[]): string
}
export interface AggregateFunctions1 {
_count(params: any[], value: any): string
_countDistinct(params: any[], value: any): string
_max(params: any[], value: any): string
_min(params: any[], value: any): string
_sum(params: any[], value: any): string
_sumDistinct(params: any[], value: any): string
_average(params: any[], value: any): string
_averageDistinct(params: any[], value: any): string
}
export interface AggregateFunctions1or2 {
_stringConcat(params: any[], separator: string | undefined, value: any): string
_stringConcatDistinct(params: any[], separator: string | undefined, value: any): string
}
export interface SqlOperationStatic0 extends SqlFunctionStatic0 {
}
export interface SqlOperationStatic1 extends SqlFunctionStatic1 {
}
export interface SqlOperation0 extends SqlComparator0, SqlFunction0 {
}
export interface SqlOperation1 extends SqlComparator1, SqlFunction1 {
}
export interface SqlOperation2 extends SqlComparator2, SqlFunction2 {
}
export interface SqlOperation extends SqlOperationStatic0, SqlOperationStatic1, SqlOperation0, SqlOperation1, SqlOperation2, SqlSequenceOperation, SqlFragmentOperation, AggregateFunctions0, AggregateFunctions1, AggregateFunctions1or2 {
_inlineSelectAsValue(query: SelectData, params: any[]): string
} | the_stack |
import DomElements from "./DomElements";
import ArrayUtils from "./ArrayUtils";
export default class DomAttributes {
static readonly ATTRIBUTE_DISABLED = "disabled";
public static actions = {
set : "set",
unset : "unset"
};
public static dataAttributes = {
contentEditable: "data-content-editable"
};
/**
* @description This function will check if the element has attribute "content editable"
* If selector as second param is provided then found children will be checked
* If children is not found then throws error
*
* @param element
* @param selectorToSearchInElement
* @returns {boolean}
*/
public static isContentEditable(element, selectorToSearchInElement: string = null): boolean
{
let isContentEditable = true;
let childElement = null;
if( null !== selectorToSearchInElement ){
childElement = DomElements.findChild(element, selectorToSearchInElement);
element = childElement;
}
if(
typeof $(element).attr("contentEditable") == 'undefined'
|| $(element).attr("contentEditable") != "true"
){
isContentEditable = false;
}
return isContentEditable;
};
/**
* @description This function will set or unset content editable attribute based on the "action" variable
* If "excludeSelectorsForChildren" is present then only the found children which does NOT contain children will be modified
* If "selectorToSearchInElement" is present then children will be searched and they will be modified
* If "selectorsToSearchInChildren" is present then it will search for children inside children
* and they will be changed alongside with it's parents but not main parent
* If "onlyForChildrenInChildren" is present then only the children of v will be modified
* Also by default this method will skip elements which have " data-content-editable="false" "
*
* @param element (jq elem)
* @param action (set/unset)
* @param selectorToSearchInElement string
* @param excludedSelectorsForChildren string
* @param selectorsToSearchInChildren string
* @param onlyForChildrenInChildren bool
*/
public static contentEditable(
element,
action : string,
selectorToSearchInElement : string = null,
excludedSelectorsForChildren : string = null,
selectorsToSearchInChildren : string = null,
onlyForChildrenInChildren : boolean = false
){
let contentEditableState = null;
switch( action ){
case DomAttributes.actions.set:
contentEditableState = "true";
break;
case DomAttributes.actions.unset:
contentEditableState = "false";
break;
default:
throw({
"message": "This action for toggling content editable is not defined",
"action" : action
})
}
let firstLevelChildren = null;
let secondLevelChildren = null;
if( null !== selectorToSearchInElement ){
firstLevelChildren = DomElements.findChild(element, selectorToSearchInElement);
}
if( null !== excludedSelectorsForChildren){
let filteredFirstLevelChildren = [];
$.each(firstLevelChildren, (index, element) => {
let foundExcludedElements = $(element).find(excludedSelectorsForChildren);
if( 0 === foundExcludedElements.length ){
filteredFirstLevelChildren.push(element);
}
});
firstLevelChildren = filteredFirstLevelChildren;
}
if( null !== selectorsToSearchInChildren ){
secondLevelChildren = DomElements.findChild(firstLevelChildren, selectorsToSearchInChildren);
}
if( null === firstLevelChildren ){
if( $(element).attr(DomAttributes.dataAttributes.contentEditable) !== "false" ){
$(element).attr({"contentEditable": contentEditableState});
}
}
if(
null !== firstLevelChildren
&& null == secondLevelChildren
){
$.each(firstLevelChildren, (index, element) => {
if( $(element).attr(DomAttributes.dataAttributes.contentEditable) !== "false" ){
$(element).attr({"contentEditable": contentEditableState});
}
})
}
if(
null !== firstLevelChildren
&& null !== secondLevelChildren
&& !onlyForChildrenInChildren
){
$.each(firstLevelChildren, (index, element) => {
if( $(element).attr(DomAttributes.dataAttributes.contentEditable) !== "false" ){
$(element).attr({"contentEditable": contentEditableState});
}
});
$.each(secondLevelChildren, (index, element) => {
if( $(element).attr(DomAttributes.dataAttributes.contentEditable) !== "false" ){
$(element).attr({"contentEditable": contentEditableState});
}
});
}else{
$.each(secondLevelChildren, (index, element) => {
if( $(element).attr(DomAttributes.dataAttributes.contentEditable) !== "false" ){
$(element).attr({"contentEditable": contentEditableState});
}
});
}
};
/**
* @description Will check if provided element is a checkbox, and if not then exception will be thrown,
* or exception will be skipped if second param will be passed
*
* @param element {object}
* @param throwException {boolean}
*/
public static isCheckbox(element, throwException: boolean = true): boolean
{
let type = $(element).attr('type');
if( type !== "checkbox" ){
if(throwException){
throw({
"message": "This element is not a checkbox",
"element": element
});
}
return false;
}
return true;
};
/**
* @description Will mark checkbox as checked
*
* @param element {object}
*/
public static setChecked(element): void
{
if( DomAttributes.isCheckbox(element) ){
$(element).attr("checked", "checked");
$(element).prop("checked", true);
}
};
/**
* @description Will uncheck checkbox
*
* @param element {object}
*/
public static unsetChecked(element): void
{
if( DomAttributes.isCheckbox(element) ){
$(element).removeAttr("checked");
$(element).prop("checked", false);
}
};
/**
* @description Will check if checkbox is checked
*
* @param element {object}
*/
public static isChecked(element): boolean
{
if( DomAttributes.isCheckbox(element) ){
return $(element).prop("checked");
}
};
/**
* @description Will check if `disabled` class is present on element
*
* @param element {object}
* @return {boolean}
*/
public static isDisabledClass(element): boolean
{
let isDisabled = $(element).hasClass('disabled');
return isDisabled;
};
/**
* @description Will set disabled class
*
* @param element {object}
*/
public static setDisabledClass(element): void
{
$(element).addClass("disabled");
};
/**
* @description Will unset disabled class
*
* @param element {object}
*/
public static unsetDisabledClass(element): void
{
$(element).removeClass("disabled");
};
/**
* @description Will check if element has present/set `disabled property
*
* @param element {object}
* @return {boolean}
*/
public static isDisabledAttribute(element: JQuery<HTMLElement>): boolean
{
let isDisabled = (true == $(element).prop(DomAttributes.ATTRIBUTE_DISABLED));
return isDisabled;
};
/**
* @description Will set `disabled` property
*
* @param element {object}
*/
public static setDisabledAttribute(element: JQuery<HTMLElement>): void
{
$(element).attr(DomAttributes.ATTRIBUTE_DISABLED, DomAttributes.ATTRIBUTE_DISABLED);
};
/**
* @description Will unset `disabled` property
*
* @param element {object}
*/
public static unsetDisabledAttribute(element: JQuery<HTMLElement>): void
{
$(element).removeAttr(DomAttributes.ATTRIBUTE_DISABLED);
};
/**
* @description Add d-none class to element
*
* @param $element
*/
public static setDisplayNoneClass($element): void
{
$element.addClass("d-none");
}
/**
* Remove d-none class from element
*
* @param $element
*/
public static unsetDisplayNoneClass($element): void
{
$element.removeClass("d-none");
}
/**
* @description Check if element has d-none class
*
* @param $element
*/
public static hasDisplayNoneClass($element): boolean
{
return $element.hasClass("d-none");
}
/**
* @description Will set error class - mostly used for form elements
*
* @param element
*/
public static setErrorClass(element): void
{
$(element).addClass("has-error");
};
/**
* @description Will unset error class
*
* @param element
*/
public static unsetErrorClass(element): void
{
$(element).removeClass("has-error");
}
/**
* @description this function will trim the selector elements like `#` , `.` to get the className
* the classname is used by jquery `hasClass` etc.
* Keep in mind that this won't work with multiple classes and attribute selectors
*/
public static getClassNameFromSelector(selector: string): string
{
return selector.replace(/[#.]?/g,"");
}
/**
* @description Will check if target DOM element has given attribute
* Does not rely on the value but just if the attribute is there at all
*
* @param $element
* @param attributeName
*/
public static hasAttribute($element: JQuery<HTMLElement>, attributeName: string): boolean
{
return !( "undefined" === typeof $element.attr(attributeName) );
}
} | the_stack |
import { expect } from 'chai';
import {
Stylable,
functionWarnings,
processorWarnings,
resolverWarnings,
murmurhash3_32_gc,
} from '@stylable/core';
import { build } from '@stylable/cli';
import { createMemoryFs } from '@file-services/memory';
const log = () => {
/**/
};
describe('build stand alone', () => {
it('should create modules and copy source css files', async () => {
const fs = createMemoryFs({
'/main.st.css': `
:import{
-st-from: "./components/comp.st.css";
-st-default:Comp;
}
.gaga{
-st-extends:Comp;
color:blue;
}
`,
'/components/comp.st.css': `
.baga{
color:red;
}
`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: 'lib',
srcDir: '.',
rootDir: '/',
log,
cjs: true,
outputSources: true,
});
[
'/lib/main.st.css',
'/lib/main.st.css.js',
'/lib/components/comp.st.css',
'/lib/components/comp.st.css.js',
].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});
// assure no index file was generated by default
expect(fs.existsSync('/lib/index.st.css'), '/lib/index.st.css').to.equal(false);
});
it('should use "useNamespaceReference" to maintain a single namespace for all builds using it', async () => {
const fs = createMemoryFs({
'/src/main.st.css': `
:import{
-st-from: "./components/comp.st.css";
-st-default:Comp;
}
.gaga{
-st-extends:Comp;
color:blue;
}
`,
'/src/components/comp.st.css': `
.baga{
color:red;
}
`,
});
const stylable = Stylable.create({
projectRoot: '/',
fileSystem: fs,
resolveNamespace(n, s) {
const normalizedWindowsRoot = fs.relative(
'/',
s.replace(/^\w:\\/, '/').replace('\\', '/')
);
return n + murmurhash3_32_gc(normalizedWindowsRoot);
},
});
await build({
extension: '.st.css',
fs,
stylable,
rootDir: '/',
srcDir: 'src',
outDir: 'cjs',
log,
cjs: true,
outputSources: true,
useNamespaceReference: true,
});
[
'/cjs/main.st.css',
'/cjs/main.st.css.js',
'/cjs/components/comp.st.css',
'/cjs/components/comp.st.css.js',
].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});
expect(fs.readFileSync('/cjs/main.st.css', 'utf-8')).to.include(
'st-namespace-reference="../src/main.st.css"'
);
await build({
extension: '.st.css',
fs,
stylable,
rootDir: '/',
srcDir: 'cjs',
outDir: 'cjs2',
log,
cjs: true,
});
// check two builds using sourceNamespace are identical
// compare two serializable js modules including their namespace
expect(fs.readFileSync('/cjs/main.st.css.js', 'utf-8')).to.equal(
fs.readFileSync('/cjs2/main.st.css.js', 'utf-8')
);
});
it('should report errors originating from stylable (process + transform)', async () => {
const fs = createMemoryFs({
'/comp.st.css': `
:import {
-st-from: "./missing-file.st.css";
-st-default: OtherMissingComp;
}
.a {
-st-extends: MissingComp;
color: value(missingVar);
}
`,
});
const stylable = new Stylable('/', fs, () => ({}));
const { diagnosticsMessages } = await build({
extension: '.st.css',
fs,
stylable,
outDir: '.',
srcDir: '.',
rootDir: '/',
log,
cjs: true,
});
const messages = diagnosticsMessages.get('/comp.st.css')!;
expect(messages[0].message).to.contain(
processorWarnings.CANNOT_RESOLVE_EXTEND('MissingComp')
);
expect(messages[1].message).to.contain(
resolverWarnings.UNKNOWN_IMPORTED_FILE('./missing-file.st.css')
);
expect(messages[2].message).to.contain(functionWarnings.UNKNOWN_VAR('missingVar'));
});
it('should optimize css (remove empty nodes, remove stylable-directives, remove comments)', async () => {
const fs = createMemoryFs({
'/comp.st.css': `
.root {
color: red;
}
/* comment */
.x {
}
`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: './dist',
srcDir: '.',
rootDir: '/',
log,
cjs: true,
outputCSS: true,
outputCSSNameTemplate: '[filename].global.css',
});
const builtFile = fs.readFileSync('/dist/comp.global.css', 'utf8');
expect(builtFile).to.contain(`root {`);
expect(builtFile).to.contain(`color: red;`);
expect(builtFile).to.not.contain(`.x`);
});
it('should minify', async () => {
const fs = createMemoryFs({
'/comp.st.css': `
.root {
color: rgb(255,0,0);
}
`,
});
const stylable = Stylable.create({
projectRoot: '/',
fileSystem: fs,
resolveNamespace() {
return 'test';
},
});
await build({
extension: '.st.css',
fs,
stylable,
outDir: './dist',
srcDir: '.',
minify: true,
rootDir: '/',
log,
cjs: true,
outputCSS: true,
outputCSSNameTemplate: '[filename].global.css',
});
const builtFile = fs.readFileSync('/dist/comp.global.css', 'utf8');
expect(builtFile).to.contain(`.test__root{color:red}`);
});
it('should inject request to output module', async () => {
const fs = createMemoryFs({
'/comp.st.css': `
.root {
color: red;
}
`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: './dist',
srcDir: '.',
rootDir: '/',
log,
cjs: true,
outputCSS: true,
injectCSSRequest: true,
outputCSSNameTemplate: '[filename].global.css',
});
expect(fs.readFileSync('/dist/comp.st.css.js', 'utf8')).contains(
`require("./comp.global.css")`
);
expect(fs.existsSync('/dist/comp.global.css')).to.equal(true);
});
it('DTS only parts', async () => {
const fs = createMemoryFs({
'/main.st.css': `
.root {}
.part {}`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: '.',
srcDir: '.',
rootDir: '/',
log,
dts: true,
dtsSourceMap: false,
});
['/main.st.css', '/main.st.css.d.ts'].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});
const dtsContent = fs.readFileSync('/main.st.css.d.ts', 'utf8');
expect(dtsContent).contains('declare const classes');
expect(dtsContent).contains('"root":');
expect(dtsContent).contains('"part":');
});
it('DTS with states', async () => {
const fs = createMemoryFs({
'/main.st.css': `
.root { -st-states: w; }
.string { -st-states: x(string); }
.number { -st-states: y(number); }
.enum { -st-states: z(enum(on, off, default)); }`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: '.',
srcDir: '.',
rootDir: '/',
log,
dts: true,
dtsSourceMap: false,
});
['/main.st.css', '/main.st.css.d.ts'].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});
const dtsContent = fs.readFileSync('/main.st.css.d.ts', 'utf8');
expect(dtsContent).to.contain('type states = {');
expect(dtsContent).to.contain('"w"?:');
expect(dtsContent).to.contain('"x"?: string');
expect(dtsContent).to.contain('"y"?: number');
expect(dtsContent).to.contain('"z"?: "on" | "off" | "default";');
});
it('DTS with mapping', async () => {
const fs = createMemoryFs({
'/main.st.css': `
@keyframes blah {
0% {}
100% {}
}
:vars {
v1: red;
v2: green;
}
.root {
-st-states: a, b, w;
--c1: red;
--c2: green;
}
.string { -st-states: x(string); }
.number { -st-states: y(number); }
.enum { -st-states: z(enum(on, off, default)); }`,
});
const stylable = new Stylable('/', fs, () => ({}));
await build({
extension: '.st.css',
fs,
stylable,
outDir: '.',
srcDir: '.',
rootDir: '/',
log,
dts: true,
dtsSourceMap: true,
});
['/main.st.css', '/main.st.css.d.ts', '/main.st.css.d.ts.map'].forEach((p) => {
expect(fs.existsSync(p), p).to.equal(true);
});
const dtsSourceMapContent = fs.readFileSync('/main.st.css.d.ts.map', 'utf8');
expect(dtsSourceMapContent).to.contain(`"file": "main.st.css.d.ts",`);
expect(dtsSourceMapContent).to.contain(`"sources": [`);
expect(dtsSourceMapContent).to.contain(`"main.st.css"`);
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.