repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
h-o-t/entente | tests/fixtures/imports.ts | import * as mod3 from "./mod3";
import { qux, quux, quuux } from "./mod4";
mod3.baz();
// eslint-disable-next-line no-console
console.log(qux, quux, quuux);
|
h-o-t/entente | src/nodes/ParameterDeclarationArray.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ParameterDeclaration } from "./ParameterDeclaration";
export class ParameterDeclarationArray {
constructor(private _parameters: ts.ParameterDeclaration[]) {}
/** Assert there is a parameter at the given index. If true, return an
* interface to the parameter. */
parameter(
idx: number,
msg = `Expected parameter to exist at index ${idx}.`
): ParameterDeclaration {
if (!this._parameters[idx]) {
throw new AssertionError(
msg,
{
actual: undefined,
expected: true,
showDiff: false,
},
this.parameter
);
}
return new ParameterDeclaration(this._parameters[idx]);
}
/** Assert the length of the number of parameters accepted by the function.
* If true, return the parameter list. */
length(expected: number, msg?: string): this {
const actual = this._parameters.length;
if (actual !== expected) {
throw new AssertionError(
msg ?? `Expected length of ${expected}, actual ${actual}.`,
{
actual,
expected,
showDiff: false,
},
this.length
);
}
return this;
}
*[Symbol.iterator](): IterableIterator<ParameterDeclaration> {
let idx = 0;
while (this._parameters[idx]) {
yield new ParameterDeclaration(this._parameters[idx]);
idx++;
}
}
}
|
h-o-t/entente | tests/fixtures/mod4.ts | export const qux = "qux";
export const quux = 1;
export const quuux = (): boolean => true;
|
h-o-t/entente | tests/project.ts | <reponame>h-o-t/entente
import { assert } from "chai";
import * as ts from "ts-morph";
import { test } from "./harness";
import { createProject } from "../src";
test({
name: "able to create TS project",
fn() {
const project = createProject("./tests/fixtures/ts.ts");
assert(project instanceof ts.Project);
const sourceFiles = project.getSourceFiles();
assert(sourceFiles.length === 2);
},
});
test({
name: "able to create JS project",
fn() {
const project = createProject("./tests/fixtures/js.js");
assert(project instanceof ts.Project);
const sourceFiles = project.getSourceFiles();
assert(sourceFiles.length === 2);
},
});
test({
name: "able to create mixed JS/TS project",
fn() {
const project = createProject("./tests/fixtures/mixed.js");
assert(project instanceof ts.Project);
const sourceFiles = project.getSourceFiles();
assert(sourceFiles.length === 2);
},
});
test({
name: "able to create from tsconfig.json",
fn() {
const project = createProject("./tests/fixtures/tsconfig.json");
assert(project instanceof ts.Project);
const sourceFiles = project.getSourceFiles();
assert(sourceFiles.length === 2);
},
});
|
h-o-t/entente | src/nodes/ExportedDeclarationArray.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ExportedDeclaration } from "./ExportedDeclaration";
export class ExportedDeclarationsArray {
private _declarations?: ExportedDeclaration[];
constructor(private _exportedDeclarations: ts.ExportedDeclarations[]) {}
/** The declarations associated with an export statement. */
get declarations(): ExportedDeclaration[] {
if (!this._declarations) {
this._declarations = this._exportedDeclarations.map(
(ed) => new ExportedDeclaration(ed)
);
}
return this._declarations;
}
/** Assert the length (number) of export declarations associated with an
* export statement. Typically this is 1. */
length(expected: number, msg = "Unexpected length."): this {
const actual = this._exportedDeclarations.length;
if (expected !== actual) {
throw new AssertionError(
msg,
{
actual,
expected,
showDiff: true,
},
this.length
);
}
return this;
}
*[Symbol.iterator](): IterableIterator<ExportedDeclaration> {
let idx = 0;
while (this._exportedDeclarations[idx]) {
yield new ExportedDeclaration(this._exportedDeclarations[idx]);
idx++;
}
}
}
|
h-o-t/entente | tests/harness/index.ts | import { format } from "assertion-error-formatter";
import * as chalk from "chalk";
/* eslint-disable no-console */
interface TestSpec {
name: string;
skip?: boolean | string;
fn(): Promise<void> | void;
}
const testQueue: TestSpec[] = [];
function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
return Boolean(typeof value === "object" && value && "then" in value);
}
const formatOptions = {
colorFns: {
diffAdded: chalk.greenBright,
diffRemoved: chalk.redBright,
errorMessage: chalk.yellowBright,
errorStack: chalk.cyanBright,
},
};
export async function run(): Promise<number> {
const { length } = testQueue;
console.log(`\n${chalk.green("Starting...")}\n\n${length} tests to run.\n`);
let spec: TestSpec | undefined;
let count = 0;
let fail = 0;
while ((spec = testQueue.shift())) {
count++;
if (spec.skip) {
console.log(
`[${count}/${length}] - ${chalk.yellowBright("skip")}${
typeof spec.skip === "string" ? ` (${spec.skip})` : ""
} - ${chalk.yellow(spec.name)}`
);
} else {
try {
const result = spec.fn();
if (isPromiseLike(result)) {
// eslint-disable-next-line no-await-in-loop
await result;
}
console.log(
`[${count}/${length}] - ${chalk.greenBright("pass")} - ${chalk.yellow(
spec.name
)}`
);
} catch (e) {
fail++;
const errorString = format(e, formatOptions);
console.log(
`[${count}/${length}] - ${chalk.redBright("fail")} - ${chalk.yellow(
spec.name
)}\n`
);
console.log(`${errorString}\n`);
}
}
}
console.log(
`\n${chalk.yellow(
"Finished."
)}\n\n${fail} failures out of ${count} tests.\n`
);
return fail;
}
export function test(spec: TestSpec): void {
testQueue.push(spec);
}
|
h-o-t/entente | src/nodes/Exports.ts | <reponame>h-o-t/entente
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ExportedDeclarationsArray } from "./ExportedDeclarationArray";
export class Exports {
constructor(
private _declarations: ReadonlyMap<string, ts.ExportedDeclarations[]>
) {}
/** Assert there is a default export from the module and return the export
* declarations related to the default export. */
default(msg = "No default export."): ExportedDeclarationsArray {
return this.namedExport("default", msg);
}
/**
* Assert there is a named export that matches the `key` and return the export
* declarations related to that named export. When `key` is a regular
* expression, the first named export to match the `key` is returned.
*
* @param key A string or a regular expression to match.
* @param msg An optional message to associate with the error if the assertion
* fails.
*/
namedExport(
key: string | RegExp,
msg = `No export named "${key}".`
): ExportedDeclarationsArray {
let values: ts.ExportedDeclarations[] | undefined;
if (typeof key === "string") {
if (!this._declarations.has(key)) {
throw new AssertionError(
msg,
{
actual: false,
expected: true,
showDiff: false,
},
this.namedExport
);
}
values = this._declarations.get(key)!;
} else {
for (const namedExport of this._declarations.keys()) {
if (namedExport.match(key)) {
values = this._declarations.get(namedExport);
break;
}
}
if (!values) {
throw new AssertionError(
`No export matches "${key.toString()}".`,
{
actual: false,
expected: true,
showDiff: false,
},
this.namedExport
);
}
}
return new ExportedDeclarationsArray(values);
}
*[Symbol.iterator](): IterableIterator<[string, ExportedDeclarationsArray]> {
for (const [key, value] of this._declarations) {
yield [key, new ExportedDeclarationsArray(value)];
}
}
}
|
h-o-t/entente | src/nodes/ClassProperty.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { Expression } from "./Expression";
export class ClassProperty {
constructor(private _node: ts.ClassInstancePropertyTypes) {}
/** Provides the initializer for the property if there is one. */
get initializer(): Expression | undefined {
let value: ts.Expression | undefined;
if (ts.TypeGuards.isParameterDeclaration(this._node)) {
value = this._node.getInitializer();
} else if (ts.TypeGuards.isPropertyDeclaration(this._node)) {
value = this._node.getInitializer();
}
return value ? new Expression(value) : undefined;
}
/** Asserts the property has an inializer and returns the expression. */
hasInitializer(msg = "Expected property to have intializer."): Expression {
const { initializer } = this;
if (!initializer) {
throw new AssertionError(msg, undefined, this.hasInitializer);
}
return initializer;
}
}
|
h-o-t/entente | src/nodes/ClassDeclarations.ts | <filename>src/nodes/ClassDeclarations.ts
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ClassDeclaration } from "./ClassDeclaration";
export class ClassDeclarations {
constructor(private _declarations: ts.ClassDeclaration[]) {}
/** The declarations of classes as an array. */
get declarations(): ClassDeclaration[] {
return this._declarations.map((cd) => new ClassDeclaration(cd));
}
/** Asserts that there is a class with a name that matches the supplied
* value */
includes(
value: string | RegExp,
msg = `Expected a class to match "${String(value)}".`
): ClassDeclarations {
const includeArray = this._declarations.filter((cd) => {
const name = cd.getName();
if (!name) {
return false;
}
return typeof value === "string"
? name.includes(value)
: name.match(value);
});
if (!includeArray.length) {
throw new AssertionError(msg, undefined, this.includes);
}
return new ClassDeclarations(includeArray);
}
/** Asserts the number of classes. */
length(expected: number, msg = "Unexpected number of classes."): this {
const actual = this._declarations.length;
if (this._declarations.length !== expected) {
throw new AssertionError(
msg,
{
actual,
expected,
showDiff: true,
},
this.length
);
}
return this;
}
*[Symbol.iterator](): IterableIterator<ClassDeclaration> {
for (const importDeclaration of this._declarations) {
yield new ClassDeclaration(importDeclaration);
}
}
}
|
h-o-t/entente | src/nodes/ParameterDeclaration.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
export class ParameterDeclaration {
constructor(private _node: ts.ParameterDeclaration) {}
/** Assert the parameter is an object type. If true, return the parameter. */
isObject(msg = "Expected parameter accept an object type."): this {
if (!this._node.getType().isObject()) {
throw new AssertionError(
msg,
{
actual: this._node.getType().getText(this._node),
expected: "object",
showDiff: false,
},
this.isObject
);
}
return this;
}
/** Assert the parameter is optional. If true, return the parameter. */
isOptional(msg = "Expected parameter to be optional."): this {
if (!this._node.isOptional()) {
throw new AssertionError(
msg,
{
actual: false,
expected: true,
showDiff: false,
},
this.isOptional
);
}
return this;
}
/** Assert the parameter is not optional. If true, return the parameter. */
isNotOptional(msg = "Expected parameter to not be optional."): this {
if (this._node.isOptional()) {
throw new AssertionError(
msg,
{
actual: true,
expected: false,
showDiff: false,
},
this.isNotOptional
);
}
return this;
}
}
|
h-o-t/entente | src/assert.ts | <filename>src/assert.ts
import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ClassDeclaration } from "./nodes/ClassDeclaration";
import { FunctionLikeDeclaration } from "./nodes/FunctionLikeDeclaration";
import { SourceFile } from "./nodes/SourceFile";
import { Type } from "./nodes/Type";
/** Throws if the condition is not trueish. */
export function assert(cond: unknown, msg = "Failed assertion."): asserts cond {
if (!cond) {
throw new AssertionError(msg, undefined, assert);
}
}
/** Returns an interfact to make assertions against a class. */
export function assertClass(node: ts.ClassDeclaration): ClassDeclaration {
return new ClassDeclaration(node);
}
/** Returns an interface to make assertions against a function like
* declaration. */
export function assertFunctionLike(
node: ts.FunctionLikeDeclaration
): FunctionLikeDeclaration {
return new FunctionLikeDeclaration(node);
}
/** Returns an interface to make assertions against a source file. */
export function assertSourceFile(node: ts.SourceFile): SourceFile {
return new SourceFile(node);
}
/** Returns an interface to make assertions against a type. */
export function assertType(type: ts.Type): Type {
return new Type(type);
}
|
h-o-t/entente | src/nodes/ImportDeclaration.ts | <reponame>h-o-t/entente<filename>src/nodes/ImportDeclaration.ts
import * as ts from "ts-morph";
import { SourceFile } from "./SourceFile";
export class ImportDeclaration {
constructor(private _node: ts.ImportDeclaration) {}
sourceFile(): SourceFile {
return new SourceFile(this._node.getModuleSpecifierSourceFileOrThrow());
}
}
|
h-o-t/entente | src/nodes/ClassDeclaration.ts | import * as AssertionError from "assertion-error";
import * as ts from "ts-morph";
import { ClassMember } from "./ClassMember";
export class ClassDeclaration {
constructor(private _node: ts.ClassDeclaration) {}
/** Asserts that the class is the default export of the source file. */
isDefaultExport(msg = `Expected class to be the default export.`): this {
if (!this._node.getExportKeyword() || !this._node.getDefaultKeyword()) {
throw new AssertionError(msg, undefined, this.isDefaultExport);
}
return this;
}
/** Asserts that the class is exported from the source file. */
isExported(msg = `Expected class to be exported.`): this {
if (!this._node.getExportKeyword()) {
throw new AssertionError(msg, undefined, this.isExported);
}
return this;
}
/** Asserts that the class has an instance member that matches the supplied
* value. */
member(
value: string | RegExp,
msg = `Expected the class to have a member that matches "${String(value)}".`
): ClassMember[] {
const includeArray = this._node.getInstanceMembers().filter((im) => {
const name = im.getName();
if (!name) {
return false;
}
return typeof value === "string"
? name.includes(value)
: name.match(value);
});
if (!includeArray.length) {
throw new AssertionError(msg, undefined, this.member);
}
return includeArray.map((im) => new ClassMember(im));
}
/** Asserts that the class has an static member that matches the supplied
* value. */
staticMember(
value: string | RegExp,
msg = `Expected the class to have a static member that matches "${String(
value
)}".`
): ClassMember[] {
const includeArray = this._node.getStaticMembers().filter((im) => {
const name = im.getName();
if (!name) {
return false;
}
return typeof value === "string"
? name.includes(value)
: name.match(value);
});
if (!includeArray.length) {
throw new AssertionError(msg, undefined, this.member);
}
return includeArray.map((im) => new ClassMember(im));
}
}
|
crqra/chatops-action | src/events/deploymentError.ts | <gh_stars>1-10
import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deploymentError = actionSlasher.event('deployment-error', {
description: 'An event triggered when a deployment has an error',
async handler() {
const {repository, deploymentId} = chatops.context
if (!deploymentId) {
chatops.setFailed('No deployment ID available...')
return
}
await chatops.octokit.repos.createDeploymentStatus({
...repository,
deployment_id: deploymentId,
state: 'error'
})
chatops.error(
`There was an error with the deployment... ${chatops.Icon.Cry}`
)
}
})
|
crqra/chatops-action | src/chatops/index.ts | <reponame>crqra/chatops-action<filename>src/chatops/index.ts<gh_stars>1-10
import * as core from '@actions/core'
import * as github from '@actions/github'
import {Context} from './context'
import {Log} from './log'
export {Icon} from './log'
export const octokit = github.getOctokit(
core.getInput('token', {required: true}),
{previews: ['flash', 'ant-man']}
)
export const context = new Context(octokit)
const log = new Log(context, octokit)
export const debug = log.debug.bind(log)
export const error = log.error.bind(log)
export const info = log.info.bind(log)
export const warn = log.warning.bind(log)
export const setFailed = log.setFailed.bind(log)
|
crqra/chatops-action | src/events/deploymentLog.ts | <reponame>crqra/chatops-action
import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deploymentLog = actionSlasher.event('deployment-log', {
description: 'An event triggered when a deployment has emitted some log',
async handler() {
chatops.info(chatops.context.message)
}
})
|
crqra/chatops-action | src/commands/cancelDeployment.ts | import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const cancelDeployment = actionSlasher.command('cancel-deployment', {
description: 'Cancels an active deployment',
definition(c) {
c.arg('id', {
type: String,
description: 'The ID of the deployment'
})
},
async handler(args) {
// @ts-expect-error FIXME
const deploymentId = args.id
if (!deploymentId) {
chatops.setFailed('You did not provide any deployment ID...')
return
}
const {repository} = chatops.context
const deployment = await chatops.octokit.repos.getDeployment({
...repository,
deployment_id: deploymentId
})
await chatops.octokit.repos.createDeploymentStatus({
...repository,
deployment_id: deploymentId,
state: 'error',
description: 'Deployment cancelled'
})
chatops.info(
`
${chatops.Icon.BlackCircle} Deployment with ID ${deploymentId} to ${deployment.data.environment} was cancelled...
If you also want do delete the deployment, use the command:
\`\`\`
/delete-deployment --id ${deploymentId}
\`\`\`
`,
{icon: undefined, shouldUpdateComment: true}
)
}
})
|
crqra/chatops-action | src/commands/listDeployments.ts | import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
const query = `
query ListRepositoryDeployments($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
deployments(last: 100) {
nodes {
id
ref {
name
}
databaseId
environment
state
creator {
login
}
}
}
}
}
`
export const listDeployments = actionSlasher.command('list-deployments', {
description: 'Lists all deployments for a specific reference',
definition(c) {
c.arg('ref', {
type: String,
description: 'The reference of the deployment'
})
c.arg('env', {
type: String,
description: 'Only list deployments for this environment'
})
c.arg('state', {
type: String,
description: 'Only list deployments in this state'
})
},
async handler(args) {
// @ts-expect-error FIXME
const ref = args.ref || (await chatops.context.fetchRef())
// @ts-expect-error FIXME
const {env, state} = args
const {repository} = chatops.context
// const envs = env
// ? [env]
// : chatops.context.environments.map(({name}) => name)
const {
repository: {
deployments: {nodes: deployments}
}
} = await chatops.octokit.graphql(query, {...repository})
if (deployments.length === 0) {
chatops.info(`
_No deployments found for ${
env ? `environment ${env}` : 'any environment'
}, reference ${ref} and ${state ? `state ${state}` : 'any state'}._
You can trigger a new deployment with the command:
\`\`\`
/deploy --env <${chatops.context.environments
.map(({name}) => name)
.join(' | ')}>
\`\`\`
`)
return
}
const table = `
| ID | Environment | Ref | State | Created by |
| -- | ----------- | --- | ----- | ---------- |
${deployments
.map(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(deployment: any) =>
`| ${deployment.databaseId} | ${deployment.environment} | ${deployment.ref.name} | ${deployment.state} | @${deployment.creator?.login} |`
)
.join('\n')}
`
chatops.info(table, {
icon: undefined,
shouldUpdateComment: true
})
}
})
|
crqra/chatops-action | src/chatops/log.ts | <filename>src/chatops/log.ts
import * as core from '@actions/core'
import {GitHub} from '@actions/github/lib/utils'
import {Context} from './context'
export interface LogOptions {
icon?: string
shouldUpdateComment: boolean
}
export interface Comment {
id: number
body?: string
}
export enum Icon {
Clock = '🕐',
Rocket = '🚀',
ArrowRight = '➡️',
Check = '✅',
HourGlass = '⏳',
FastForward = '⏩',
Cry = '😢',
Error = '❌',
BlackCircle = '⚫',
Info = 'ℹ️',
Warning = '⚠️',
Magnifier = '🔍'
}
const defaultOptions = {shouldUpdateComment: true}
export class Log {
private _context: Context
private _octokit: InstanceType<typeof GitHub>
constructor(context: Context, octokit: InstanceType<typeof GitHub>) {
this._context = context
this._octokit = octokit
}
debug(
message: string,
options: LogOptions = {...defaultOptions, icon: Icon.Magnifier}
): void {
if (options.shouldUpdateComment) {
this.updateComment(message, options)
}
core.debug(message)
}
info(
message: string,
options: LogOptions = {...defaultOptions, icon: Icon.Info}
): void {
if (options.shouldUpdateComment) {
this.updateComment(message, options)
}
core.info(message)
}
warning(
message: string,
options: LogOptions = {...defaultOptions, icon: Icon.Warning}
): void {
if (options.shouldUpdateComment) {
this.updateComment(message, options)
}
core.warning(message)
}
error(
message: string,
options: LogOptions = {...defaultOptions, icon: Icon.Error}
): void {
if (options.shouldUpdateComment) {
this.updateComment(message, options)
}
core.error(message)
}
setFailed(
message: string,
options: LogOptions = {...defaultOptions, icon: Icon.Error}
): void {
if (options.shouldUpdateComment) {
this.updateComment(message, options)
}
core.setFailed(message)
}
private async updateComment(
message: string,
options?: LogOptions
): Promise<Comment | undefined> {
try {
if (!this._context.commentId || !options?.shouldUpdateComment) {
return
}
const reqOptions = {
...this._context.repository,
comment_id: this._context.commentId
}
const getResp = await this._octokit.issues.getComment(reqOptions)
if (getResp.status !== 200) {
return
}
const body = this.appendBody(
getResp.data.body || '',
`${options?.icon ? `${options.icon} ` : ''} ${message}`
)
const updateResp = await this._octokit.issues.updateComment({
...reqOptions,
body
})
return {
id: updateResp.data.id,
body: updateResp.data.body
}
} catch (error) {
this.setFailed(
`Failed to update comment: ${JSON.stringify(error, null, 2)}`,
{shouldUpdateComment: false}
)
}
}
private trimBody(body: string): string {
return body
.split('\n')
.map(l => l.trimStart())
.join('\n')
}
private appendBody(original: string, body: string): string {
return this.trimBody(`${original}\n${body}`)
}
}
|
crqra/chatops-action | src/commands/poll.ts | <gh_stars>1-10
import {ghPolls} from 'gh-polls'
import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const poll = actionSlasher.command('poll', {
description: 'Creates a poll using [GitHub Polls](https://gh-polls.com/)',
definition(c) {
c.arg('question', {
type: String,
description: 'Subject of the poll'
})
c.arg('option', {
type: [String],
description: 'The options available'
})
},
async handler(args) {
if (!chatops.context.commentId) {
return
}
// @ts-expect-error FIXME
if (args.option.length === 0) {
chatops.error('You did not specified any options for the poll')
return
}
// @ts-expect-error FIXME
const ghPoll = await ghPolls(args.option.map(o => o.replace(/^"|"$/g, '')))
chatops.info(
`
${
// @ts-expect-error FIXME
args.question ? `#### ${args.question.replace(/^"|"$/g, '')}` : ''
}
${ghPoll.map(o => `[![](${o.image})](${o.vote})`).join('\n')}
`,
{icon: undefined, shouldUpdateComment: true}
)
}
})
|
crqra/chatops-action | src/commands/index.ts | <filename>src/commands/index.ts
export * from './cancelDeployment'
export * from './deleteDeployment'
export * from './deploy'
export * from './listDeployments'
export * from './poll'
|
crqra/chatops-action | src/events/deploymentPending.ts | <reponame>crqra/chatops-action
import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deploymentPending = actionSlasher.event('deployment-pending', {
description: 'An event triggered when a deployment is pending',
async handler() {
const {repository, deploymentId} = chatops.context
if (!deploymentId) {
chatops.setFailed('No deployment ID available...')
return
}
await chatops.octokit.repos.createDeploymentStatus({
...repository,
deployment_id: deploymentId,
state: 'pending'
})
chatops.info('Deployment starting soon...', {
icon: chatops.Icon.HourGlass,
shouldUpdateComment: true
})
}
})
|
crqra/chatops-action | src/main.ts | import * as core from '@actions/core'
import * as actionSlasher from './action-slasher'
import * as commands from './commands'
import * as chatops from './chatops'
import * as events from './events'
const run = async (): Promise<void> => {
core.debug(`Payload: ${JSON.stringify(chatops.context.payload, null, 2)}`)
core.debug(`Project: ${chatops.context.project}`)
core.debug(
`Repository: ${JSON.stringify(chatops.context.repository, null, 2)}`
)
core.debug(`Comment ID: ${chatops.context.commentId}`)
core.debug(`Deployment ID: ${chatops.context.deploymentId}`)
core.debug(
`Issue Number: ${chatops.context.issueNumber} (pr? ${chatops.context.isPullRequest})`
)
try {
await actionSlasher.run({commands, events})
} catch (error) {
core.setFailed(error.message || error)
}
}
run()
|
crqra/chatops-action | src/action-slasher/event.ts | <filename>src/action-slasher/event.ts
export interface EventOptions {
description?: string
handler(): Promise<void> | void
}
export class Event implements Event {
name: string
description?: string
handler: EventOptions['handler']
constructor(name: string, options: EventOptions) {
this.name = name
this.description = options.description
// FIXME
// eslint-disable-next-line @typescript-eslint/unbound-method
this.handler = options.handler
}
match(str: string): boolean {
return this.name === str
}
}
export function event(name: string, options: EventOptions): Event {
return new Event(name, options)
}
|
crqra/chatops-action | src/action-slasher/command.ts | import arg from 'arg'
export interface CommandOptions {
description?: string
definition?(c: Command): void
handler(args: unknown): Promise<void> | void
}
export interface CommandArg {
name: string
type: CommandArgType
description?: string
}
export interface CommandArgOptions {
type: CommandArgType
description?: string
}
export type CommandArgType = string | arg.Handler | [arg.Handler]
export class Command implements Command {
name: string
description?: string
args: {[key: string]: CommandArg}
handler: CommandOptions['handler']
constructor(name: string, options: CommandOptions) {
this.name = name
this.description = options.description
this.args = {}
// FIXME
// eslint-disable-next-line @typescript-eslint/unbound-method
this.handler = options.handler
}
arg(name: string, options: CommandArgOptions): void {
this.args[name] = {
name,
type: options.type,
description: options.description
}
}
match(str: string): unknown | undefined {
const argv = str.match(/(?:[^\s"]+|"[^"]*")+/g) || []
if (argv[0] !== this.name) {
return
}
const args = arg(this.argSpec, {argv})
return Object.keys(args)
.filter(a => a !== '_')
.reduce(
(normalizedArgs, argFlag) => ({
...normalizedArgs,
[`${argFlag.replace('--', '')}`]: args[argFlag]
}),
{}
)
}
private get argSpec(): arg.Spec {
return Object.keys(this.args).reduce(
(spec, argName) => ({...spec, [`--${argName}`]: this.args[argName].type}),
{}
)
}
}
export function command(name: string, options: CommandOptions): Command {
const cmd = new Command(name, options)
if (options.definition) {
options.definition(cmd)
}
return cmd
}
|
crqra/chatops-action | src/events/index.ts | <gh_stars>1-10
export * from './deploymentError'
export * from './deploymentFailure'
export * from './deploymentInProgress'
export * from './deploymentLog'
export * from './deploymentPending'
export * from './deploymentSuccess'
|
crqra/chatops-action | src/action-slasher/help.ts | <filename>src/action-slasher/help.ts
import * as github from '@actions/github'
import * as octokit from './octokit'
import {Command, command} from './command'
const getArgumentsList = (cmd: Command): string =>
Object.keys(cmd.args)
.map(argName => {
const arg = cmd.args[argName]
return `* \`--${arg.name}\` -- ${arg.description}`
})
.join('\n')
const getCommandUsageText = (cmd: Command): string => {
return `
#### Name
_${cmd.name}_ -- ${cmd.description}
#### Arguments
${getArgumentsList(cmd)}
`
}
const getCommandNotFoundText = (
name: string,
availableCommands: Command[]
): string => {
return `
The command \`${name}\` doesn't exist. Here's a list of commands available:
${availableCommands
.map(cmd => `* \`${cmd.name}\` -- ${cmd.description}`)
.join('\n')}
Comment \`/help [command]\` to get help for a particular command or \`/help\` for general usage.
`
}
const getGeneralUsageText = (availableCommands: Command[]): string => {
return `
Comment an issue or Pull Request with a command prefixed with a slash (i.e. \`/help\`) to run it.
#### Commands available:
${availableCommands
.map(cmd => `* \`${cmd.name}\` -- ${cmd.description}`)
.join('\n')}
`
}
export const buildHelpCommand = (commands: Command[]): Command =>
command('help', {
description: 'Displays usage information and commands available',
definition(c) {
c.arg('cmd', {
type: String,
description: 'A command to get information about'
})
},
async handler(args) {
if (!github.context.payload.comment?.id) {
return
}
const updateCommentOptions = {
...github.context.repo,
comment_id: github.context.payload.comment.id,
body: ''
}
// @ts-expect-error FIXME
if (args.cmd) {
// @ts-expect-error FIXME
const cmd = commands.find(c => c.name === args.cmd)
updateCommentOptions.body = cmd
? getCommandUsageText(cmd)
: // @ts-expect-error FIXME
getCommandNotFoundText(args.cmd, commands)
} else {
updateCommentOptions.body = getGeneralUsageText(commands)
}
await octokit.octokit.issues.updateComment(updateCommentOptions)
}
})
|
crqra/chatops-action | src/commands/deleteDeployment.ts | import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deleteDeployment = actionSlasher.command('delete-deployment', {
description: 'Deletes a deployment',
definition(c) {
c.arg('id', {
type: String,
description: 'The ID of the deployment'
})
},
async handler(args) {
// @ts-expect-error FIXME
const deploymentId = args.id
if (!deploymentId) {
chatops.setFailed('You did not provide any deployment ID...')
return
}
const {repository} = chatops.context
await chatops.octokit.repos.deleteDeployment({
...repository,
deployment_id: deploymentId
})
chatops.info(`Deployment with ID ${deploymentId} has been deleted...`, {
icon: chatops.Icon.BlackCircle,
shouldUpdateComment: true
})
}
})
|
crqra/chatops-action | src/chatops/context.ts | <filename>src/chatops/context.ts
import * as core from '@actions/core'
import * as github from '@actions/github'
import {GitHub} from '@actions/github/lib/utils'
export interface Environment {
id: string
url?: string
name: string
description: string
default: boolean
}
export interface Repository {
owner: string
repo: string
}
export interface Payload {
environments: Environment[]
project: string
processor: Repository
repository: Repository
issueNumber: number
commentId?: number
deploymentId?: number
}
export class Context {
issueNumber: number
commentId?: number
deploymentId?: number
repository: Repository
project: string
message: string
isPullRequest: boolean
environments: Environment[]
payload: Payload
private _octokit: InstanceType<typeof GitHub>
constructor(octokit: InstanceType<typeof GitHub>) {
const {repo} = github.context
this.payload = this.inputFromJSON('payload', {
environments: this.inputFromJSON('environments', [], {
required: false
}),
issueNumber: github.context.issue.number,
commentId: github.context.payload.comment?.id,
repository: repo,
processor: this.processor,
project: core.getInput('project') || `${repo.owner}/${repo.repo}`
})
this.environments = this.payload.environments
this.project = this.payload.project
this.repository = this.payload.repository
this.deploymentId = this.payload.deploymentId
this.issueNumber = this.payload.issueNumber
this.commentId = this.payload.commentId
this.message = core.getInput('message')
this.isPullRequest = !!github.context.payload.issue?.pull_request
this._octokit = octokit
}
get processor(): Repository {
const [processorOwner, processorRepo] = core
.getInput('processor')
.split('/')
if (!processorOwner || !processorRepo) {
return github.context.repo
}
return {owner: processorOwner, repo: processorRepo}
}
async fetchRef(): Promise<string> {
const input = core.getInput('ref')
if (input) {
return input
}
if (this.isPullRequest) {
const pr = await this._octokit.pulls.get({
...this.repository,
pull_number: this.issueNumber
})
return pr.data.head.ref
}
return github.context.ref
}
findEnvironment(idOrName: string): Environment | undefined {
return this.environments.find(
env => env.id === idOrName || env.name === idOrName
)
}
findDefaultEnvironment(): Environment | undefined {
return this.environments.find(env => env.default)
}
private inputFromJSON<T>(
name: string,
fallback: T,
options?: core.InputOptions
): T {
return JSON.parse(core.getInput(name, options) || JSON.stringify(fallback))
}
}
|
crqra/chatops-action | src/events/deploymentSuccess.ts | import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deploymentSuccess = actionSlasher.event('deployment-success', {
description: 'An event triggered when a deployment is successful',
async handler() {
const {repository, deploymentId} = chatops.context
if (!deploymentId) {
chatops.setFailed('No deployment ID available...')
return
}
await chatops.octokit.repos.createDeploymentStatus({
...repository,
deployment_id: deploymentId,
state: 'success'
})
chatops.info('Deployment finished with success!', {
icon: chatops.Icon.Check,
shouldUpdateComment: true
})
}
})
|
crqra/chatops-action | src/action-slasher/run.ts | <filename>src/action-slasher/run.ts
import * as core from '@actions/core'
import * as github from '@actions/github'
import * as command from './command'
import * as event from './event'
import * as help from './help'
export function run({
commands,
events
}: {
commands: command.Command[] | {[key: string]: command.Command}
events?: event.Event[] | {[key: string]: event.Event}
}): Promise<void> | void {
if (github.context.eventName === 'repository_dispatch') {
if (!events) {
return
}
const eventsList = ('length' in events
? events
: Object.keys(events).map(key => events[key])) as event.Event[]
for (const evt of eventsList) {
if (evt.match(core.getInput('event', {required: true}))) {
evt.handler()
return
}
}
return
}
let commandsList = ('length' in commands
? commands
: Object.keys(commands).map(key => commands[key])) as command.Command[]
const helpCommand = help.buildHelpCommand(commandsList)
// Inject help command to the list
commandsList.push(helpCommand)
// Inject help arg in all commands
commandsList = commandsList.map(cmd => {
cmd.arg('help', {
type: Boolean,
description: `Shows usage information for \`${cmd.name}\` command`
})
return cmd
})
const commentBody = github.context.payload.comment?.body
if (!commentBody) {
return
}
const commentFirstLine = commentBody.split(/\r?\n/)[0].trim()
if (commentFirstLine.length < 2 || commentFirstLine.charAt(0) !== '/') {
return
}
for (const cmd of commandsList) {
const args = cmd.match(commentFirstLine.replace('/', ''))
if (!args) {
continue
}
// @ts-expect-error FIXME
if (args.help) {
helpCommand.handler({cmd: cmd.name})
return
}
try {
cmd.handler(args)
} catch (err) {
core.error(`Error caught in ActionSlasher: ${err.message}`)
core.setFailed(err.message)
}
return
}
// If no command has matched, display help information
helpCommand.handler({cmd: commentFirstLine.split(' ')[0]})
}
|
crqra/chatops-action | src/action-slasher/octokit.ts | import * as core from '@actions/core'
import * as github from '@actions/github'
export const octokit = github.getOctokit(
core.getInput('token', {required: true}),
{previews: ['flash', 'ant-man']}
)
|
crqra/chatops-action | src/action-slasher/index.ts | <gh_stars>1-10
export * from './command'
export * from './event'
export * from './run'
|
crqra/chatops-action | src/commands/deploy.ts | <filename>src/commands/deploy.ts
import * as actionSlasher from '../action-slasher'
import * as chatops from '../chatops'
export const deploy = actionSlasher.command('deploy', {
description: 'Deploys the project to the specified environment',
definition(c) {
c.arg('env', {
type: String,
description: 'The target environment for the deployment'
})
},
async handler(args) {
if (!chatops.context.isPullRequest) {
chatops.setFailed(`ChatOps doesn't support deploying from issues yet`)
return
}
let environment = chatops.context.findDefaultEnvironment()
// @ts-expect-error FIXME
if (args.env) {
// @ts-expect-error FIXME
environment = chatops.context.findEnvironment(args.env)
}
if (!environment) {
chatops.setFailed(
// @ts-expect-error FIXME
`The target environment "${args.env}" is not configured.`
)
return
}
const {repository} = chatops.context
const activeDeployment = (
await Promise.all(
(
await chatops.octokit.repos.listDeployments({
...repository,
environment: environment.name
})
).data.map(async deployment => {
const status = (
await chatops.octokit.repos.listDeploymentStatuses({
...repository,
deployment_id: deployment.id
})
).data[0]
return {
deployment,
status,
active: ['queued', 'pending', 'in_progress'].includes(status.state)
}
})
)
).find(({active}) => active)
if (activeDeployment) {
chatops.setFailed(
`\n${chatops.Icon.Error} A deployment for ${environment.name} environment is already ${activeDeployment.status.state}.
Wait for its completion before triggering a new deployment to this environment.
If you want to cancel the active deployment, use the command:
\`\`\`
/cancel-deployment --id ${activeDeployment.deployment.id}
\`\`\`
`,
{icon: undefined, shouldUpdateComment: true}
)
return
}
const deploymentOptions = {
...repository,
ref: await chatops.context.fetchRef(),
environment: environment.name,
environment_url: environment.url,
description: `Triggered in PR #${chatops.context.issueNumber}`
}
chatops.debug(`DeploymentOptions: ${JSON.stringify(deploymentOptions)}`)
let deployment = await chatops.octokit.repos.createDeployment(
deploymentOptions
)
// Status code === 202 means GitHub performed an auto-merge
// and we have to attempt creating the deployment again
if (deployment.status === 202) {
chatops.info(deployment.data.message || '')
deployment = await chatops.octokit.repos.createDeployment(
deploymentOptions
)
}
// When status code is something else than 201, even if it's an
// auto-merge again, we stop execution
if (deployment.status !== 201) {
chatops.setFailed(
`Could not start a deployment... Endpoint returned ${
deployment.status
}: ${JSON.stringify(deployment.data, null, 2)}`
)
return
}
// Set the status of the deployment to queued as it'll be triggered
// by another workflow which will start in the same state
await chatops.octokit.repos.createDeploymentStatus({
...repository,
deployment_id: deployment.data.id,
state: 'queued'
})
await chatops.octokit.repos.createDispatchEvent({
...chatops.context.processor,
event_type: 'chatops-deploy',
client_payload: {
...chatops.context.payload,
deploymentId: deployment.data.id
}
})
chatops.info(
`\n${chatops.Icon.Clock} Deployment of \`${deploymentOptions.ref}\` to \`${environment.name}\` has been queued (ID: ${deployment.data.id})...`,
{icon: undefined, shouldUpdateComment: true}
)
}
})
|
LutheranWorldRelief/monitoreo_lac | web/js/vue/contact.merge.document.ts | // @ts-ignore
let app = new Vue({
el: "#app",
mixins:[
// @ts-ignore
MergeUrls,
],
data: {
ids:[], // it is shown when the duplicate models were load
name: '', // it is shown when the duplicate models were load
loading: {
all: true, // controls were duplicate models are loaded
modal: true, // controls when to show the loading animation on the modal form
fusion:false, // it indicates if the fusion process has been initialiced
result:false,
},
modelFilter:{
projectId:'',
countryCode:'',
organizationId:'',
nameSearch:''
},
modalState:'select', // stores the state of the modal view [select, resolve, fusion]
modelsAll:[], // stores all the data from all the duplicate models by name
models:[], // stores all the data from all the duplicate models by name
modelSelected:null,
modelsResolve:{},
modelLabels:{},
modelEmpty:{},
modelMerge:{}, // stores all the data from all the duplicate models by name
list_organizations:{}, // stores the organizations listData ( id => name )
list_projects:{}, // stores the projects listData ( id => name )
list_types:{}, // stores the types data_list ( id => name ) values
list_countries:{}, // stores the countries data_list ( id => name ) values
list_education:{}, // stores the countries data_list ( id => name ) values
noShowAttributes:[
'id',
'organizationName',
'created',
'modified',
'errors',
],
noShowFields:[
'id',
'country',
'organization_id',
'education_id',
'type_id',
'created',
'modified',
'errors',
],
fusionResult:null,
fusionFlags:{
result:false
},
errorFlags:{
fusion:false,
finish:false,
},
errorMessage: {
fusion:null,
finish:null,
},
},
methods: {
load: function () {
let self = this;
self.loading.all = true;
self.loadBaseUrl(self.$el);
/* var modelFilter is global */
// @ts-ignore
if(typeof modelFilter !== 'undefined')
// @ts-ignore
self.modelFilter = modelFilter;
// ------------------------------------------------------------------------------ Getting label information
// @ts-ignore
$.get(self.getUrlModelLabels(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelLabels = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar las etiquetas");
console.log("Error al cargar la información de los etiquetas");
});
// ------------------------------------------------------------------------------ Getting Empty Model
// @ts-ignore
$.get(self.getUrlModelEmpty(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelEmpty = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los datos de guardado");
console.log("Error al cargar la información del modelo vacío");
});
// ------------------------------------------------------------------------------ Getting Organization List
// @ts-ignore
$.get(self.getUrlOrganizations(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_organizations = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los datos de organizaciones");
console.log("Error al cargar la información de las organizaciones");
});
// ------------------------------------------------------------------------------ Getting Countries List
// @ts-ignore
$.get(self.getUrlCountries(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_countries = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los datos de los países");
console.log("Problema al cargar la información de los países");
});
// ------------------------------------------------------------------------------ Getting Projects List
// @ts-ignore
$.get(self.getUrlProjects(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_projects = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los datos de los proyectos");
console.log("Problema al cargar los datos de los proyectos");
});
// ------------------------------------------------------------------------------ Getting Types List
// @ts-ignore
$.get(self.getUrlTypes(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_types = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los datos de los tipos de beneficiarios");
console.log("Problema al cargar los datos de los tipos de beneficiarios");
});
// ------------------------------------------------------------------------------ Getting Types List
// @ts-ignore
$.get(self.getUrlEducation(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_education= data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar el catalogo de tipo de educacion");
console.log("Problema al cargar el catalogo de tipo de educacion");
});
// ------------------------------------------------------------------------------ Getting Models
// @ts-ignore
$.get(self.getUrlAllDocs(), self.modelFilter, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelsAll = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al ");
console.log("Error al cargar la información de los contactos");
})
.always(() => {
self.loading.all = false;
});
},
loadModels:function(){
let self = this;
self.loading.all = true;
// @ts-ignore
$.get(self.getUrlAllDocs(), self.modelFilter, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelsAll = data;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al ");
console.log("Error al cargar la información de los contactos");
})
.always(() => {
self.loading.all = false;
});
},
//----------------------------------------------------------------------------------------- MODAL URL FUNCTIONS
fusionCancelar: function (modalName){
let self = this;
self.load.modal = false;
self.load.fusion = false;
switch (self.modalState){
case 'resolve': self.modalState = 'select'; break;
case 'fusion': self.modalState = 'resolve'; break;
case 'finish':
default:
// @ts-ignore
$(modalName).modal('hide');
}
},
fusionExclude: function (model) {
let self = this;
self.models.splice(self.models.indexOf(model), 1);
},
fusionSelect: function () {
let self = this;
self.loading.modal = true;
self.modalState = 'resolve';
self.ids = [];
for (let i=0; i < self.models.length; i++){
self.ids.push(self.models[i].id);
}
// ------------------------------------------------------------------------------ Getting Types List
// @ts-ignore
$.post(self.getUrlDocValues(), { ids: self.ids}, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelMerge = data.values;
let resolve = data.resolve;
for(var attr in resolve){
self.modelMerge[attr] = resolve[attr][0];
}
self.modelsResolve = resolve;
self.loading.modal = false;
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al cargar los registros");
});
},
fusionResolve: function () {
let self = this;
self.modalState = 'fusion';
},
fusionStart: function () {
let self = this;
self.loading.modal = true;
self.loading.fusion = true;
let data = {
id: self.modelSelected,
ids: self.ids,
values: self.modelMerge,
};
// ------------------------------------------------------------------------------ Getting Types List
// @ts-ignore
$.post(self.getUrlFusion(), data, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.fusionResult = data.result;
self.fusionFlags.result = false;
self.loading.modal = false;
self.loading.fusion = false;
self.modalState = 'finish';
})
.fail(() => {
// @ts-ignore
alertify.error("Problema al fusionar los registros de contacto.");
self.loading.modal = false;
self.loading.fusion = false;
});
},
fusionFinish: function (){
let self = this;
self.load();
},
//---------------------------------------------------------------------------------------------- PREPARING DATA
showAttribute: function(field){
let self = this;
return self.noShowAttributes.indexOf(field) != -1 ? false : true;
},
showField: function(field){
let self = this;
return self.noShowFields.indexOf(field) != -1 ? false : true;
},
//---------------------------------------------------------------------------------------------- PREPARING DATA
preparingFusionForm: function (model) {
let self = this;
self.ids = [];
self.models = [];
self.modelMerge = {};
self.modelsResolve = {};
self.modelSelected = null;
self.fusionResult = null;
self.fusionFlags.result = false;
self.loading.modal = true;
self.name = model.document;
self.modalState = 'select';
let url = self.getUrlDoc(self.name);
if (!url) {
self.loading.modal = false;
console.log("No se logró generar la URL para obtener la información del contacto");
}
else{
// @ts-ignore
$.get(url, (data, textStatus, jqXHR)=>{
if(textStatus !== 'success' ) console.log([textStatus, jqXHR]);
self.models = data.models;
})
.fail(()=>{
console.log("No se logró generar la URL para obtener la información del contacto");
})
.always(() => {
self.loading.modal = false;
});
}
return false;
},
btnFiltrarClick: function () {
var self = this;
self.loadModels();
},
btnLimpiarFiltroClick: function () {
var self = this;
self.modelFilter.nameSearch = '';
self.loadModels();
}
},
mounted: function () {
this.load();
}
}); |
LutheranWorldRelief/monitoreo_lac | web/js/vue/contact.merge.modules.ts | let MergeUrls = {
data:{
baseurl:''
},
methods:{
loadBaseUrl: function(elem){
let self = this;
// @ts-ignore
self.baseurl = $(elem).data('baseurl');
},
//---------------------------------------------------------------------------------------------- URL FUNCTIONS
createUrl : function (append) {
return this.baseurl + append;
},
getUrlAll: function () {
return this.createUrl('opt/api-names')
},
getUrlModelLabels: function () {
return this.createUrl('opt/api-labels')
},
getUrlModelEmpty: function () {
return this.createUrl('opt/api-empty')
},
getUrlId: function (id) {
if(!id)
return null;
return this.createUrl('opt/api-contact?id=' + id)
},
getUrlName: function (name) {
if(!name)
return null;
return this.createUrl('opt/api-name?name=' + name)
},
getUrlNameValues: function () {
return this.createUrl('opt/api-name-values')
},
getUrlFusion: function () {
return this.createUrl('opt/api-fusion')
},
getUrlAllDocs: function () {
return this.createUrl('opt/api-docs')
},
getUrlDoc: function (doc) {
if(!doc)
return null;
return this.createUrl('opt/api-doc?doc=' + doc)
},
getUrlDocValues: function () {
return this.createUrl('opt/api-doc-values')
},
getUrlOrganizations: function () {
return this.createUrl('opt/api-organizations')
},
getUrlProjects: function () {
return this.createUrl('opt/api-projects')
},
getUrlCountries: function () {
return this.createUrl('opt/api-countries')
},
getUrlTypes: function () {
return this.createUrl('opt/api-types')
},
getUrlEducation: function () {
return this.createUrl('opt/api-education')
},
}
}; |
LutheranWorldRelief/monitoreo_lac | web/js/vue/project.contact.ts | let appVue = new Vue({
el: "#app",
mixins:[
MergeUrls,
],
data: {
loading: true,
filter:'',
projectId:null,
project:null,
models:[],
count:{
contact:0,
projectContact:0
},
labels:{
contact:{},
projectContact:{}
},
new:{
contact:null,
projectContact:null
},
modal:{
loading:false,
model:{},
contactIndex:null,
contact:{},
errors:{}
}
},
filters: {
uppercase: function(v) {
return v.toUpperCase();
}
}
methods: {
search: function(q){
let self = this;
self.loading = true;
// ------------------------------------------------------------------------------ Getting Models
$.get(self.getUrlAll(), {projectId:self.projectId, q:q}, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.models = data.models;
self.labels = data.labels;
self.count = data.count;
self.new = data.new;
self.project = data.project;
})
.fail(() => {
let msg = "Error al cargar la información de los contactos";
alertify.error(msg);
console.log(msg);
})
.always(() => {
self.loading = false;
});
},
load: function () {
let self = this;
self.projectId = $(self.$el).data('project-id');
self.loadBaseUrl(self.$el);
self.search('');
},
//---------------------------------------------------------------------------------------------- PREPARING DATA
modalCancel:function(modalName){
let self = this;
$(modalName).modal('hide');
},
modalSave:function(modalName){
let self = this;
self.modal.loading = true;
self.modal.errors = {};
let url = self.getUrlSaveProjectContact({
projectId:self.projectId,
contactId:self.modal.contact.id
});
if (!self.modal.contact){
alertify.error("No se consiguió cargar el modelo de Beneficiario");
return;
}
if (self.modal.contactIndex < 0){
alertify.error("No se consiguió cargar el índice del Beneficiario");
return;
}
if (!url) {
self.modal.loading = false;
alertify.error("No se logró generar la URL para obtener la información del contacto");
}
else{
let dataPost = {
ProjectContact: self.modal.model
};
$.post(url, dataPost, ( data, textStatus, jqXHR) =>{
if(textStatus !== 'success' )
console.log([data, textStatus, jqXHR]);
let contactIndex = self.modal.contactIndex;
self.models[contactIndex].projectContactOne = self.modal.model;
$(modalName).modal('hide');
alertify.success('Los datos se han guardado correctamente');
})
.fail((jqXHR, textStatus, errorThrown)=>{
alertify.error('Se ha producido un error. Favor revisar los datos introducidos.');
if (errorThrown == 'error_registro_dato'){
self.modal.errors = jqXHR.responseJSON.projectContact.errors;
}
})
.always(() => {
self.modal.loading = false;
self.modalLoadDatepicker(null);
});
}
},
modalLoadDatepicker: function(event){
let self = this;
let jq = $('.datepicker');
if(jq.data('kvDatepicker')) jq.kvDatepicker('destroy');
jq.kvDatepicker({
format:"yyyy-mm-dd",
language:"es"
});
$('#date_end').kvDatepicker('setDate', self.modal.model.date_end_project);
$('#date_entry').kvDatepicker('setDate', self.modal.model.date_entry_project);
$('#date_end').on('changeDate', function (event) {
self.modal.model.date_end_project = $('#date_end').val();
});
$('#date_entry').on('changeDate', function (event) {
self.modal.model.date_entry_project = $('#date_entry').val();
});
},
modalEdit: function (contact, index) {
let self = this;
if(contact && (index >= 0)){
self.modal.contact = contact;
self.modal.contactIndex = index;
self.modal.errors = {};
if(!contact.projectContactOne)
self.modal.model = Object.assign({}, self.new.projectContact);
else
self.modal.model = Object.assign({}, contact.projectContactOne);
}
return false;
}
},
mounted: function () {
this.load();
}
}); |
LutheranWorldRelief/monitoreo_lac | web/js/vue/contact.merge.import.ts | let app = new Vue({
el: "#app",
mixins:[
MergeUrls,
],
data: {
ids:[], // it is shown when the duplicate models were load
name: '', // it is shown when the duplicate models were load
loading: {
all: true, // controls were duplicate models are loaded
modal: true, // controls when to show the loading animation on the modal form
fusion:false, // it indicates if the fusion process has been initialiced
result:false,
},
modelFilter:{
projectId:'',
countryCode:'',
organizationId:'',
},
modalState:'select', // stores the state of the modal view [select, resolve, fusion]
modelsNames:[], // stores all the data from all the duplicate models by name
models:[], // stores all the data from all the duplicate models by name
modelSelected:null,
modelCurrent:null,
modelsResolve:{},
modelLabels:{},
modelEmpty:{},
modelMerge:{}, // stores all the data from all the duplicate models by name
list_organizations:{}, // stores the organizations listData ( id => name )
list_projects:{}, // stores the projects listData ( id => name )
list_types:{}, // stores the types data_list ( id => name ) values
list_countries:{}, // stores the countries data_list ( id => name ) values
list_education:{}, // stores the countries data_list ( id => name ) values
noShowAttributes:[
'id',
'organizationName',
'created',
'modified',
'errors',
],
noShowFields:[
'id',
'country',
'organization_id',
'education_id',
'type_id',
'created',
'modified',
'errors',
],
fusionResult:null,
fusionFlags:{
result:false
},
errorFlags:{
fusion:false,
finish:false,
},
errorMessage: {
fusion:null,
finish:null,
},
},
methods: {
load: function () {
let self = this;
self.loading.all = true;
self.loadBaseUrl(self.$el);
/* var modelFilter is global */
if(typeof modelFilter !== 'undefined')
self.modelFilter = modelFilter;
/* var modelFilter is global */
if(typeof gModels !== 'undefined')
self.modelsNames = gModels;
// ------------------------------------------------------------------------------ Getting label information
$.get(self.getUrlModelLabels(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelLabels = data;
})
.fail(() => {
alertify.error("Problema al cargar las etiquetas");
console.log("Error al cargar la información de los etiquetas");
});
// ------------------------------------------------------------------------------ Getting Empty Model
$.get(self.getUrlModelEmpty(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelEmpty = data;
})
.fail(() => {
alertify.error("Problema al cargar los datos de guardado");
console.log("Error al cargar la información del modelo vacío");
});
// ------------------------------------------------------------------------------ Getting Organization List
$.get(self.getUrlOrganizations(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_organizations = data;
})
.fail(() => {
alertify.error("Problema al cargar los datos de organizaciones");
console.log("Error al cargar la información de las organizaciones");
});
// ------------------------------------------------------------------------------ Getting Countries List
$.get(self.getUrlCountries(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_countries = data;
})
.fail(() => {
alertify.error("Problema al cargar los datos de los países");
console.log("Problema al cargar la información de los países");
});
// ------------------------------------------------------------------------------ Getting Projects List
$.get(self.getUrlProjects(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_projects = data;
})
.fail(() => {
alertify.error("Problema al cargar los datos de los proyectos");
console.log("Problema al cargar los datos de los proyectos");
});
// ------------------------------------------------------------------------------ Getting Types List
$.get(self.getUrlTypes(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_types = data;
})
.fail(() => {
alertify.error("Problema al cargar los datos de los tipos de beneficiarios");
console.log("Problema al cargar los datos de los tipos de beneficiarios");
});
// ------------------------------------------------------------------------------ Getting Types List
$.get(self.getUrlEducation(), (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.list_education= data;
})
.fail(() => {
alertify.error("Problema al cargar el catalogo de tipo de educacion");
console.log("Problema al cargar el catalogo de tipo de educacion");
});
},
removingFromDuplicateListImported:function(ids){
let self = this;
let indexes = [];
let models = self.modelsNames.filter(function (model, index) {
if (ids.indexOf(model.contact_id * 1) !== -1){
indexes.push(index);
return true;
}
return false;
});
console.log([models, ids, indexes, self.modelsNames]);
$.each(models, function (index, model) {
let i = self.modelsNames.indexOf(model);
console.log(self.modelsNames.splice(i, 1));
});
},
//----------------------------------------------------------------------------------------- MODAL URL FUNCTIONS
fusionCancelar: function (modalName){
let self = this;
self.load.modal = false;
self.load.fusion = false;
switch (self.modalState){
case 'resolve': self.modalState = 'select'; break;
case 'fusion': self.modalState = 'resolve'; break;
case 'finish':
default:
$(modalName).modal('hide');
}
},
fusionExclude: function (model) {
let self = this;
self.models.splice(self.models.indexOf(model), 1);
},
fusionSelect: function () {
let self = this;
self.loading.modal = true;
self.modalState = 'resolve';
self.ids = [];
for (let i=0; i < self.models.length; i++){
self.ids.push(self.models[i].id);
}
// ------------------------------------------------------------------------------ Getting Types List
$.post(self.getUrlNameValues(), { ids: self.ids}, (data, textStatus, jqXHR) => {
if(textStatus != 'success' ) console.log([textStatus, jqXHR]);
self.modelMerge = data.values;
let resolve = data.resolve;
for(var attr in resolve){
self.modelMerge[attr] = resolve[attr][0];
}
self.modelsResolve = resolve;
self.loading.modal = false;
})
.fail(() => {
alertify.error("Problema al cargar los registros");
});
},
fusionResolve: function () {
let self = this;
self.modalState = 'fusion';
},
fusionStart: function () {
let self = this;
self.loading.modal = true;
self.loading.fusion = true;
let data = {
id: self.modelSelected,
ids: self.ids,
values: self.modelMerge,
};
// ------------------------------------------------------------------------------ Getting Types List
$.post(self.getUrlFusion(), data, (data, textStatus, jqXHR) => {
if(textStatus != 'success' )
console.log([textStatus, jqXHR]);
else{
self.removingFromDuplicateListImported(self.ids);
}
self.fusionResult = data.result;
self.fusionFlags.result = false;
self.loading.modal = false;
self.loading.fusion = false;
self.modalState = 'finish';
})
.fail(() => {
alertify.error("Problema al fusionar los registros de contacto.");
self.loading.modal = false;
self.loading.fusion = false;
});
},
fusionFinish: function (){
let self = this;
if (self.modelCurrent)
{
// var index = self.modelsNames.indexOf(self.modelCurrent);
// self.modelsNames.splice(index, 1);
self.modelCurrent = null;
}
},
//---------------------------------------------------------------------------------------------- PREPARING DATA
showAttribute: function(field){
let self = this;
return self.noShowAttributes.indexOf(field) != -1 ? false : true;
},
showField: function(field){
let self = this;
return self.noShowFields.indexOf(field) != -1 ? false : true;
},
//---------------------------------------------------------------------------------------------- PREPARING DATA
preparingFusionForm: function (model) {
let self = this;
self.ids = [];
self.models = [];
self.modelMerge = {};
self.modelsResolve = {};
self.modelSelected = null;
self.fusionResult = null;
self.fusionFlags.result = false;
self.modelCurrent = model;
self.loading.modal = true;
self.name = model.contact_name;
self.modalState = 'select';
let url = self.getUrlId(model.contact_id);
if (!url) {
self.loading.modal = false;
console.log("No se logró generar la URL para obtener la información del contacto");
}
else{
$.get(url, (data, textStatus, jqXHR)=>{
if(textStatus !== 'success' ) console.log([textStatus, jqXHR]);
self.models = data.models;
})
.fail(()=>{
console.log("No se logró generar la URL para obtener la información del contacto");
})
.always(() => {
self.loading.modal = false;
});
}
return false;
}
},
mounted: function () {
this.load();
}
}); |
LutheranWorldRelief/monitoreo_lac | web/js/vue/project.contact.url.ts | <filename>web/js/vue/project.contact.url.ts
let MergeUrls = {
data:{
baseurl:''
},
methods:{
loadBaseUrl: function(elem){
let self = this;
self.baseurl = $(elem).data('baseurl');
},
//---------------------------------------------------------------------------------------------- URL FUNCTIONS
createUrl : function (append, params) {
let url = this.baseurl + append;
if (params)
url += '?' + $.param(params);
return url;
},
getUrlAll: function (params) {
return this.createUrl('project/api-contacts', params)
},
getUrlSaveProjectContact: function (params) {
return this.createUrl('project/api-contact', params)
},
}
}; |
nobrayner/raid-stats-poc | types/queries.d.ts | <reponame>nobrayner/raid-stats-poc<filename>types/queries.d.ts
interface PullStats {
createdAt: string
additions: number
deletions: number
changedFiles: number
commits: {
totalCount: number
}
}
interface CommitResult {
pageInfo: {
hasNextPage: boolean
endCursor: string | null
}
nodes: Commit[]
}
interface Commit {
oid: string
additions: number
deletions: number
author: {
user: {
avatarUrl: string
login: string
}
}
parents: {
totalCount
}
associatedPullRequests: {
totalCount: number
nodes: {
baseRef: {
repository: {
nameWithOwner: string
}
}
}[]
}
} |
nobrayner/raid-stats-poc | src/utils.ts | <gh_stars>0
export const getStatsFromCommits = (raidRepoWithOwner: string, commits: Commit[] | undefined): UserStats[] => {
if (!commits) return []
return Object.values(commits.reduce<{ [key: string]: UserStats }>((stats, commit) => {
if (
!commit.author?.user?.login // Exclude null users
|| commit.parents.totalCount > 1 // Exclude Merge commits
|| commit.associatedPullRequests.nodes.filter(
node => node.baseRef?.repository?.nameWithOwner !== raidRepoWithOwner
).length > 0 // Exclude commits from PRs not to the raid repo
) {
// console.log(JSON.stringify(commit))
return stats
}
if (commit.author.user.login in stats) {
stats[commit.author.user.login].additions += commit.additions
stats[commit.author.user.login].deletions += commit.deletions
stats[commit.author.user.login].commits += 1
} else {
stats[commit.author.user.login] = {
user: commit.author.user.login,
avatarUrl: commit.author.user.avatarUrl,
additions: commit.additions,
deletions: commit.deletions,
commits: 1,
}
}
return stats
}, {}))
} |
nobrayner/raid-stats-poc | src/__tests__/App.test.ts | import { render, screen } from '@testing-library/svelte'
import App from '../App.svelte'
describe('<App>', () => {
it('renders learn svelte link', () => {
render(App)
expect(screen.getByText(/learn svelte/i)).toBeInTheDocument()
})
})
|
nobrayner/raid-stats-poc | types/stats.d.ts | <filename>types/stats.d.ts
interface UserStats {
user: string
avatarUrl: string
additions: number
deletions: number
commits: number
} |
nobrayner/raid-stats-poc | src/queries.ts | <gh_stars>0
import { GraphQLClient, gql } from 'graphql-request'
const client = new GraphQLClient('https://api.github.com/graphql', {
headers: {
authorization: `bearer ${import.meta.env.SNOWPACK_PUBLIC_GITHUB_PAT}`
}
})
export const getRepoDetails = async (owner: string, repo: string, prid: number) => {
const result = await client.request(
gql`
query pr($repo: String!, $owner: String!, $prid: Int!) {
repository(name: $repo, owner: $owner) {
pullRequest(number: $prid) {
createdAt
additions
deletions
changedFiles
commits {
totalCount
}
}
}
}
`,
{
repo,
owner,
prid,
}
)
return result.repository.pullRequest as PullStats
}
export const getAllUserStatsFromRepoSince = async(owner: string, repo: string, since: string, after: string | null): Promise<Commit[]> => {
const result: CommitResult = (await client.request(
gql`
query commits($since: GitTimestamp!, $repo: String!, $owner: String!) {
repository(name: $repo, owner: $owner) {
defaultBranchRef {
target {
... on Commit {
history(since: $since${after ? `, after: "${after}"` : ''}) {
pageInfo {
hasNextPage
endCursor
}
nodes {
oid
message
additions
deletions
author {
user {
avatarUrl
login
}
}
parents {
totalCount
}
associatedPullRequests(first: 100) {
totalCount
nodes {
baseRef {
repository {
nameWithOwner
}
}
}
}
}
}
}
}
}
}
}
`,
{
since,
repo,
owner,
}
)).repository.defaultBranchRef.target.history
return result.pageInfo.hasNextPage ? [...result.nodes, ...(await getAllUserStatsFromRepoSince(owner, repo, since, result.pageInfo.endCursor))] : result.nodes
} |
coliff/hint | packages/hint-compat-api/tests/utils/browsers.ts | import test from 'ava';
import { joinBrowsers } from '../../src/utils/browsers';
test('disjoint', (t) => {
t.deepEqual(
joinBrowsers({
browsers: ['chrome 74', 'chrome 76'],
details: new Map([
['chrome 74', { versionAdded: '77' }],
['chrome 76', { versionAdded: '77' }]
])
}),
'Chrome < 77'
);
});
test('range', (t) => {
t.deepEqual(
joinBrowsers({
browsers: ['firefox 65', 'firefox 66', 'and_ff 66'],
details: new Map([
['firefox 65', { versionAdded: '67' }],
['firefox 66', { versionAdded: '67' }],
['and_ff 66', { versionAdded: '67' }]
])
}),
'Firefox < 67, Firefox Android < 67'
);
});
test('removed then re-added', (t) => {
t.deepEqual(
joinBrowsers({
browsers: ['opera 16'],
details: new Map([
['opera 16', { versionAdded: '30', versionRemoved: '15'}]
])
}),
'Opera 15-30'
);
});
test('removed', (t) => {
t.deepEqual(
joinBrowsers({
browsers: ['opera 15'],
details: new Map([
['opera 15', { versionRemoved: '15' }]
])
}),
'Opera 15+'
);
});
|
coliff/hint | packages/utils/tests/compat/browsers.ts | import test from 'ava';
import { Identifier } from 'mdn-browser-compat-data/types';
import { getUnsupportedBrowsers } from '../../src/compat/browsers';
test('Handles complex support', (t) => {
/* eslint-disable */
const keyframes: Identifier = {
__compat: {
support: {
opera: [
{
version_added: "30"
},
{
prefix: "-webkit-",
version_added: "15"
},
{
version_added: "12.1",
version_removed: "15"
},
{
prefix: "-o-",
version_added: "12",
version_removed: "15"
}
]
}
}
} as any;
/* eslint-enable */
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 12'])!.browsers, ['opera 12'], 'Before first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 12.1']), null, 'At first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 13']), null, 'During first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 15'])!.browsers, ['opera 15'], 'After first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 29'])!.browsers, ['opera 29'], 'Before second unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 30']), null, 'At second unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 31']), null, 'After second unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 11'])!.browsers, ['opera 11'], 'Before -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 12']), null, 'At -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 12']), null, 'During -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 15'])!.browsers, ['opera 15'], 'After -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-webkit-', ['opera 14'])!.browsers, ['opera 14'], 'Before -webkit- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-webkit-', ['opera 15']), null, 'At -webkit- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-webkit-', ['opera 16']), null, 'During -webkit- support');
});
test('Handles supported prefix', (t) => {
/* eslint-disable */
const maxContent: Identifier = {
__compat: {
support: {
firefox: [
{ version_added: "66" },
{
prefix: "-moz-",
version_added: "41",
}
]
}
}
} as any;
/* eslint-enable */
t.deepEqual(getUnsupportedBrowsers(maxContent, '', ['firefox 66']), null);
t.deepEqual(getUnsupportedBrowsers(maxContent, '', ['firefox 65'])!.browsers, ['firefox 65']);
t.deepEqual(getUnsupportedBrowsers(maxContent, '', ['firefox 41'])!.browsers, ['firefox 41']);
t.deepEqual(getUnsupportedBrowsers(maxContent, '', ['firefox 40'])!.browsers, ['firefox 40']);
t.deepEqual(getUnsupportedBrowsers(maxContent, '-moz-', ['firefox 66']), null);
t.deepEqual(getUnsupportedBrowsers(maxContent, '-moz-', ['firefox 65']), null);
t.deepEqual(getUnsupportedBrowsers(maxContent, '-moz-', ['firefox 41']), null);
t.deepEqual(getUnsupportedBrowsers(maxContent, '-moz-', ['firefox 40'])!.browsers, ['firefox 40']);
});
test('Handles unsupported prefix', (t) => {
/* eslint-disable */
const appearance: Identifier = {
__compat: {
support: {
firefox: {
prefix: "-moz-",
version_added: "1"
},
}
}
} as any;
/* eslint-enable */
t.deepEqual(getUnsupportedBrowsers(appearance, '', ['firefox 1'])!.browsers, ['firefox 1']);
t.deepEqual(getUnsupportedBrowsers(appearance, '-webkit-', ['firefox 1'])!.browsers, ['firefox 1']);
t.deepEqual(getUnsupportedBrowsers(appearance, '-moz-', ['firefox 1']), null);
});
test('Handles multiple supported prefixes', (t) => {
/* eslint-disable */
const boxFlex: Identifier = {
__compat: {
support: {
firefox: [
{
prefix: "-moz-",
version_added: true
},
{
prefix: "-webkit-",
version_added: "49"
}
],
}
}
} as any;
/* eslint-enable*/
t.deepEqual(getUnsupportedBrowsers(boxFlex, '', ['firefox 48'])!.browsers, ['firefox 48']);
t.deepEqual(getUnsupportedBrowsers(boxFlex, '-moz-', ['firefox 48']), null);
t.deepEqual(getUnsupportedBrowsers(boxFlex, '-webkit-', ['firefox 48'])!.browsers, ['firefox 48']);
t.deepEqual(getUnsupportedBrowsers(boxFlex, '', ['firefox 49'])!.browsers, ['firefox 49']);
t.deepEqual(getUnsupportedBrowsers(boxFlex, '-moz-', ['firefox 49']), null);
t.deepEqual(getUnsupportedBrowsers(boxFlex, '-webkit-', ['firefox 49']), null);
});
test('Handles removed features', (t) => {
/* eslint-disable */
const boxLines: Identifier = {
__compat: {
support: {
chrome: {
version_added: true,
version_removed: "67",
prefix: "-webkit-"
},
}
}
} as any;
/* eslint-enable */
t.deepEqual(getUnsupportedBrowsers(boxLines, '-webkit-', ['chrome 66']), null);
t.deepEqual(getUnsupportedBrowsers(boxLines, '-webkit-', ['chrome 67'])!.browsers, ['chrome 67']);
t.deepEqual(getUnsupportedBrowsers(boxLines, '-webkit-', ['chrome 66', 'chrome 67'])!.browsers, ['chrome 67']);
});
test('Includes accurate details', (t) => {
/* eslint-disable */
const keyframes: Identifier = {
__compat: {
support: {
opera: [
{
version_added: "30"
},
{
prefix: "-webkit-",
version_added: "15"
},
{
version_added: "12.1",
version_removed: "15"
},
{
prefix: "-o-",
version_added: "12",
version_removed: "15"
}
]
}
}
} as any;
/* eslint-enable */
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 12'])!.details.get('opera 12'), { versionAdded: '12.1' }, 'Before first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 15'])!.details.get('opera 15'), { versionAdded: '30', versionRemoved: '15' }, 'After first unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '', ['opera 29'])!.details.get('opera 29'), { versionAdded: '30', versionRemoved: '15' }, 'Before second unprefixed support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 11'])!.details.get('opera 11'), { versionAdded: '12' }, 'Before -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-o-', ['opera 15'])!.details.get('opera 15'), { versionRemoved: '15' }, 'After -o- support');
t.deepEqual(getUnsupportedBrowsers(keyframes, '-webkit-', ['opera 14'])!.details.get('opera 14'), { versionAdded: '15' }, 'Before -webkit- support');
});
|
coliff/hint | packages/hint/tests/lib/cli/analyze.ts | <reponame>coliff/hint
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';
import anyTest, { TestInterface, ExecutionContext } from 'ava';
import * as utils from '@hint/utils';
import { Problem, Severity } from '@hint/utils/dist/src/types/problems';
import {
AnalyzeOptions,
AnalyzerError,
AnalyzerResult,
CLIOptions,
CreateAnalyzerOptions,
Endpoint,
UserConfig,
HintsConfigObject
} from '../../../src/lib/types';
import { AnalyzerErrorStatus } from '../../../src/lib/enums/error-status';
const actions = { _: ['http://localhost/'], language: 'en-US' } as CLIOptions;
const actionsFS = { _: ['./'], language: 'en-US' } as CLIOptions;
class FakeAnalyzer {
public constructor() {
}
public analyze(endpoints: Endpoint | Endpoint[], options: AnalyzeOptions = {}): Promise<AnalyzerResult[]> {
return Promise.resolve([]);
}
public async format() {
}
public resources() {
}
public static create() {
}
}
type AskQuestion = () => any;
type Logger = {
error: (text: string) => any;
log: (text: string) => any;
};
type Spinner = {
fail: () => void;
start: () => void;
succeed: () => void;
text: string;
};
type Ora = {
default: () => Spinner;
};
type Analyzer = {
Analyzer: () => void;
}
type AppInsight = {
disable: () => void;
enable: () => void;
isConfigured: () => boolean;
isEnabled: () => boolean;
trackEvent: (event: string, data: any) => void;
};
type ConfigStore = {
get: (key: string) => any;
set: (key: string, value: any) => void;
};
type AnalyzeContext = {
analyzer: Analyzer;
appInsight: AppInsight;
askQuestion: AskQuestion;
configStore: ConfigStore;
errorSpy: sinon.SinonSpy<[string]>;
failSpy: sinon.SinonSpy<[]>;
getHintsFromConfiguration: (userConfig: UserConfig) => HintsConfigObject;
logger: Logger;
logSpy: sinon.SinonSpy<[string]>;
ora: Ora;
sandbox: sinon.SinonSandbox;
spinner: Spinner;
startSpy: sinon.SinonSpy<[]>;
succeedSpy: sinon.SinonSpy<[]>;
};
const test = anyTest.serial as TestInterface<AnalyzeContext>;
const initContext = (t: ExecutionContext<AnalyzeContext>) => {
const sandbox = sinon.createSandbox();
const spinner = {
fail() { },
start() { },
succeed() { },
text: ''
};
t.context.logger = {
error(text: string) { },
log(text: string) { }
};
t.context.logSpy = sandbox.spy(t.context.logger, 'log');
t.context.errorSpy = sandbox.spy(t.context.logger, 'error');
t.context.spinner = spinner;
t.context.ora = {
default() {
return spinner;
}
};
t.context.startSpy = sandbox.spy(spinner, 'start');
t.context.failSpy = sandbox.spy(spinner, 'fail');
t.context.succeedSpy = sandbox.spy(spinner, 'succeed');
t.context.askQuestion = () => { };
t.context.sandbox = sandbox;
t.context.getHintsFromConfiguration = (userConfig: UserConfig) => {
return {};
};
const analyzer: Analyzer = { Analyzer: function Analyzer() { } };
analyzer.Analyzer.prototype.create = (userConfiguration: UserConfig, options: CreateAnalyzerOptions) => { };
analyzer.Analyzer.prototype.getUserConfig = (filePath?: string): UserConfig | null => {
return null;
};
t.context.analyzer = analyzer;
(t.context.analyzer.Analyzer as any).create = (userConfiguration: UserConfig, options: CreateAnalyzerOptions): Analyzer => {
return {} as Analyzer;
};
(t.context.analyzer.Analyzer as any).getUserConfig = (filePath?: string): UserConfig | null => {
return null;
};
t.context.appInsight = {
disable() { },
enable() { },
isConfigured() {
return false;
},
isEnabled() {
return false;
},
trackEvent(event: string, data: any) { }
};
t.context.configStore = {
get(key: string) {
return false;
},
set(key: string, value: any) { }
};
};
const loadScript = (context: AnalyzeContext, isCi: boolean = false) => {
const script = proxyquire('../../../src/lib/cli/analyze', {
'../': {
createAnalyzer: (context.analyzer.Analyzer as any).create,
getUserConfig: (context.analyzer.Analyzer as any).getUserConfig
},
'@hint/utils': {
appInsights: context.appInsight,
configStore: utils.configStore,
debug: utils.debug,
getHintsFromConfiguration: context.getHintsFromConfiguration,
logger: context.logger,
misc: {
askQuestion: context.askQuestion,
cutString: utils.misc.cutString,
mergeEnvWithOptions: (options: any) => {
return options;
}
},
network: utils.network,
npm: utils.npm,
packages: utils.packages
},
'is-ci': isCi,
ora: context.ora
});
return script.default;
};
test.beforeEach(initContext);
test.afterEach.always((t) => {
t.context.sandbox.restore();
});
test('If there is no valid user config, it should use `web-recommended` as default configuration', async (t) => {
const sandbox = t.context.sandbox;
const createAnalyzerStub = sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(new FakeAnalyzer());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns(null as any);
sandbox.stub(t.context, 'askQuestion').resolves(false);
const analyze = loadScript(t.context);
await analyze(actions);
t.true(createAnalyzerStub.calledOnce);
t.deepEqual(createAnalyzerStub.args[0][0], { extends: ['web-recommended'], language: 'en-US' });
});
test('If there is no valid user config, it should use `web-recommended` as default configuration and use formatters `stylish` and `html` if it is running in CI', async (t) => {
const sandbox = t.context.sandbox;
const createAnalyzerStub = sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(new FakeAnalyzer());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns(null as any);
sandbox.stub(t.context, 'askQuestion').resolves(false);
const analyze = loadScript(t.context, true);
await analyze(actions);
t.true(createAnalyzerStub.calledOnce);
t.deepEqual(createAnalyzerStub.args[0][0], { extends: ['web-recommended'], formatters: ['html', 'stylish'], language: 'en-US' });
});
test('If there is no valid user config and the target is an existing filesystem path, it should use `development` as default configuration', async (t) => {
const sandbox = t.context.sandbox;
const createAnalyzerStub = sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(new FakeAnalyzer());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns(null as any);
sandbox.stub(t.context, 'askQuestion').resolves(false);
const analyze = loadScript(t.context);
await analyze(actionsFS);
t.true(createAnalyzerStub.calledOnce);
t.deepEqual(createAnalyzerStub.args[0][0], { extends: ['development'], language: 'en-US' });
});
test('If there is no valid user config and the target is an existing filesystem path, it should use `development` as default configuration and use formatters `stylish` and `html` if it is running in CI', async (t) => {
const sandbox = t.context.sandbox;
const createAnalyzerStub = sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(new FakeAnalyzer());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns(null as any);
sandbox.stub(t.context, 'askQuestion').resolves(false);
const analyze = loadScript(t.context, true);
await analyze(actionsFS);
t.true(createAnalyzerStub.calledOnce);
t.deepEqual(createAnalyzerStub.args[0][0], { extends: ['development'], formatters: ['html', 'stylish'], language: 'en-US' });
});
test('If there is no valid user config and user refuses to use the default or to create a configuration file, it should exit with code 1', async (t) => {
const sandbox = t.context.sandbox;
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns(null as any);
const createAnalyzerStub = sandbox.stub(t.context.analyzer.Analyzer as any, 'create')
.onFirstCall()
.throws(new AnalyzerError('Missed configuration', AnalyzerErrorStatus.ConfigurationError));
const askQuestionDefaultStub = sandbox.stub(t.context, 'askQuestion').resolves(false);
const analyze = loadScript(t.context);
const result = await analyze(actions);
t.true(askQuestionDefaultStub.calledOnce);
t.false(result);
t.true(createAnalyzerStub.calledOnce);
});
test('If configuration file exists, it should use it', async (t) => {
const sandbox = t.context.sandbox;
const createAnalyzerSpy = sandbox.stub(t.context.analyzer.Analyzer as any, 'create');
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const customConfigOptions = ({ _: ['http://localhost'], config: 'configfile.cfg' } as CLIOptions);
const analyze = loadScript(t.context);
await analyze(customConfigOptions);
t.true(createAnalyzerSpy.called);
});
test('If the scan returns an error, it should exit with code 1 and call to analyzer.format', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.targetEndCallback!({
problems: [{ severity: Severity.error } as Problem],
url: 'https://example.com'
});
return [];
});
const analyzerFormatSpy = sandbox.spy(fakeAnalyzer, 'format');
sandbox.stub(t.context, 'askQuestion').resolves(false);
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
const exitCode = await analyze(actions);
t.false(exitCode);
t.true(analyzerFormatSpy.calledOnce);
});
test('If the scan returns an error, it should call to spinner.fail()', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.targetEndCallback!({
problems: [{ severity: Severity.error } as Problem],
url: 'https://example.com'
});
return [];
});
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
await analyze(actions);
t.true(t.context.failSpy.calledOnce);
});
test('If the scan throws an exception, it should exit with code 1', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').rejects(new Error());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
const result = await analyze(actions);
t.false(result);
});
test('If the scan throws an exception, it should call to spinner.fail()', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').rejects(new Error());
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
await analyze(actions);
t.true(t.context.failSpy.calledOnce);
});
test('If the scan returns no errors, it should exit with code 0 and call analyzer.format', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.targetEndCallback!({
problems: [{ severity: 0 } as Problem],
url: 'https://example.com'
});
return [];
});
const analyzerFormatSpy = sandbox.spy(fakeAnalyzer, 'format');
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
const exitCode = await analyze(actions);
t.true(exitCode);
t.true(analyzerFormatSpy.calledOnce);
});
test('If there is no errors analyzing the url, it should call to spinner.succeed()', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.targetEndCallback!({
problems: [{ severity: 0 } as Problem],
url: 'https://example.com'
});
return [];
});
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
await analyze(actions);
t.true(t.context.succeedSpy.calledOnce);
});
test('updateCallback should write a message in the spinner', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.updateCallback!({
message: 'Downloading http://localhost/',
url: 'http://example.com'
});
return [];
});
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
await analyze(actions);
t.is(t.context.spinner.text, 'Downloading http://localhost/');
});
test('If there is missing or incompatible packages, they should be tracked', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').throws(new AnalyzerError('error', AnalyzerErrorStatus.ResourceError, { connector: null, formatters: [], hints: [], incompatible: ['hint2'], missing: ['hint1'], parsers: [] }));
sandbox.stub(fakeAnalyzer, 'analyze').callsFake(async (targets: Endpoint | Endpoint[], options?: AnalyzeOptions) => {
await options!.updateCallback!({
message: 'Downloading http://localhost/',
url: 'http://example.com'
});
return [];
});
sandbox.stub(t.context, 'askQuestion').resolves(false);
const appInsightTrackEventSpy = sandbox.spy(t.context.appInsight, 'trackEvent');
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({});
const analyze = loadScript(t.context);
try {
await analyze(actions);
} catch {
// empty
}
t.true(appInsightTrackEventSpy.calledTwice);
t.is(appInsightTrackEventSpy.args[0][0], 'missing');
t.deepEqual(appInsightTrackEventSpy.args[0][1], ['hint1']);
t.is(appInsightTrackEventSpy.args[1][0], 'incompatible');
t.deepEqual(appInsightTrackEventSpy.args[1][1], ['hint2']);
});
test('If no sites are defined, it should return false', async (t) => {
const analyze = loadScript(t.context);
const result = await analyze({ _: [] } as any);
t.false(result);
});
test('If there is no errors analyzing the url, and it is the second time running a scan, and the user confirm telemetry, telemetry should be enabled', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').resolves();
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({ connector: { name: 'puppeteer' } });
sandbox.stub(t.context.appInsight, 'isConfigured').returns(false);
sandbox.stub(t.context.configStore, 'get').returns(true);
sandbox.stub(t.context, 'askQuestion').resolves(true);
const appInsightEnableSpy = sandbox.spy(t.context.appInsight, 'enable');
const appInsightTrackEventSpy = sandbox.spy(t.context.appInsight, 'trackEvent');
const analyze = loadScript(t.context);
await analyze(actions);
const args = appInsightTrackEventSpy.args;
t.true(appInsightEnableSpy.calledOnce);
t.true(appInsightTrackEventSpy.calledThrice);
t.is(args[1][0], 'SecondRun');
t.is(args[2][0], 'analyze');
});
test('Telemetry should trim options from a connector', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').resolves();
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({
connector: {
name: 'puppeteer',
options: {
auth: {
password: '<PASSWORD>',
submit: 'submitButton',
user: 'userInput'
}
}
}
});
const appInsightTrackEventSpy = sandbox.spy(t.context.appInsight, 'trackEvent');
const analyze = loadScript(t.context);
await analyze(actions);
t.falsy(appInsightTrackEventSpy.args[0][1].connector.options);
});
test('Telemetry should remove properties from rules', async (t) => {
const sandbox = t.context.sandbox;
const fakeAnalyzer = new FakeAnalyzer();
sandbox.stub(t.context.analyzer.Analyzer as any, 'create').returns(fakeAnalyzer);
sandbox.stub(fakeAnalyzer, 'analyze').resolves();
sandbox.stub(t.context.analyzer.Analyzer as any, 'getUserConfig').returns({
connector: { name: 'puppeteer' },
hints: {}
});
sandbox.stub(t.context, 'getHintsFromConfiguration').returns({
hint1: ['error', {
options1: 'value1',
options2: 'value2'
}],
hint2: ['warning', { option: false }]
});
sandbox.stub(t.context.appInsight, 'isConfigured').returns(false);
sandbox.stub(t.context.configStore, 'get').returns(true);
sandbox.stub(t.context, 'askQuestion').resolves(true);
const appInsightTrackEventSpy = sandbox.spy(t.context.appInsight, 'trackEvent');
const analyze = loadScript(t.context);
await analyze(actions);
const hints = appInsightTrackEventSpy.args[0][1].hints;
t.is(hints.hint1, 'error');
t.is(hints.hint2, 'warning');
});
|
coliff/hint | packages/hint-compat-api/src/utils/browsers.ts | <gh_stars>0
import { UnsupportedBrowsers } from '@hint/utils/dist/src/compat';
import { getFriendlyName } from '@hint/utils/dist/src/compat/browsers';
/**
* Apply temporary filters to the list of target browsers to reduce
* false-positives due to incorrect/outdated data. Each of these
* should be removed once the affected data sources have been updated.
*/
export const filterBrowsers = (browsers: string[]): string[] => {
return browsers.filter((browser) => {
// Ignore Android WebView due to outdated data in both browserslist and MDN.
if (browser.startsWith('android')) {
return false;
}
// Ignore Samsung 4 due to outdated data in MDN.
if (browser === 'samsung 4') {
return false;
}
// Ignore Safari 5.1 due to `caniuse` reporting incorrect usage data.
if (browser === 'safari 5.1') {
return false;
}
return true;
});
};
/**
* Serialize summarized support ranges for provided browsers.
*
* ```js
* joinBrowsers({ browsers: ['edge 15'], browserDetails: new Map([['edge 15', { versionAdded: '18' }]]));
* // returns 'Edge < 18';
* ```
*/
export const joinBrowsers = (unsupported: UnsupportedBrowsers): string => {
const summaries = unsupported.browsers.map((browser) => {
const name = getFriendlyName(browser);
const details = unsupported.details.get(browser);
if (!details) {
throw new Error(`No details provided for browser: ${name}`);
}
if (details.versionAdded && details.versionRemoved) {
return `${name} ${details.versionRemoved}-${details.versionAdded}`;
} else if (details.versionAdded) {
return `${name} < ${details.versionAdded}`;
} else if (details.versionRemoved) {
return `${name} ${details.versionRemoved}+`;
}
return name;
});
return [...new Set(summaries)].sort().join(', ');
};
|
coliff/hint | packages/extension-browser/src/content-script/connector.ts | import { URL } from 'url';
import { Engine } from 'hint';
import { getElementByUrl, HTMLDocument, HTMLElement, traverse } from '@hint/utils/dist/src/dom';
import { createHelpers, restoreReferences } from '@hint/utils/dist/src/dom/snapshot';
import { DocumentData } from '@hint/utils/dist/src/types/snapshot';
import {
ConnectorOptionsConfig,
IConnector,
FetchEnd,
NetworkData
} from 'hint/dist/src/lib/types';
import { browser, document, eval, location, MutationObserver, window } from '../shared/globals';
import { Events } from '../shared/types';
import { Fetcher } from './fetcher';
import { setFetchType } from './set-fetch-type';
export default class WebExtensionConnector implements IConnector {
private _document: HTMLDocument | undefined;
private _originalDocument: HTMLDocument | undefined;
private _engine: Engine;
private _fetcher = new Fetcher();
private _fetchEndQueue: FetchEnd[] = [];
private _onComplete: (err: Error | null, resource?: string) => void = () => { };
private _options: ConnectorOptionsConfig;
public static schema = {
additionalProperties: false,
properties: {
waitFor: {
minimum: 0,
type: 'number'
}
}
};
public constructor(engine: Engine, options?: ConnectorOptionsConfig) {
this._engine = engine;
this._options = options || {};
/* istanbul ignore else */
if (!this._options.waitFor) {
this._options.waitFor = 1000;
}
(engine as Engine<import('@hint/parser-html').HTMLEvents>).on('parse::end::html', (event) => {
/* istanbul ignore else */
if (event.resource === location.href) {
this._originalDocument = event.document;
}
});
browser.runtime.onMessage.addListener(async (events: Events) => {
try {
/** Extension resources cause overhead and noise to the user so they are ignored. */
if (this.isExtensionResource(events)) {
return;
}
if (this._fetcher.handle(events)) {
return;
}
if (events.fetchEnd) {
await this.notifyFetch(events.fetchEnd);
}
if (events.fetchStart) {
await this._engine.emitAsync('fetch::start', events.fetchStart);
}
// TODO: Trigger 'fetch::start::target'.
} catch (err) /* istanbul ignore next */ {
this._onComplete(err);
}
});
const onLoad = () => {
const resource = location.href;
setTimeout(async () => {
try {
await this.evaluateInPage(`(${createHelpers})()`);
const snapshot: DocumentData = await this.evaluateInPage('__webhint.snapshotDocument(document)');
restoreReferences(snapshot);
this._document = new HTMLDocument(snapshot, location.href, this._originalDocument);
await this.sendFetchEndEvents();
await traverse(this._document, this._engine, resource);
/*
* Evaluate after the traversing, just in case something goes wrong
* in any of the evaluation and some scripts are left in the DOM.
*/
await this._engine.emitAsync('can-evaluate::script', { resource });
this._onComplete(null, resource);
} catch (err) /* istanbul ignore next */ {
this._onComplete(err);
}
}, this._options.waitFor);
};
if (document.readyState === 'complete') {
setTimeout(onLoad, 0);
} else {
window.addEventListener('load', onLoad);
}
}
private isExtensionResource(events: Events) {
/** Only chromium resources seem to get tracked but just in case we add the Firefox protocol as well. */
const event = events.fetchStart || events.fetchEnd;
if (!event) {
return false;
}
const resource = event.resource;
return resource.startsWith('chrome-extension:') || resource.startsWith('moz-extension:');
}
private sendMessage(message: Events) {
browser.runtime.sendMessage(message);
}
private async sendFetchEndEvents() {
for (const event of this._fetchEndQueue) {
await this.notifyFetch(event);
}
}
private setFetchElement(event: FetchEnd) {
const url = event.request.url;
if (this._document) {
event.element = getElementByUrl(this._document, url);
}
}
private async notifyFetch(event: FetchEnd) {
/*
* Delay dispatching FetchEnd until we have the DOM snapshot to populate `element`.
* But immediately process target's FetchEnd to populate `originalDocument`.
*/
if (!this._document && event.response.url !== location.href) {
this._fetchEndQueue.push(event);
return;
}
this.setFetchElement(event);
const type = setFetchType(event);
await this._engine.emitAsync(`fetch::end::${type}` as 'fetch::end::*', event);
}
/* istanbul ignore next */
public fetchContent(target: string, headers?: any): Promise<NetworkData> {
return this._fetcher.fetch(target, headers);
}
public async collect(target: URL) {
const resource = target.href;
await this._engine.emitAsync('scan::start', { resource });
this.sendMessage({ ready: true });
return new Promise((resolve, reject) => {
this._onComplete = async (err: Error | null, resource = '') => {
/* istanbul ignore if */
if (err) {
reject(err);
return;
}
try {
await this._engine.emitAsync('scan::end', { resource });
resolve();
this.sendMessage({ done: true });
} catch (e) /* istanbul ignore next */ {
reject(e);
}
};
});
}
private needsToRunInPage(source: string) {
return source.includes('/*RunInPageContext*/');
}
/**
* Runs a script in the website context.
*
* By default, `eval` runs the scripts in a different context
* but, some scripts, needs to run in the same context
* of the website.
*/
private evaluateInPage(source: string): Promise<any> {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
const config = {
attributes: true,
childList: false,
subtree: false
};
const injectTimeout = setTimeout(() => {
reject(new Error('Cannot run analysis scripts. Page may have CSP restrictions.'));
}, 100);
const callback = (mutationsList: MutationRecord[], observer: MutationObserver) => {
try {
mutationsList.forEach((mutation: MutationRecord) => {
/* istanbul ignore if */
if (mutation.type !== 'attributes' || !(/^data-(error|result|start)$/).test(mutation.attributeName || '')) {
return;
}
if (mutation.attributeName === 'data-start') {
clearTimeout(injectTimeout);
return;
}
const error = script.getAttribute('data-error');
const result = script.getAttribute('data-result');
document.body.removeChild(script);
observer.disconnect();
if (error) {
reject(JSON.parse(error));
/* istanbul ignore else*/
} else if (result) {
resolve(JSON.parse(result));
} else {
reject(new Error('No error or result returned from evaluate.'));
}
});
} catch (err) /* istanbul ignore next */ {
reject(err);
}
};
const observer = new MutationObserver(callback);
observer.observe(script, config);
script.textContent = `(async () => {
const scriptElement = document.currentScript;
try {
scriptElement.setAttribute('data-start', 'true');
const result = await ${source}
scriptElement.setAttribute('data-result', JSON.stringify(result) || null);
} catch (err) {
scriptElement.setAttribute('data-error', JSON.stringify({ message: err.message, stack: err.stack }));
}
})();`;
document.body.appendChild(script);
});
}
public evaluate(source: string): Promise<any> {
/*
* TODO: another option here is changing the interface of IConnector
* to allow another parameter in evaluate to indicate if we should run
* the script in the page context or if eval is enough.
*/
if (this.needsToRunInPage(source)) {
return this.evaluateInPage(source);
}
// `eval` will run the code inside the browser.
return Promise.resolve(eval(source)); // eslint-disable-line no-eval
}
public querySelectorAll(selector: string): HTMLElement[] {
return this._document ? this._document.querySelectorAll(selector) : [];
}
/* istanbul ignore next */
public close() {
return Promise.resolve();
}
public get dom(): HTMLDocument | undefined {
return this._document;
}
/* istanbul ignore next */
public get html(): string {
return this._document ? this._document.pageHTML() : '';
}
}
|
coliff/hint | packages/hint/src/bin/hint.ts | #!/usr/bin/env node
/**
* @fileoverview Main CLI that is run via the hint command. Based on ESLint.
*/
/* eslint-disable no-process-exit, no-process-env */
/*
* ------------------------------------------------------------------------------
* Helpers
* ------------------------------------------------------------------------------
*/
const tracking = (/--tracking[=\s]+([^\s]*)/i).exec(process.argv.join(' '));
import { configStore, appInsights } from '@hint/utils';
const trackingEnv = process.env.HINT_TRACKING;
let enableTracking;
if (tracking) {
enableTracking = tracking[1] === 'on';
} else if (trackingEnv) {
enableTracking = trackingEnv === 'on';
}
if (typeof enableTracking !== 'undefined') {
if (enableTracking) {
const alreadyRun: boolean = configStore.get('run');
const configured = appInsights.isConfigured();
appInsights.enable();
if (!configured) {
if (!alreadyRun) {
appInsights.trackEvent('FirstRun');
} else {
appInsights.trackEvent('SecondRun');
}
}
} else {
appInsights.disable();
}
}
/*
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
* Now we can safely include the other modules that use debug.
*/
import * as cli from '../lib/cli';
const { trackException, sendPendingData } = appInsights;
/*
* ------------------------------------------------------------------------------
* Execution
* ------------------------------------------------------------------------------
*/
process.once('uncaughtException', async (err) => {
console.error(err.message);
console.error(err.stack);
trackException(err);
await sendPendingData(true);
process.exit(1);
});
process.once('unhandledRejection', async (r) => {
// TODO: remove once https://github.com/DefinitelyTyped/DefinitelyTyped/issues/33636 is fixed
const reason = r as any;
const source = reason && reason instanceof Error ? reason : reason.error;
trackException(source);
await sendPendingData(true);
console.error(`Unhandled rejection promise:
uri: ${source.uri}
message: ${source.message}
stack:
${source.stack}`);
process.exit(1);
});
const run = async () => {
process.exitCode = await cli.execute(process.argv);
process.exit(process.exitCode);
};
run();
|
coliff/hint | packages/extension-vscode/tests/utils/analytics.ts | <filename>packages/extension-vscode/tests/utils/analytics.ts
import * as proxyquire from 'proxyquire';
import * as sinon from 'sinon';
import test from 'ava';
import { IHintConstructor, Problem } from 'hint';
const stubContext = () => {
const stubs = { './app-insights': {} as typeof import ('../../src/utils/app-insights') };
const module = proxyquire('../../src/utils/analytics', stubs) as typeof import('../../src/utils/analytics');
return { module, stubs };
};
test('It tracks when telemetry is first enabled', (t) => {
const sandbox = sinon.createSandbox();
const { module, stubs } = stubContext();
const trackEventSpy = sandbox.spy(stubs['./app-insights'], 'trackEvent');
module.trackOptIn('ask', true);
t.true(trackEventSpy.notCalled);
module.trackOptIn('ask', false);
t.true(trackEventSpy.notCalled);
module.trackOptIn('disabled', true);
t.true(trackEventSpy.notCalled);
module.trackOptIn('disabled', false);
t.true(trackEventSpy.notCalled);
module.trackOptIn('enabled', true);
t.true(trackEventSpy.notCalled);
module.trackOptIn('enabled', false);
t.true(trackEventSpy.calledOnce);
t.is(trackEventSpy.firstCall.args[0], 'vscode-telemetry');
sandbox.restore();
});
test('It tracks the first result for each document when opened', (t) => {
const sandbox = sinon.createSandbox();
const { module, stubs } = stubContext();
const trackEventSpy = sandbox.spy(stubs['./app-insights'], 'trackEvent');
// First result should be tracked.
module.trackResult('test.html', {
hints: [
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: [
{
hintId: 'foo',
message: 'This should not be logged'
} as Problem
]
});
// Second result should not be tracked (will be cached for 'onSave').
module.trackResult('test.html', {
hints: [
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: []
});
// First result for another document should be tracked.
module.trackResult('test.css', {
hints: [
{ meta: { id: 'bar' } } as IHintConstructor
],
problems: []
});
t.true(trackEventSpy.calledTwice);
t.is(trackEventSpy.firstCall.args[0], 'vscode-open');
t.deepEqual(trackEventSpy.firstCall.args[1], { 'hint-foo': 'failed' });
t.is(trackEventSpy.secondCall.args[0], 'vscode-open');
t.deepEqual(trackEventSpy.secondCall.args[1], { 'hint-bar': 'passed' });
sandbox.restore();
});
test('It tracks the delta between the first and last results on save', (t) => {
const sandbox = sinon.createSandbox();
const { module, stubs } = stubContext();
const trackEventSpy = sandbox.spy(stubs['./app-insights'], 'trackEvent');
// First result should be tracked.
module.trackResult('test.html', {
hints: [
{ meta: { id: 'bar' } } as IHintConstructor,
{ meta: { id: 'baz' } } as IHintConstructor,
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: [
{ hintId: 'bar' } as Problem,
{ hintId: 'bar' } as Problem,
{ hintId: 'foo' } as Problem,
{ hintId: 'foo' } as Problem,
{ hintId: 'foo' } as Problem
]
});
// Second result should not be tracked (will be cached for 'onSave').
module.trackResult('test.html', {
hints: [
{ meta: { id: 'bar' } } as IHintConstructor,
{ meta: { id: 'baz' } } as IHintConstructor,
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: [
{ hintId: 'bar' } as Problem,
{ hintId: 'bar' } as Problem
]
});
// First result for another document should be tracked.
module.trackResult('test.html', {
hints: [
{ meta: { id: 'bar' } } as IHintConstructor,
{ meta: { id: 'baz' } } as IHintConstructor,
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: [
{ hintId: 'foo' } as Problem
]
});
module.trackSave('test.html');
// Verify multiple saves only submit once with no new results.
module.trackSave('test.html');
t.true(trackEventSpy.calledTwice);
t.is(trackEventSpy.firstCall.args[0], 'vscode-open');
t.deepEqual(trackEventSpy.firstCall.args[1], {
'hint-bar': 'failed',
'hint-baz': 'passed',
'hint-foo': 'failed'
});
t.is(trackEventSpy.secondCall.args[0], 'vscode-save');
t.deepEqual(trackEventSpy.secondCall.args[1], {
'hint-bar': 'fixed',
'hint-baz': 'passed',
'hint-foo': 'fixing'
});
sandbox.restore();
});
test('It tracks results again for a document when re-opened', (t) => {
const sandbox = sinon.createSandbox();
const { module, stubs } = stubContext();
const trackEventSpy = sandbox.spy(stubs['./app-insights'], 'trackEvent');
// First result should be tracked.
module.trackResult('test.html', {
hints: [
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: [
{
hintId: 'foo',
message: 'This should not be logged'
} as Problem
]
});
// Closing the document should clear the internal result cache.
module.trackClose('test.html');
// Second result should be tracked because document was re-opened.
module.trackResult('test.html', {
hints: [
{ meta: { id: 'foo' } } as IHintConstructor
],
problems: []
});
t.true(trackEventSpy.calledTwice);
t.is(trackEventSpy.firstCall.args[0], 'vscode-open');
t.deepEqual(trackEventSpy.firstCall.args[1], { 'hint-foo': 'failed' });
t.is(trackEventSpy.secondCall.args[0], 'vscode-open');
t.deepEqual(trackEventSpy.secondCall.args[1], { 'hint-foo': 'passed' });
});
|
coliff/hint | packages/hint-compat-api/tests/css.ts | import { fs, test } from '@hint/utils';
import { testHint } from '@hint/utils-tests-helpers';
const { generateHTMLPage, getHintPath } = test;
const { readFile } = fs;
const hintPath = getHintPath(__filename, true);
const generateCSSConfig = (fileName: string) => {
const path = 'fixtures/css';
const styles = readFile(`${__dirname}/${path}/${fileName}.css`);
return {
'/': generateHTMLPage(`<link rel="stylesheet" href="styles/${fileName}">`),
[`/styles/${fileName}`]: {
content: styles,
headers: { 'Content-Type': 'text/css' }
}
};
};
const targetBrowsers = ['chrome 73-74', 'edge 15-16', 'firefox 65-66', 'ie 9-11'];
testHint(hintPath,
[
{
name: 'Reports unsupported CSS at-rules',
reports: [
{
message: '@keyframes is not supported by Internet Explorer < 10.',
position: { match: '@keyframes' }
}
],
serverConfig: generateCSSConfig('atrules')
},
{
name: 'Does not report ignored CSS features by default',
serverConfig: generateCSSConfig('ignore')
},
{
name: 'Reports unsupported properties, respecting prefixes and fallback',
reports: [
{
message: 'appearance is not supported by Internet Explorer.',
position: { match: 'appearance: button; /* Report 1 */' }
},
{
message: 'appearance is not supported by Internet Explorer.',
position: { match: 'appearance: button; /* Report 2 */' }
},
{
message: '-webkit-appearance is not supported by Internet Explorer.',
position: { match: '-webkit-appearance: button; /* Report 3 */' }
},
{
message: '-moz-appearance is not supported by Internet Explorer.',
position: { match: '-moz-appearance: button; /* Report 4 */' }
},
{
message: '-webkit-appearance is not supported by Firefox, Internet Explorer.',
position: { match: '-webkit-appearance: button; /* Report 5 */' }
},
{
message: 'appearance is not supported by Chrome, Edge, Firefox, Internet Explorer.',
position: { match: 'appearance: button; /* Report 6 */' }
}
],
serverConfig: generateCSSConfig('properties')
},
/*
* TODO: Uncomment after re-enabling CSS selector support.
*
* {
* name: 'Reports unsupported CSS selectors',
* reports: [
* {
* message: ':valid is not supported by Internet Explorer < 10.',
* position: { match: ':valid' }
* }
* ],
* serverConfig: generateCSSConfig('selectors')
* },
*/
{
name: 'Respects CSS @supports rules when generating reports',
reports: [
{
message: 'display: grid is not supported by Edge < 16.',
position: { match: 'display: grid; /* Report */' }
}
],
serverConfig: generateCSSConfig('supports')
},
{
name: 'Reports unsupported CSS property values, respecting prefixes and fallback',
reports: [
{
message: 'display: grid is not supported by Internet Explorer.',
position: { match: 'display: grid; /* Report 1 */' }
},
{
message: 'display: grid is not supported by Internet Explorer.',
position: { match: 'display: grid; /* Report 2 */' }
},
{
message: 'display: -ms-grid is not supported by Chrome, Firefox, Internet Explorer < 10.',
position: { match: 'display: -ms-grid; /* Report 3 */' }
},
{
message: 'display: grid is not supported by Edge < 16, Internet Explorer.',
position: { match: 'display: grid; /* Report 4 */' }
}
],
serverConfig: generateCSSConfig('values')
}
],
{
browserslist: targetBrowsers,
parsers: ['css']
}
);
testHint(hintPath,
[
{
name: 'Does not report prefixed CSS at-rules if unprefixed support exists',
serverConfig: generateCSSConfig('atrules')
}
],
{
browserslist: ['ie 11'],
parsers: ['css']
}
);
testHint(hintPath,
[
{
name: 'Reports overridden ignored CSS features',
reports: [
{
message: 'appearance is not supported by Internet Explorer.',
position: { match: 'appearance: none; /* unprefixed */' }
}
],
serverConfig: generateCSSConfig('ignore')
},
{
name: 'Does not report manually ignored CSS features',
serverConfig: generateCSSConfig('values')
}
],
{
browserslist: targetBrowsers,
hintOptions: {
enable: ['-moz-appearance: none', '-webkit-appearance: none', 'appearance: none'],
ignore: ['display: grid', 'display: -ms-grid']
},
parsers: ['css']
}
);
|
coliff/hint | packages/extension-vscode/src/utils/webhint-packages.ts | <gh_stars>0
import { hasFile, mkdir } from './fs';
import { installPackages, loadPackage, InstallOptions } from './packages';
const installWebhint = (options: InstallOptions) => {
return installPackages(['hint', '@hint/configuration-development'], options);
};
/**
* Install or update a shared copy of webhint to the provided global storage
* path reserved for the extension.
*/
/* istanbul ignore next */
export const updateSharedWebhint = async (globalStoragePath: string) => {
/*
* Per VS Code docs globalStoragePath may not exist but parent folder will.
* https://code.visualstudio.com/api/references/vscode-api#ExtensionContext.globalStoragePath
*/
if (!await hasFile(globalStoragePath)) {
await mkdir(globalStoragePath);
await updateSharedWebhint(globalStoragePath);
}
try {
await installWebhint({ cwd: globalStoragePath });
} catch (err) {
console.warn('Unable to install shared webhint instance', err);
}
};
/**
* Load a shared copy of webhint from the provided global storage path
* reserved for the extension. Installs a shared copy if none exists.
*/
/* istanbul ignore next */
const loadSharedWebhint = async (globalStoragePath: string): Promise<typeof import('hint') | null> => {
try {
return loadPackage('hint', { paths: [globalStoragePath] });
} catch (err) {
await updateSharedWebhint(globalStoragePath);
console.error('Unable to load shared webhint instance', err);
return null;
}
};
/**
* Load webhint, installing it if needed.
* Will prompt to install a local copy if `.hintrc` is present.
*/
export const loadWebhint = async (directory: string, globalStoragePath: string, promptToInstall?: (install: () => Promise<void>) => Promise<void>): Promise<typeof import('hint') | null> => {
try {
return loadPackage('hint', { paths: [directory] });
} catch (e) {
if (promptToInstall && await hasFile('.hintrc', directory)) {
await promptToInstall(async () => {
await installWebhint({ cwd: directory });
});
return loadWebhint(directory, globalStoragePath);
}
return loadSharedWebhint(globalStoragePath);
}
};
|
acteq/mook | es/create-hooks.d.ts | import { HookFunc, WrappedHooks } from "./types";
declare type Subscriber<T> = (data: T) => void;
export declare class Store<T = unknown> {
constructor();
subscribers: Set<Subscriber<T>>;
model: T;
notify(): void;
setModel(newModel: T): void;
}
export declare function createHooks<T, P>(hook: HookFunc<T, P>): WrappedHooks<T>;
export {};
|
acteq/mook | es/types.d.ts | <gh_stars>1-10
export declare type HookFunc<T = any, P = any> = (args: P) => T;
declare type Deps<T> = (model: T) => unknown[];
export interface UseHook<T> {
(depsFn?: Deps<T>): T;
}
export interface WrappedHooks<T> {
wrapped: HookFunc<T>;
standin: HookFunc<T>;
}
export interface UseHook<T> {
(depsFn?: Deps<T>): T;
}
export declare type UseHookFunc<T> = (depsFn?: Deps<T>) => T;
export {};
|
acteq/mook | src/types.ts | <reponame>acteq/mook
export type HookFunc<T = any, P = any> = (args: P) => T;
export type StandInHook<T> = (depsFn?: Deps<T>) => T;
type Deps<T> = (model: T) => unknown[];
export interface WrappedHooks<T> {
wrapped : HookFunc<T>;
standin : StandInHook<T>;
}
|
acteq/mook | src/index.tsx | <reponame>acteq/mook<filename>src/index.tsx
export { createHooks } from "./create-hooks";
|
acteq/mook | src/__tests__/create-hooks.test.tsx | <filename>src/__tests__/create-hooks.test.tsx
import { createHooks } from "..";
import { useState } from "react";
// import "@testing-library/jest-dom/extend-expect";
import { renderHook,act } from '@testing-library/react-hooks';
function useCounter(initalValue: number) {
const [count, setCount] = useState(initalValue??0);
const decrement = () => setCount(count - 1);
const increment = () => setCount(count + 1);
return { count, decrement, increment };
}
test('should use counterModel', () => {
const {wrapped:useCounterModel, standin: useRefCounterModel} = createHooks(useCounter);
const { result } = renderHook(useCounterModel,{initialProps: 5})
expect(result.current.count).toBe(5)
expect(typeof result.current.increment).toBe('function')
})
test('should increment counter', () => {
const {wrapped:useCounterModel, standin: useRefCounterModel} = createHooks(useCounter);
const { result } = renderHook(useCounterModel)
act(() => {
result.current.increment()
})
expect(result.current.count).toBe(1)
})
/*
test('should use refCounterModel', () => {
const {wrapped:useCounterModel, standin: useRefCounterModel} = createHooks(useCounter);
const { result } = renderHook((initialProps) => useCounterModel(initialProps), {initialProps: 5})
const { result:result2 } = renderHook(useRefCounterModel)
expect(result2.current.count).toBe(result.current.count)
expect(typeof result2.current.increment).toBe('function')
})
test('should increment counter', () => {
const {wrapped:useCounterModel, standin: useRefCounterModel} = createHooks(useCounter);
const { result } = renderHook((initialProps) => useCounterModel(initialProps), {initialProps: 5})
const { result:result2 } = renderHook(useRefCounterModel)
act(() => {
result2.current.increment()
})
expect(result2.current.count).toBe(6)
expect(result2.current.count).toBe(result.current.count)
})
*/
|
acteq/mook | src/create-hooks.tsx | import { HookFunc, StandInHook, WrappedHooks } from "./types";
import { useEffect, useRef, useState } from "react";
type Subscriber<T> = (data: T) => void;
export class Store<T = unknown> {
constructor() {}
subscribers = new Set<Subscriber<T>>();
model!: T;
notify() {
for (const subscriber of this.subscribers) {
subscriber(this.model);
}
}
setModel(newModel:T) {
this.model = newModel;
setTimeout(()=>{
this.notify();
},0 );
}
}
export function createHooks<T, P>(hook: HookFunc<T, P>): WrappedHooks<T> {
const store = new Store();
const wrapped: HookFunc<T> = (args:any) => {
const model = hook(args);
store.setModel(model);
return store.model! as T;
};
const standin: StandInHook<T> = depsFn => {
const [state, setState] = useState<Object>();
const depsFnRef = useRef(depsFn);
depsFnRef.current = depsFn;
const depsRef = useRef<unknown[]>([]);
useEffect(() => {
if (!store) return;
function subscriber(val: T) {
if (!depsFnRef.current) {
setState({});
} else {
const oldDeps = depsRef.current;
const newDeps = depsFnRef.current(val);
if (hasChanged(oldDeps, newDeps)) {
setState({});
}
depsRef.current = newDeps;
}
}
store.subscribers.add(subscriber);
return () => {
store.subscribers.delete(subscriber);
};
}, [store]);
//if (process.env.NODE_ENV !== 'production' )
// throw new Error(message)
return store ? (store.model as T) : undefined;
};
return {wrapped, standin};
}
function hasChanged(oldDeps: unknown[], newDeps: unknown[]) {
if (oldDeps.length !== newDeps.length) {
return true;
}
for (const index in newDeps) {
if (oldDeps[index] !== newDeps[index]) {
return true;
}
}
return false;
}
|
ctx-core/email | src/email_valid_.ts | <reponame>ctx-core/email<filename>src/email_valid_.ts<gh_stars>0
export function email_valid_(email:string):boolean {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
}
export {
email_valid_ as _email_valid,
email_valid_ as _valid__email,
email_valid_ as validate_email,
email_valid_ as validate__email,
}
|
ctx-core/email | src/index.ts | <gh_stars>0
export * from './email_valid_.js'
|
kevans2226/HRV | ClientApp/src/app/home/home.component.ts | <reponame>kevans2226/HRV
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AppComponent } from '../app.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
})
export class HomeComponent {
constructor(public app: AppComponent, private router: Router) {
console.log(`Home Componet UserSignedIn ${this.app.userSignedIn}`);
if(app.userSignedIn) {
this.router.navigate(['/hrv']);
}
}
}
|
kevans2226/HRV | ClientApp/src/app/hrv/hrv.component.ts | <gh_stars>0
import { DatePipe, formatDate } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { HRVRecordService } from '../Services/hrvrecord.service';
import { hrvOutput, hrvRecord } from '../Structures/structures';
@Component({
selector: 'app-hrv',
templateUrl: './hrv.component.html',
styleUrls: ['./hrv.component.scss']
})
export class HRVComponent implements OnInit {
public formHRV: FormGroup ;
public hrvs: hrvOutput[] = [];
public PanelEnum = Panel;
public panelValue: Panel;
public hrvDelete: hrvOutput;
constructor(private fb: FormBuilder,
private hrvService: HRVRecordService,
private activedRoute: ActivatedRoute,
private router: Router) {
this.panelValue = Panel.Loading;
this.formHRV = this.fb.group({});
var idString = this.activedRoute.snapshot.paramMap.get("id");
if(idString == null) {
this.hrvService.GetHrv().subscribe(result => {
this.hrvs = result;
console.log(this.hrvs);
this.panelValue = Panel.List;
console.log(this.panelValue);
}, error => {
console.log(error);
if(error.status == 401) {
this.router.navigate(['/home']);
}
});
}
else {
if(idString === "0") {
this.formHRV = fb.group({
date: [new Date().toLocaleString(), [Validators.required]],
hrv: ['', [Validators.required]],
id: [0, [Validators.required]]
});
this.panelValue = Panel.Form;
}
else {
this.hrvService.GetAHrv(parseInt(idString)).subscribe(result => {
var lang = navigator.language;
var pipe = new DatePipe(lang);
var dateFormat = pipe.transform(result.date, 'medium');
this.formHRV = fb.group({
date: [dateFormat, [Validators.required]],
hrv: [result.hrv, [Validators.required]],
id: [result.id, [Validators.required]]
});
this.panelValue = Panel.Form;
});
}
}
}
ngOnInit(): void {
}
addHrv() : void {
this.router.navigate(['/hrv/0']);
}
editHrv(id: number) : void {
this.router.navigate([`/hrv/${id}`]);
}
submit() : void {
var dateString = this.formHRV.get("date")?.value;
console.log(dateString);
var d = new Date(Date.parse(dateString));
console.log(d);
var offset = d.getTimezoneOffset();
console.log(`offset ${offset}`);
// Build Date String
var year = d.getFullYear();
var month = (d.getMonth() + 1) < 10 ? `0${(d.getMonth() + 1)}` : (d.getMonth() + 1);
var day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
var hour = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
var minute = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
var second = d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds();
var offSetHours = Math.abs(Math.floor(offset / 60));
var offSetMinutes = offset % 60;
var offHours = offSetHours < 10 ? `0${offSetHours}` : offSetHours;
var offMinutes = offSetMinutes < 10 ? `0${offSetMinutes}` : offSetMinutes;
var sign = offset < 0 ? '+' : '-';
var dString = `${year}-${month}-${day}T${hour}:${minute}:${second}${sign}${offHours}:${offMinutes}`;
var hrvReading = parseInt(this.formHRV.get("hrv")?.value);
var record = { date: dString, hrv: hrvReading } as hrvRecord
var id = parseInt(this.formHRV.get("id")?.value);
if(id === 0) {
console.log("Adding");
console.log(record);
this.hrvService.AddHrv(record).subscribe(r => {
this.hrvs.push(r);
this.router.navigate(['/hrv']);
});
}
else {
console.log("Updating");
console.log(record);
this.hrvService.UpdateHrv(record, id).subscribe(r => {
this.router.navigate(['/hrv']);
})
}
}
showForm(panel: Panel) : boolean {
if((panel & this.panelValue) === panel) return true;
else return false;
}
cancel() : void {
this.router.navigate(['/hrv']);
this.panelValue = Panel.List;
}
public showDeleteForm(id: number) {
this.hrvDelete = this.hrvs.find(h => h.id);
this.panelValue = this.PanelEnum.DeleteForm;
}
public deleteRecord(id: number) {
this.panelValue = this.PanelEnum.Loading;
this.hrvService.DeleteHRV(id).subscribe(result => {
console.log(result)
var index = this.hrvs.findIndex(f => f.id == id);
this.hrvs.splice(index, 1);
this.panelValue = Panel.List;
}, error => {
console.error(error);
})
}
}
export enum Panel {
Loading = 1,
List = 2,
Form = 4,
DeleteForm = 8
}
|
kevans2226/HRV | ClientApp/src/app/Structures/structures.ts | <reponame>kevans2226/HRV<gh_stars>0
import { FormGroup } from "@angular/forms";
export class LoginModel {
userName!: string;
password!: string;
}
export class Token {
token!: string;
expiration! : Date;
userName!: string;
}
export class newUser {
emailAddress!: string;
password!: string;
firstName!: string;
lastName!: string;
userName!: string;
}
export class hrvRecord {
date!: string;
hrv!: number;
}
export class hrvOutput extends hrvRecord {
id!: number;
}
export class hrvList extends hrvOutput {
range: string;
}
export class passwordChange {
oldPassword: string;
newPassword: string;
}
export function ComparePassword(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
};
} |
kevans2226/HRV | ClientApp/src/app/Services/login.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { LoginModel, newUser, passwordChange, Token } from '../Structures/structures';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor(private http: HttpClient) { }
public login(login: LoginModel) : Observable<Token> {
return this.http.post<Token>("/api/Authenticate/login", login);
}
public createUser(user: newUser) : Observable<any> {
return this.http.post<any>('/api/Authenticate/createUser', user);
}
public checkUser() : Observable<any> {
return this.http.get<any>('/api/Authenticate/check');
}
public refreshToken(): Observable<Token> {
return this.http.get<Token>("/api/Authenticate/refresh");
}
public passwordChange(pwdChange: passwordChange): Observable<any> {
return this.http.put<any>("/api/Authenticate/passwordChange", pwdChange);
}
}
|
kevans2226/HRV | ClientApp/src/app/password-change/password-change.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoginService } from '../Services/login.service';
import { ComparePassword, passwordChange } from '../Structures/structures';
@Component({
selector: 'app-password-change',
templateUrl: './password-change.component.html',
styleUrls: ['./password-change.component.css']
})
export class PasswordChangeComponent implements OnInit {
public passwordChange: FormGroup;
public showForm: boolean = true;
public showSuccessMessage: boolean = false;
public showErrorMessage: boolean = false;
public errorMessage: string;
constructor(private formBuilder: FormBuilder, private loginService: LoginService) {
this.passwordChange = this.formBuilder.group({
oldPassword: ['', [Validators.required]],
newPassword: ['', [Validators.required]],
confirmPassword: ['', [Validators.required]]
},
{
validator: ComparePassword("newPassword", "confirmPassword")
});
}
ngOnInit(): void {
}
public changePassword() : void {
var pwdChange = {
newPassword: this.passwordChange.get("newPassword").value,
oldPassword: this.passwordChange.get("oldPassword").value
} as passwordChange;
this.loginService.passwordChange(pwdChange).subscribe(result => {
console.log("Accepted");
this.showForm = false;
this.showSuccessMessage = true;
}, error => {
console.log(error);
this.showForm = true;
this.showErrorMessage = true;
this.showSuccessMessage = false;
this.errorMessage = error.error;
})
}
}
|
kevans2226/HRV | ClientApp/src/app/signin/signin.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AppComponent } from '../app.component';
import { LoginService } from '../Services/login.service';
import { LoginModel } from '../Structures/structures';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.scss']
})
export class SigninComponent implements OnInit {
signInForm: FormGroup;
loginFailed: boolean = false;
constructor(private fb: FormBuilder, private loginService: LoginService, private router: Router,
private parent: AppComponent)
{
this.signInForm = this.fb.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
}
ngOnInit(): void {
}
login(): void {
var email = this.signInForm.get("email")?.value;
var password = this.signInForm.get("password")?.value;
var l = { userName: email, password: password } as LoginModel;
this.loginService.login(l).subscribe(result => {
localStorage.setItem("HRV_TOKEN", result.token);
localStorage.setItem("HRV_TOKEN_EXP", result.expiration.toString());
localStorage.setItem("USER_ID", result.userName);
localStorage.setItem("LAST_REFRESH", (new Date()).toString());
this.parent.checkToken();
this.parent.userSignedIn = true;
this.router.navigate(['hrv']);
this.loginFailed = false;
}, error => {
console.log(error);
localStorage.removeItem("HRV_TOKEN");
localStorage.removeItem("HRV_TOKEN_EXP");
localStorage.removeItem("USER_ID");
localStorage.removeItem("LAST_REFRESH");
this.loginFailed = true;
});
}
}
|
kevans2226/HRV | ClientApp/src/app/Services/hrvrecord.service.ts | <filename>ClientApp/src/app/Services/hrvrecord.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { hrvList, hrvOutput, hrvRecord } from '../Structures/structures';
@Injectable({
providedIn: 'root'
})
export class HRVRecordService {
constructor(private http: HttpClient) {
}
public AddHrv(record: hrvRecord) : Observable<hrvOutput> {
return this.http.post<hrvOutput>("/api/HRV", record);
}
public GetHrv() : Observable<hrvList[]> {
return this.http.get<hrvList[]>("/api/HRV");
}
public UpdateHrv(record: hrvRecord, id: number) : Observable<hrvOutput> {
return this.http.put<hrvOutput>(`/api/HRV/${id}`, record);
}
public GetAHrv(id: number) : Observable<hrvOutput> {
return this.http.get<hrvOutput>(`/api/HRV/${id}`);
}
public DeleteHRV(id: number) : Observable<any> {
return this.http.delete<any>(`/api/HRV/${id}`);
}
}
|
kevans2226/HRV | ClientApp/src/app/app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HRVRecordService } from './Services/hrvrecord.service';
import { LoginService } from './Services/login.service';
import { NewUserComponent } from './new-user/new-user.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import { AppRoutingModule } from './app-routing.module';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatDatepickerModule } from '@angular/material/datepicker';
import {
NgxMatDatetimePickerModule,
NgxMatNativeDateModule,
NgxMatTimepickerModule
} from '@angular-material-components/datetime-picker';
import { MatNativeDateModule } from '@angular/material/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SigninComponent } from './signin/signin.component';
import { AuthInterceptor } from './auth-interceptor';
import { HRVComponent } from './hrv/hrv.component';
import { PasswordChangeComponent } from './password-change/password-change.component';
import {MatMenuModule} from '@angular/material/menu';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NewUserComponent,
SigninComponent,
HRVComponent,
PasswordChangeComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
MatFormFieldModule,
AppRoutingModule,
MatIconModule,
MatButtonModule,
ReactiveFormsModule,
HttpClientModule,
MatInputModule,
MatDatepickerModule,
NgxMatDatetimePickerModule,
NgxMatTimepickerModule,
MatNativeDateModule,
NgxMatNativeDateModule,
BrowserAnimationsModule,
MatMenuModule
],
providers: [
HRVRecordService,
LoginService,
AuthInterceptor,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
|
kevans2226/HRV | ClientApp/src/app/new-user/new-user.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginService } from '../Services/login.service';
import { newUser, ComparePassword } from '../Structures/structures';
@Component({
selector: 'app-new-user',
templateUrl: './new-user.component.html',
styleUrls: ['./new-user.component.scss']
})
export class NewUserComponent implements OnInit {
public formNewUser: FormGroup;
constructor(private fb: FormBuilder, private login: LoginService, private route: Router) {
this.formNewUser = fb.group({
email: ['', [Validators.required,Validators.email]],
userName: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
},
{
// Used custom form validator name
validator: ComparePassword("password", "confirmPassword")
});
}
ngOnInit(): void {
}
submitNewUser() : void {
var u = {
emailAddress: this.formNewUser.get("email")?.value,
firstName: this.formNewUser.get("firstName")?.value,
lastName: this.formNewUser.get("lastName")?.value,
userName: this.formNewUser.get("userName")?.value,
password: this.formNewUser.get("password")?.value
} as newUser
console.log(u);
this.login.createUser(u).subscribe(result => {
this.route.navigate(['/signin']);
})
}
}
|
kevans2226/HRV | ClientApp/src/app/app.component.ts | <filename>ClientApp/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from './Services/login.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
title = 'HRV';
public userSignedIn: boolean = false;
public loading: boolean = false;
public userId: string;
constructor(private login: LoginService, private router: Router) {
}
ngOnInit(): void {
this.loading = true;
var jwt = localStorage.getItem("HRV_TOKEN");
if (jwt) {
this.login.checkUser().subscribe(result => {
if (!result.tokenValiden) {
this.clearLocalStorage();
this.userSignedIn = false;
}
else {
this.userSignedIn = true;
this.userId = localStorage.getItem("USER_ID");
var lastRefresh = Date.parse(localStorage.getItem("LAST_REFRESH"));
var currentDate = new Date().valueOf()
var dif = currentDate - lastRefresh;
var bolRefresh = (14400000 < dif);
console.log(`${lastRefresh} - ${currentDate} = ${dif} [${bolRefresh}]`);
if(bolRefresh) {
this.login.refreshToken().subscribe(result => {
localStorage.setItem("HRV_TOKEN", result.token);
localStorage.setItem("HRV_TOKEN_EXP", result.expiration.toString());
localStorage.setItem("USER_ID", result.userName);
localStorage.setItem("LAST_REFRESH", (new Date()).toString());
console.log("Token Refreshed");
}, error => {
console.error(error);
});
}
}
this.loading = false;
}, error => {
this.clearLocalStorage();
this.loading = false;
})
}
else {
console.log("No JWT");
this.clearLocalStorage();
this.loading = false;
this.userSignedIn = false;
}
}
private clearLocalStorage() {
localStorage.removeItem("HRV_TOKEN");
localStorage.removeItem("HRV_TOKEN_EXP");
localStorage.removeItem("USER_ID");
localStorage.removeItem("LAST_REFRESH");
}
public checkToken(): void {
var jwt = localStorage.getItem("HRV_TOKEN");
if (jwt) {
console.log("Checking Token");
this.userSignedIn = false;
this.userId = localStorage.getItem("USER_ID");
var bolLoggedIn = false;
this.login.checkUser().subscribe(result => {
console.log(result);
if (!result.tokenValiden) {
this.clearLocalStorage();
this.userSignedIn = false;
this.userId = "";
bolLoggedIn = false;
}
else {
this.userSignedIn = true;
this.userId = localStorage.getItem("USER_ID");
}
}, error => { console.error(error) });
}
else {
this.userSignedIn = false;
this.userId = "";
}
}
public logOff(): void {
console.log("logging off...")
this.clearLocalStorage();
this.userSignedIn = false;
this.router.navigate(["/home"]);
}
public logIn(): void {
this.clearLocalStorage();
this.router.navigate(['/signin']);
}
public signUp() : void {
this.clearLocalStorage();
this.router.navigate(["/newUser"]);
}
public passwordChange() : void {
this.router.navigate(['/passwordChange']);
}
}
|
typoon/coc-rust-analyzer | src/commands.ts | <reponame>typoon/coc-rust-analyzer<gh_stars>0
import { spawnSync, spawn } from 'child_process';
import readline from 'readline';
import { commands, Documentation, FloatFactory, Terminal, TerminalOptions, Uri, workspace } from 'coc.nvim';
import { Location, Position, Range, TextDocumentEdit, TextDocumentPositionParams, TextEdit, WorkspaceEdit } from 'vscode-languageserver-protocol';
import { Cmd, Ctx, isRustDocument } from './ctx';
import * as ra from './lsp_ext';
let terminal: Terminal | undefined;
class RunnableQuickPick {
label: string;
constructor(public runnable: ra.Runnable) {
this.label = runnable.label;
}
}
function isInRange(range: Range, position: Position): boolean {
const lineWithin = range.start.line <= position.line && range.end.line >= position.line;
const charWithin = range.start.character <= position.character && range.end.line >= position.character;
return lineWithin && charWithin;
}
function codeFormat(expanded: ra.ExpandedMacro): string {
let result = `// Recursive expansion of ${expanded.name}! macro\n`;
result += '// ' + '='.repeat(result.length - 3);
result += '\n\n';
result += expanded.expansion;
return result;
}
function parseSnippet(snip: string): [string, [number, number]] | undefined {
const m = snip.match(/\$(0|\{0:([^}]*)\})/);
if (!m) return undefined;
const placeholder = m[2] ?? '';
const range: [number, number] = [m.index!, placeholder.length];
const insert = snip.replace(m[0], placeholder);
return [insert, range];
}
function countLines(text: string): number {
return (text.match(/\n/g) || []).length;
}
export function analyzerStatus(ctx: Ctx): Cmd {
return async () => {
const { document } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const params: ra.AnalyzerStatusParams = {
textDocument: { uri: document.uri },
};
const ret = await ctx.client.sendRequest(ra.analyzerStatus, params);
workspace.echoLines(ret.split('\n'));
};
}
export function memoryUsage(ctx: Ctx): Cmd {
return async () => {
const ret = await ctx.client.sendRequest(ra.memoryUsage);
workspace.echoLines(ret.split('\n'));
};
}
export function matchingBrace(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const params: ra.MatchingBraceParams = {
textDocument: { uri: document.uri },
positions: [position],
};
const response = await ctx.client.sendRequest(ra.matchingBrace, params);
if (response.length > 0) {
workspace.jumpTo(document.uri, response[0]);
}
};
}
export function joinLines(ctx: Ctx): Cmd {
return async () => {
const doc = await workspace.document;
if (!isRustDocument(doc.textDocument)) return;
const mode = await workspace.nvim.call('visualmode');
const range = await workspace.getSelectedRange(mode, doc);
if (!range) {
return;
}
const param: ra.JoinLinesParams = {
textDocument: { uri: doc.uri },
ranges: [range],
};
const items = await ctx.client.sendRequest(ra.joinLines, param);
await doc.applyEdits(items);
};
}
export function parentModule(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const param: TextDocumentPositionParams = {
textDocument: { uri: document.uri },
position,
};
const response = await ctx.client.sendRequest(ra.parentModule, param);
if (response.length > 0) {
const uri = response[0].targetUri;
const range = response[0].targetRange;
workspace.jumpTo(uri, range?.start);
}
};
}
export function ssr(ctx: Ctx): Cmd {
return async () => {
const input = await workspace.callAsync<string>('input', ['Enter request like this: foo($a, $b) ==>> ($a).foo($b): ']);
workspace.nvim.command('normal! :<C-u>', true);
if (!input) {
return;
}
if (!input.includes('==>>')) {
return;
}
const selections: Range[] = [];
const mode = await workspace.nvim.call('visualmode');
if (mode) {
const doc = await workspace.document;
const range = await workspace.getSelectedRange(mode, doc);
if (range) selections.push(range);
}
const { document, position } = await workspace.getCurrentState();
const param: ra.SsrParams = {
query: input,
parseOnly: false,
textDocument: { uri: document.uri },
position,
selections,
};
const edit = await ctx.client.sendRequest(ra.ssr, param);
await workspace.applyEdit(edit);
};
}
export function serverVersion(ctx: Ctx): Cmd {
return async () => {
const bin = ctx.resolveBin();
if (!bin) {
const msg = `Rust Analyzer is not found`;
workspace.showMessage(msg, 'error');
return;
}
const version = spawnSync(bin, ['--version'], { encoding: 'utf-8' }).stdout;
workspace.showMessage(version);
};
}
export function run(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
workspace.showMessage(`Fetching runnable...`);
const params: ra.RunnablesParams = {
textDocument: { uri: document.uri },
position,
};
const runnables = await ctx.client.sendRequest(ra.runnables, params);
const items: RunnableQuickPick[] = [];
for (const r of runnables) {
items.push(new RunnableQuickPick(r));
}
const idx = await workspace.showQuickpick(items.map((o) => o.label));
if (idx === -1) {
return;
}
const runnable = items[idx].runnable;
const cmd = `${runnable.kind} ${runnable.args.cargoArgs.join(' ')}`;
const opt: TerminalOptions = {
name: runnable.label,
cwd: runnable.args.workspaceRoot,
};
if (terminal) {
terminal.dispose();
terminal = undefined;
}
terminal = await workspace.createTerminal(opt);
terminal.sendText(cmd);
};
}
export function debugSingle(): Cmd {
return async (runnable: ra.Runnable) => {
const { document } = await workspace.getCurrentState();
if (!runnable || !isRustDocument(document)) return;
const args = [...runnable.args.cargoArgs];
if (runnable.args.cargoExtraArgs.length > 0) {
args.push(...runnable.args.cargoExtraArgs);
}
// do not run tests, we will run through gdb
if (args[0] === 'test') {
args.push('--no-run');
}
// output as json
args.push('--message-format=json');
// remove noise
args.push('-q');
if (runnable.args.executableArgs.length > 0) {
args.push('--', ...runnable.args.executableArgs);
}
if (args[0] === 'run') {
args[0] = 'build';
}
console.debug(`${runnable.kind} ${args}`);
const proc = spawn(runnable.kind, args, { shell: true });
const rl = readline.createInterface({
input: proc.stdout,
crlfDelay: Infinity,
});
let executable = null;
for await (const line of rl) {
if (!line) {
continue;
}
let cargoMessage = {};
try {
cargoMessage = JSON.parse(line);
} catch (e) {
console.error(e);
continue;
}
if (!cargoMessage) {
console.debug(`Skipping cargo message: ${cargoMessage}`);
}
if (cargoMessage['reason'] !== 'compiler-artifact') {
console.debug(`Not artifact: ${cargoMessage['reason']}`);
continue;
}
if (!executable && cargoMessage['executable']) {
executable = cargoMessage['executable'];
}
}
if (!executable) {
throw new Error('Could not find executable');
}
const executableArgs = runnable.args.executableArgs.join(' ');
console.info(`Debugging executable: ${executable} ${executableArgs}`);
const debugConfig = workspace.getConfiguration('rust-analyzer.debug');
if (debugConfig.get<string>('runtime') == 'termdebug') {
await workspace.nvim.command(`TermdebugCommand ${executable} ${executableArgs}`);
return;
}
if (debugConfig.get<string>('runtime') == 'vimspector') {
const name = workspace.getConfiguration('rust-analyzer.debug.vimspector.configuration').get<string>('name');
const configuration = { configuration: name, Executable: executable, Args: executableArgs };
await workspace.nvim.call('vimspector#LaunchWithSettings', configuration);
return;
}
throw new Error(`Invalid debug runtime: ${debugConfig.get<string>('runtime')}`);
};
}
export function runSingle(): Cmd {
return async (runnable: ra.Runnable) => {
const { document } = await workspace.getCurrentState();
if (!runnable || !isRustDocument(document)) return;
const args = [...runnable.args.cargoArgs];
if (runnable.args.cargoExtraArgs.length > 0) {
args.push(...runnable.args.cargoExtraArgs);
}
if (runnable.args.executableArgs.length > 0) {
args.push('--', ...runnable.args.executableArgs);
}
const cmd = `${runnable.kind} ${args.join(' ')}`;
const opt: TerminalOptions = {
name: runnable.label,
cwd: runnable.args.workspaceRoot,
};
if (terminal) {
terminal.dispose();
terminal = undefined;
}
terminal = await workspace.createTerminal(opt);
terminal.sendText(cmd);
};
}
export function syntaxTree(ctx: Ctx): Cmd {
return async () => {
const doc = await workspace.document;
if (!isRustDocument(doc.textDocument)) return;
const mode = await workspace.nvim.call('visualmode');
let range: Range | null = null;
if (mode) {
range = await workspace.getSelectedRange(mode, doc);
}
const param: ra.SyntaxTreeParams = {
textDocument: { uri: doc.uri },
range,
};
const ret = await ctx.client.sendRequest(ra.syntaxTree, param);
await workspace.nvim.command('tabnew').then(async () => {
const buf = await workspace.nvim.buffer;
buf.setLines(ret.split('\n'), { start: 0, end: -1 });
});
};
}
export function expandMacro(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const param: TextDocumentPositionParams = {
textDocument: { uri: document.uri },
position,
};
const expanded = await ctx.client.sendRequest(ra.expandMacro, param);
if (!expanded) {
return;
}
await workspace.nvim.command('tabnew').then(async () => {
const buf = await workspace.nvim.buffer;
buf.setLines(codeFormat(expanded).split('\n'), { start: 0, end: -1 });
});
};
}
export function explainError(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const diagnostic = ctx.client.diagnostics?.get(workspace.uri)?.find((diagnostic) => isInRange(diagnostic.range, position));
if (diagnostic?.code) {
const explaination = spawnSync('rustc', ['--explain', `${diagnostic.code}`], { encoding: 'utf-8' }).stdout;
const docs: Documentation[] = [];
let isCode = false;
for (const part of explaination.split('```\n')) {
docs.push({ content: part, filetype: isCode ? 'rust' : 'markdown' });
isCode = !isCode;
}
const factory: FloatFactory = new FloatFactory(workspace.nvim, workspace.env);
await factory.create(docs);
}
};
}
export function reloadWorkspace(ctx: Ctx): Cmd {
return async () => {
await ctx.client.sendRequest(ra.reloadWorkspace);
};
}
export function showReferences(): Cmd {
return async (uri: string, position: Position, locations: Location[]) => {
if (!uri) {
return;
}
await commands.executeCommand('editor.action.showReferences', Uri.parse(uri), position, locations);
};
}
export function upgrade(ctx: Ctx) {
return async () => {
await ctx.checkUpdate(false);
};
}
export function toggleInlayHints(ctx: Ctx) {
return async () => {
if (!ctx.config.inlayHints.chainingHints) {
workspace.showMessage(`Inlay hints for method chains is disabled. Toggle action does nothing;`, 'warning');
return;
}
await ctx.toggleInlayHints();
};
}
export async function applySnippetWorkspaceEdit(edit: WorkspaceEdit) {
if (!edit?.documentChanges?.length) {
return;
}
let selection: Range | undefined = undefined;
let position: Position | undefined = undefined;
let lineDelta = 0;
const change = edit.documentChanges[0];
if (TextDocumentEdit.is(change)) {
const newEdits: TextEdit[] = [];
for (const indel of change.edits) {
let { newText } = indel;
const parsed = parseSnippet(indel.newText);
if (parsed) {
const [insert, [placeholderStart, placeholderLength]] = parsed;
const prefix = insert.substr(0, placeholderStart);
const lastNewline = prefix.lastIndexOf('\n');
const startLine = indel.range.start.line + lineDelta + countLines(prefix);
const startColumn = lastNewline === -1 ? indel.range.start.character + placeholderStart : prefix.length - lastNewline - 1;
if (placeholderLength) {
selection = Range.create(startLine, startColumn, startLine, startColumn + placeholderLength);
} else {
position = Position.create(startLine, startColumn);
}
newText = insert;
} else {
lineDelta = countLines(indel.newText) - (indel.range.end.line - indel.range.start.line);
}
newEdits.push(TextEdit.replace(indel.range, newText));
}
const wsEdit: WorkspaceEdit = {
changes: {
[change.textDocument.uri]: newEdits,
},
};
await workspace.applyEdit(wsEdit);
const current = await workspace.document;
if (current.uri !== change.textDocument.uri) {
await workspace.loadFile(change.textDocument.uri);
await workspace.jumpTo(change.textDocument.uri);
}
if (selection) {
await workspace.selectRange(selection);
} else if (position) {
await workspace.moveTo(position);
}
}
}
export function applySnippetWorkspaceEditCommand(): Cmd {
return async (edit: WorkspaceEdit) => {
await applySnippetWorkspaceEdit(edit);
};
}
export function resolveCodeAction(ctx: Ctx): Cmd {
return async (params: ra.ResolveCodeActionParams) => {
const edit: WorkspaceEdit = await ctx.client.sendRequest(ra.resolveCodeAction, params);
if (!edit) return;
await applySnippetWorkspaceEdit(edit);
};
}
export function openDocs(ctx: Ctx): Cmd {
return async () => {
const { document, position } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const param: TextDocumentPositionParams = {
textDocument: { uri: document.uri },
position,
};
const doclink = await ctx.client.sendRequest(ra.openDocs, param);
if (doclink) {
await commands.executeCommand('vscode.open', Uri.parse(doclink));
}
};
}
export function openCargoToml(ctx: Ctx): Cmd {
return async () => {
const { document } = await workspace.getCurrentState();
if (!isRustDocument(document)) return;
const location = await ctx.client.sendRequest(ra.openCargoToml, {
textDocument: { uri: document.uri },
});
if (!location) return;
await workspace.jumpTo(location.uri);
};
}
|
looker/ts-babel-node | test/cases/destructure.ts | <filename>test/cases/destructure.ts
import 'babel-polyfill';
import { delay } from 'bluebird';
async function main() {
const { foo } = await getStuff();
console.log(foo);
}
async function getStuff() {
await delay(100);
return { foo: 'bar', bar: 'baz' };
}
main().catch(err => console.log(err.stack));
|
looker/ts-babel-node | test/cases/supports.tsx | <filename>test/cases/supports.tsx<gh_stars>10-100
process.stdout.write('testing\n');
|
looker/ts-babel-node | test/cases/custom-babel/test.ts | <filename>test/cases/custom-babel/test.ts
console.log('this should not appear');
process.stdout.write('this is the only thing that should appear\n');
|
looker/ts-babel-node | test/cases/sync-throw.ts | <filename>test/cases/sync-throw.ts
import 'babel-polyfill';
function main() {
throwError();
}
function throwError() {
throw new Error('test error');
}
try {
main();
} catch (err) {
console.log(err.stack);
}
|
jruipinto/search-dropdown-filter-wc | components/dropdown-item-list.element.d.ts | import { LitElement } from 'lit';
/**
* This is the element that presents the list under
* the dropdown button
*/
export declare class DropdownItemList extends LitElement {
static styles: import("lit").CSSResultGroup;
/**
* Items to be presented in this list
*/
items: string[];
dropdownItemTemplate(item: string, index: number): import("lit-html").TemplateResult<1>;
render(): import("lit-html").TemplateResult<1>;
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-item-list': DropdownItemList;
}
}
//# sourceMappingURL=dropdown-item-list.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | components/search-input.element.d.ts | <filename>components/search-input.element.d.ts<gh_stars>0
import { LitElement } from 'lit';
import './magnifier-icon.element';
/**
* this is the search input element wich shows a magnifier on its left
*/
export declare class SearchInput extends LitElement {
static styles: import("lit").CSSResultGroup;
render(): import("lit-html").TemplateResult<1>;
}
declare global {
interface HTMLElementTagNameMap {
'app-search-input': SearchInput;
}
}
//# sourceMappingURL=search-input.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | components/magnifier-icon.element.d.ts | import { LitElement } from 'lit';
/**
* This is the element that contains the SVG
* for the magnifier icon
*/
export declare class MagnifierIcon extends LitElement {
static styles: import("lit").CSSResultGroup;
render(): import("lit-html").TemplateResult<1>;
}
declare global {
interface HTMLElementTagNameMap {
'app-magnifier-icon': MagnifierIcon;
}
}
//# sourceMappingURL=magnifier-icon.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | src/components/dropdown-icon.element.ts | <reponame>jruipinto/search-dropdown-filter-wc
import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
/**
* This is the element that contains the SVG
* for the dropdown icon on its rigt side
*/
@customElement('app-dropdown-icon')
export class DropdownIcon extends LitElement {
static styles = css`
:host {
display: block;
}
`;
render() {
return html`
<svg
xmlns="http://www.w3.org/2000/svg"
height="24px"
viewBox="0 0 24 24"
width="24px"
fill="#000000"
>
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M7 10l5 5 5-5H7z" />
</svg>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-icon': DropdownIcon;
}
}
|
jruipinto/search-dropdown-filter-wc | components/dropdown-icon.element.d.ts | <filename>components/dropdown-icon.element.d.ts<gh_stars>0
import { LitElement } from 'lit';
/**
* This is the element that contains the SVG
* for the dropdown icon on its rigt side
*/
export declare class DropdownIcon extends LitElement {
static styles: import("lit").CSSResultGroup;
render(): import("lit-html").TemplateResult<1>;
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-icon': DropdownIcon;
}
}
//# sourceMappingURL=dropdown-icon.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | src/components/search-input.element.ts | import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
import './magnifier-icon.element';
/**
* this is the search input element wich shows a magnifier on its left
*/
@customElement('app-search-input')
export class SearchInput extends LitElement {
static styles = css`
:host {
display: block;
position: relative;
}
input[type='search'] {
width: 100%;
padding: 0.5em 1em;
padding-left: 2.5em;
}
app-magnifier-icon {
position: absolute;
top: 0.2em;
left: 0.2em;
}
`;
render() {
return html`
<app-magnifier-icon></app-magnifier-icon>
<input
type="search"
@input=${(e: Event) => {
const searchInputEvt = new CustomEvent('searchinput', {
detail: {
value: (e.target as HTMLInputElement).value,
},
});
this.dispatchEvent(searchInputEvt);
}}
/>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-search-input': SearchInput;
}
}
|
jruipinto/search-dropdown-filter-wc | components/dropdown-button.element.d.ts | <gh_stars>0
import { LitElement } from 'lit';
import './dropdown-icon.element';
/**
* This is the dropdown button with dropdown icon
* in its right side
*/
export declare class DropdownButton extends LitElement {
static styles: import("lit").CSSResultGroup;
/**
* Search input option (default).
*/
inp: string;
render(): import("lit-html").TemplateResult<1>;
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-button': DropdownButton;
}
}
//# sourceMappingURL=dropdown-button.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | src/test/search-drop-down-filter-wc_test.ts | <reponame>jruipinto/search-dropdown-filter-wc<gh_stars>0
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
import {SearchDropdownFilter} from '../search-drop-down-filter-wc.element.js';
import {fixture, html} from '@open-wc/testing';
const assert = chai.assert;
suite('search-drop-down-filter-wc', () => {
test('is defined', () => {
const el = document.createElement('search-drop-down-filter-wc');
assert.instanceOf(el, SearchDropdownFilter);
});
test('renders with default values', async () => {
const el = await fixture(
html`<search-drop-down-filter-wc></search-drop-down-filter-wc>`
);
assert.shadowDom.equal(
el,
`
<h1>Hello, World!</h1>
<button part="button">Click Count: 0</button>
<slot></slot>
`
);
});
test('renders with a set name', async () => {
const el = await fixture(
html`<search-drop-down-filter-wc
?search=${true}
?dropdown=${true}
.datalist=${['one', 'two', 'three']}
></search-drop-down-filter-wc>`
);
assert.shadowDom.equal(
el,
`
<search-drop-down-filter-wc>
<app-search-input>
<app-magnifier-icon>
<svg
xmlns="http://www.w3.org/2000/svg"
height="24px"
viewBox="0 0 24 24"
width="24px"
fill="#000000"
>
<path d="M0 0h24v24H0z" fill="none" />
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
</app-magnifier-icon>
</app-search-input>
</search-drop-down-filter-wc>
`
);
});
test('handles a click', async () => {
const el = (await fixture(
html`<search-drop-down-filter-wc></search-drop-down-filter-wc>`
)) as SearchDropdownFilter;
const button = el.shadowRoot!.querySelector('button')!;
button.click();
await el.updateComplete;
assert.shadowDom.equal(
el,
`
<h1>Hello, World!</h1>
<button part="button">Click Count: 1</button>
<slot></slot>
`
);
});
test('styling applied', async () => {
const el = (await fixture(
html`<search-drop-down-filter-wc></search-drop-down-filter-wc>`
)) as SearchDropdownFilter;
await el.updateComplete;
assert.equal(getComputedStyle(el).paddingTop, '16px');
});
});
|
jruipinto/search-dropdown-filter-wc | models/dropdown-item.model.d.ts | <reponame>jruipinto/search-dropdown-filter-wc<gh_stars>0
//# sourceMappingURL=dropdown-item.model.d.ts.map |
jruipinto/search-dropdown-filter-wc | src/components/dropdown-item-list.element.ts | <reponame>jruipinto/search-dropdown-filter-wc
import {LitElement, html, css} from 'lit';
import {customElement, property} from 'lit/decorators.js';
/**
* This is the element that presents the list under
* the dropdown button
*/
@customElement('app-dropdown-item-list')
export class DropdownItemList extends LitElement {
static styles = css`
* {
box-sizing: border-box;
}
:host {
display: block;
}
.item-list {
display: flex;
flex-direction: column;
}
.item {
display: block;
position: relative;
}
.item input[type='radio'] {
display: none;
}
.item label {
display: inline-block;
font-family: sans-serif;
background-color: #ddd;
padding: 0.5em 1em;
width: 100%;
border: solid 1px gray;
}
.item input[type='radio']:checked + label {
background-color: #bbb;
}
`;
/**
* Items to be presented in this list
*/
@property({type: Array})
items: string[] = [];
dropdownItemTemplate(item: string, index: number) {
return html`
<div class="item">
<input
type="radio"
id="item${index}"
name="search-item"
.value=${item}
/>
<label for="item${index}">${item}</label>
</div>
`;
}
render() {
return html`
<div class="item-list">
${this.items.map(this.dropdownItemTemplate)}
</div>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-item-list': DropdownItemList;
}
}
|
jruipinto/search-dropdown-filter-wc | src/search-drop-down-filter-wc.element.ts | /**
* @license
* SPDX-License-Identifier: MIT
*/
import {LitElement, html, css} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import './components/dropdown-item-list.element';
import './components/search-input.element';
import './components/dropdown-button.element';
/**
* This is a WebComponent made with lit with configurable option
* to show a search input, dropdown or search with dropdown filter
*
* - if property **search** is set then it looks like a normal input with magnifier icon on left.
* - if property **dropdown** is set then it behaves like dropdown (with some dummy radio group) with drop-down icon on right
* - if both **search** and **dropdown** property are set then it will be a drop-down search filtering
*/
@customElement('search-drop-down-filter-wc')
export class SearchDropdownFilter extends LitElement {
static styles = css`
:host {
display: block;
}
`;
/**
* Search input option (default).
*/
@property({type: Boolean})
search = true;
/**
* Dropdown option.
*/
@property({type: Boolean})
dropdown = true;
/**
* Datalist to be presented by dropdown.
* It has a default value for demo purposes
*/
@property({type: Array})
datalist = ['one', 'two', 'three'];
/**
* Datalist to be presented by dropdown when "search filter mode".
*/
@property({type: Array})
filteredDatalist: string[] = [];
/**
* Item list option.
*/
@property({type: Boolean})
isItemListOpen = false;
render() {
return html`
${this.getDropdownButton(this.dropdown, this.search)}
${this.getSearchInput(this.search)}
${this.getDropdownItemList(this.isItemListOpen)}
`;
}
toogleDropdownItemList(): void {
this.isItemListOpen = !this.isItemListOpen;
this.filteredDatalist = this.datalist;
}
filterDropdownItemList({detail}: CustomEvent) {
const searchInputValue = detail.value;
this.isItemListOpen = this.dropdown && this.search ? true : false;
if (searchInputValue.length) {
this.filteredDatalist = this.datalist.filter((item) =>
item.includes(searchInputValue)
);
return;
}
this.filteredDatalist = [];
}
getDropdownItemList(isItemListOpen: boolean) {
if (isItemListOpen) {
return html`
<app-dropdown-item-list
.items=${this.filteredDatalist}
></app-dropdown-item-list>
`;
}
return '';
}
getDropdownButton(dropdown: boolean, search: boolean) {
if (dropdown && !search) {
return html`
<app-dropdown-button
@click=${this.toogleDropdownItemList}
></app-dropdown-button>
`;
}
return '';
}
getSearchInput(search: boolean) {
if (search) {
return html`
<app-search-input
@searchinput=${this.filterDropdownItemList}
></app-search-input>
`;
}
return '';
}
}
declare global {
interface HTMLElementTagNameMap {
'search-drop-down-filter-wc': SearchDropdownFilter;
}
}
|
jruipinto/search-dropdown-filter-wc | src/components/magnifier-icon.element.ts | <reponame>jruipinto/search-dropdown-filter-wc<gh_stars>0
import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
/**
* This is the element that contains the SVG
* for the magnifier icon
*/
@customElement('app-magnifier-icon')
export class MagnifierIcon extends LitElement {
static styles = css`
:host {
display: block;
}
`;
render() {
return html`
<svg
xmlns="http://www.w3.org/2000/svg"
height="24px"
viewBox="0 0 24 24"
width="24px"
fill="#000000"
>
<path d="M0 0h24v24H0z" fill="none" />
<path
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>
</svg>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-magnifier-icon': MagnifierIcon;
}
}
|
jruipinto/search-dropdown-filter-wc | search-drop-down-filter-wc.element.d.ts | /**
* @license
* SPDX-License-Identifier: MIT
*/
import { LitElement } from 'lit';
import './components/dropdown-item-list.element';
import './components/search-input.element';
import './components/dropdown-button.element';
/**
* This is a WebComponent made with lit with configurable option
* to show a search input, dropdown or search with dropdown filter
*
* - if property **search** is set then it looks like a normal input with magnifier icon on left.
* - if property **dropdown** is set then it behaves like dropdown (with some dummy radio group) with drop-down icon on right
* - if both **search** and **dropdown** property are set then it will be a drop-down search filtering
*/
export declare class SearchDropdownFilter extends LitElement {
static styles: import("lit").CSSResultGroup;
/**
* Search input option (default).
*/
search: boolean;
/**
* Dropdown option.
*/
dropdown: boolean;
/**
* Datalist to be presented by dropdown.
* It has a default value for demo purposes
*/
datalist: string[];
/**
* Datalist to be presented by dropdown when "search filter mode".
*/
filteredDatalist: string[];
/**
* Item list option.
*/
isItemListOpen: boolean;
render(): import("lit-html").TemplateResult<1>;
toogleDropdownItemList(): void;
filterDropdownItemList({ detail }: CustomEvent): void;
getDropdownItemList(isItemListOpen: boolean): import("lit-html").TemplateResult<1> | "";
getDropdownButton(dropdown: boolean, search: boolean): import("lit-html").TemplateResult<1> | "";
getSearchInput(search: boolean): import("lit-html").TemplateResult<1> | "";
}
declare global {
interface HTMLElementTagNameMap {
'search-drop-down-filter-wc': SearchDropdownFilter;
}
}
//# sourceMappingURL=search-drop-down-filter-wc.element.d.ts.map |
jruipinto/search-dropdown-filter-wc | src/components/dropdown-button.element.ts | <gh_stars>0
import {customElement, property} from 'lit/decorators.js';
import {LitElement, html, css} from 'lit';
import './dropdown-icon.element';
/**
* This is the dropdown button with dropdown icon
* in its right side
*/
@customElement('app-dropdown-button')
export class DropdownButton extends LitElement {
static styles = css`
:host {
display: block;
border: solid 1px gray;
position: relative;
}
button {
text-transform: uppercase;
width: 100%;
border: 0;
background-color: gray;
padding: 0.5em 1em;
}
button:hover {
filter: brightness(1.2);
}
app-dropdown-icon {
position: absolute;
top: 0.2em;
right: 0.2em;
}
`;
/**
* Search input option (default).
*/
@property()
inp = '';
render() {
return html`
<button>dropdown</button>
<app-dropdown-icon></app-dropdown-icon>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'app-dropdown-button': DropdownButton;
}
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/024_meetingRoomAmongUs/components/dialog/LeaveMeetingDialog.tsx | <gh_stars>0
import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from "@material-ui/core";
import React from "react";
import { useAppState } from "../../../../providers/AppStateProvider";
type LeaveMeetingDialogProps = {
open:boolean,
onClose:()=>void
}
export const LeaveMeetingDialog = (props:LeaveMeetingDialogProps) =>{
const {setStage, leaveMeeting} = useAppState()
return(
<Dialog disableBackdropClick disableEscapeKeyDown open={props.open} onClose={props.onClose} >
<DialogTitle>Leave meeting</DialogTitle>
<DialogContent>
You are leaving meeting.
</DialogContent>
<DialogActions>
<Button onClick={(e)=>{props.onClose();leaveMeeting();setStage("SIGNIN")}} color="primary">
Ok
</Button>
<Button onClick={props.onClose} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/RecorderView.tsx | <gh_stars>0
import React, { useEffect, useMemo } from "react"
import { Divider, Typography } from '@material-ui/core'
import { VideoTileState } from "amazon-chime-sdk-js";
import { useAppState } from "../../../../providers/AppStateProvider";
import { RendererForRecorder } from "./helper/RendererForRecorder";
export type FocustTarget = "SharedContent" | "Speaker"
type Props = {
width: number
height: number
setRecorderCanvas?: (c:HTMLCanvasElement|null)=>void
};
export const RecorderView = ({ width, height, setRecorderCanvas }: Props) => {
const { videoTileStates, activeSpeakerId, meetingSession } = useAppState()
const renderer = useMemo(()=>{return new RendererForRecorder(meetingSession!)},[]) // eslint-disable-line
const contentsTiles = Object.values(videoTileStates).filter(tile=>{return tile.isContent})
const activeSpekerTile = activeSpeakerId && videoTileStates[activeSpeakerId] ? videoTileStates[activeSpeakerId] : null
const targetTiles = (contentsTiles.length > 0 ? contentsTiles : [activeSpekerTile]).filter(tile=>{return tile!==null}) as VideoTileState[]
const targetTilesId = targetTiles.reduce<string>((sum,cur)=>{return `${sum}-${cur.boundAttendeeId}`},"")
//// setup renderer
useEffect(() => {
const dstCanvas = document.getElementById("recorderCanvas") as HTMLCanvasElement
renderer.init(dstCanvas)
renderer.start()
return () => {
console.log("destroy renderer", renderer)
renderer.destroy()
}
}, []) // eslint-disable-line
//// setTargetTileNum
useEffect(()=>{
console.log("TARGET CHANGE!", targetTilesId)
const videoElems = [...Array(targetTiles.length)].map((v,i)=>{return document.getElementById(`video${i}`) as HTMLVideoElement})
console.log(videoElems)
targetTiles.forEach((tile,index)=>{
if(tile.tileId){
meetingSession?.audioVideo.bindVideoElement(tile.tileId, videoElems[index])
}
})
renderer.setSrcVideoElements(videoElems)
},[targetTilesId]) // eslint-disable-line
// notify recorder canvas to parent (to access from sidebar pane)
useEffect(() => {
console.log("set recorder canvas")
const dstCanvas = document.getElementById("recorderCanvas") as HTMLCanvasElement
setRecorderCanvas!(dstCanvas)
return () => {
console.log("remove recorder canvas")
setRecorderCanvas!(null)
}
}, []) // eslint-disable-line
return (
<div style={{ width: width, height: height }}>
<div style={{ width: "100%", height: "70%", objectFit: "contain", background:"#bbbbbb"}}>
<canvas width="1920" height="1080" id="recorderCanvas" style={{ width: "100%", height: "100%", border: "medium solid #ffaaaa"}} />
</div>
<div style={{ width: "100%", height: "20%", objectFit: "contain" }}>
<Divider />
<Typography variant="body2" color="textSecondary">
resources
</Typography>
<video id="video0" style={{width:50, height:50}}/>
<video id="video1" style={{width:50, height:50}}/>
<video id="video2" style={{width:50, height:50}}/>
<video id="video3" style={{width:50, height:50}}/>
<video id="video4" style={{width:50, height:50}}/>
<video id="video5" style={{width:50, height:50}}/>
<video id="video6" style={{width:50, height:50}}/>
<video id="video7" style={{width:50, height:50}}/>
<video id="video8" style={{width:50, height:50}}/>
<video id="video9" style={{width:50, height:50}}/>
</div>
</div>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/sidebars/OnetimeCodePanel.tsx | import React, { useMemo, useState } from 'react';
import { Link, Typography } from '@material-ui/core';
import { useStyles } from './css';
import { useAppState } from '../../../../providers/AppStateProvider';
import { generateOnetimeCode } from '../../../../api/api';
var QRCode = require('qrcode.react');
export const OnetimeCodePanel = () => {
const classes = useStyles();
const { meetingName, attendeeId, idToken, accessToken, refreshToken} = useAppState()
const [url, setURL] = useState<string>()
const [onetimeCode, setOnetimeCode] = useState<string>()
const qrcode = useMemo(()=>{
return url ? <QRCode value={url} />:<></>
},[url])
const handleGenerateOnetimeCode = async () =>{
const res = await generateOnetimeCode(meetingName!, attendeeId!, idToken!, accessToken!, refreshToken!)
const url = `${window.location.href}?stage=MEETING_MANAGER_SIGNIN&uuid=${res.uuid}&meetingName=${meetingName}&attendeeId=${attendeeId}`
console.log("generatecode",res, url)
setURL(url)
setOnetimeCode(res.code)
}
return (
<div className={classes.root}>
<Typography variant="body1" color="textSecondary">
One Time Code
</Typography>
<Link onClick={(e: any) => { handleGenerateOnetimeCode() }}>
generateCode
</Link>
<Typography variant="body1" color="textSecondary">
<a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
</Typography>
{qrcode}
<div>
{onetimeCode}
</div>
</div>
);
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/013_requestChangePassword/index.tsx | <reponame>diitalk/flect-chime-sdk-demo
import { Avatar, Box, Button, CircularProgress, Container, CssBaseline, Grid, Link, makeStyles, TextField, Typography, withStyles } from "@material-ui/core";
import React, { useState } from "react";
import { useAppState } from "../../providers/AppStateProvider";
import { Lock } from '@material-ui/icons';
import { Copyright } from "../000_common/Copyright";
const useStyles = makeStyles((theme) => ({
root: {
background: 'white',
},
root_amongus: {
background: 'black'
},
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.primary.main,
},
form: {
width: '100%',
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
margin: {
margin: theme.spacing(1),
},
input: {
color: 'black',
},
input_amongus: {
color: 'blue'
}
}));
const CustomTextField = withStyles({
root: {
'& input:valid + fieldset': {
borderColor: 'blue',
borderWidth: 1,
},
'& input:invalid + fieldset': {
borderColor: 'blue',
borderWidth: 1,
},
'& input:valid:focus + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:valid:hover + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
// padding: '4px !important',
},
'& input:invalid:hover + fieldset': {
borderColor: 'blue',
borderLeftWidth: 6,
color: 'blue'
// padding: '4px !important',
},
'& label.Mui-focused': {
color: 'blue',
},
'& label.MuiInputLabel-root': {
color: 'blue',
},
},
})(TextField);
export const RequestChangePassword = () => {
const classes = useStyles();
const { userId: curUserId, handleSendVerificationCodeForChangePassword, setMessage, setStage, mode } = useAppState()
const [userId, setUserId] = useState(curUserId || "")
const [isLoading, setIsLoading] = useState(false)
const onSendVerificationCodeForChangePasswordClicked = () => {
setIsLoading(true)
handleSendVerificationCodeForChangePassword(userId || "").then(()=>{
console.log("send verify code fo changing password")
setMessage("Info", "Send Verification Code success ", [`Verification is accepted.`] )
setIsLoading(false)
setStage("NEW_PASSWORD")
}).catch(e=>{
console.log(e)
setMessage("Exception", "request change password error", [`${e.message}`, `(code: ${e.code})`] )
setIsLoading(false)
})
}
return (
<Container maxWidth="xs" className={mode === "amongus" ? classes.root_amongus : classes.root}>
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<Lock />
</Avatar>
<Typography variant="h4" color={mode === "amongus" ? "secondary":"primary"} >
Send Verification Code
</Typography>
<Typography variant="h4" color={mode === "amongus" ? "secondary":"primary"} >
for Change Password
</Typography>
<form className={classes.form} noValidate>
<CustomTextField
required
variant="outlined"
margin="normal"
fullWidth
id="email"
name="email"
label="Email Address"
autoComplete="email"
autoFocus
value={userId}
onChange={(e) => setUserId(e.target.value)}
InputProps={{
className: mode === "amongus" ? classes.input_amongus : classes.input,
}}
/>
<Grid container direction="column" alignItems="center" >
{
isLoading ?
<CircularProgress />
:
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onSendVerificationCodeForChangePasswordClicked}
>
Send verification code
</Button>
}
</Grid>
<Grid container direction="column" >
<Grid item xs>
<Link onClick={(e: any) => { setStage("SIGNIN") }}>
return to home
</Link>
</Grid>
</Grid>
<Box mt={8}>
<Copyright />
</Box>
</form>
</div>
</Container>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/101_MeetingManager/MeetingManager.tsx | import { AppBar, createMuiTheme, CssBaseline, ThemeProvider, Toolbar } from "@material-ui/core"
import React, { useEffect, useState } from "react"
import { useAppState } from "../../providers/AppStateProvider"
import { DialogOpener } from "../023_meetingRoom/components/appbars/DialogOpener"
import { FeatureEnabler } from "../023_meetingRoom/components/appbars/FeatureEnabler"
import { AttendeesTable } from "../023_meetingRoom/components/sidebars/AttendeesTable"
import { BGMPanel } from "../023_meetingRoom/components/sidebars/BGMPanel"
import { ChatArea } from "../023_meetingRoom/components/sidebars/ChatArea"
import { CreditPanel } from "../023_meetingRoom/components/sidebars/CreditPanel"
import { CustomAccordion } from "../023_meetingRoom/components/sidebars/CustomAccordion"
import { RecorderPanel } from "../023_meetingRoom/components/sidebars/RecorderPanel"
import { useStyles } from "../023_meetingRoom/css"
import clsx from 'clsx';
import { Title } from "../023_meetingRoom/components/appbars/Title"
import { LeaveMeetingDialog } from "../023_meetingRoom/components/dialog/LeaveMeetingDialog"
const toolbarHeight = 20
const theme = createMuiTheme({
mixins: {
toolbar: {
minHeight: toolbarHeight,
}
},
});
export const MeetingManager = () => {
const classes = useStyles()
const { meetingName, audioOutputDeviceSetting, isShareContent,
startShareScreen, stopShareScreen, audioOutputList} = useAppState()
const [leaveDialogOpen, setLeaveDialogOpen] = useState(false);
const enableShareScreen = (val:boolean) =>{
if(val){
startShareScreen()
}else{
stopShareScreen()
}
}
useEffect(()=>{
const audioOutput = (audioOutputList && audioOutputList!.length > 0) ? audioOutputList[0].deviceId:null
audioOutputDeviceSetting!.setAudioOutput(audioOutput).then(()=>{
const audioElement = document.getElementById("for-speaker")! as HTMLAudioElement
audioElement.autoplay=false
audioElement.volume = 0
audioOutputDeviceSetting!.setOutputAudioElement(audioElement)
})
},[]) // eslint-disable-line
return (
<ThemeProvider theme={theme}>
<CssBaseline />
aaa
<div className={classes.root}>
<AppBar position="absolute" className={clsx(classes.appBar)}>
<Toolbar className={classes.toolbar}>
<div className={classes.toolbarInnnerBox}>
</div>
<div className={classes.toolbarInnnerBox}>
<Title title={meetingName||""} />
</div>
<div className={classes.toolbarInnnerBox}>
<div className={classes.toolbarInnnerBox}>
<span className={clsx(classes.menuSpacer)}> </span>
<FeatureEnabler type="ShareScreen" enable={isShareContent} setEnable={(val:boolean)=>{enableShareScreen(val)}}/>
<span className={clsx(classes.menuSpacer)}> </span>
<span className={clsx(classes.menuSpacer)}> </span>
<DialogOpener type="LeaveMeeting" onClick={()=>setLeaveDialogOpen(true)}/>
</div>
<div className={classes.toolbarInnnerBox}>
</div>
</div>
</Toolbar>
</AppBar>
<LeaveMeetingDialog open={leaveDialogOpen} onClose={()=>setLeaveDialogOpen(false)} />
<div style={{display:"flex", flexDirection:"column"}}>
<CustomAccordion title="Member">
<AttendeesTable/>
</CustomAccordion>
<CustomAccordion title="Chat">
<ChatArea/>
</CustomAccordion>
<CustomAccordion title="RecordMeeting (exp.)">
<RecorderPanel />
</CustomAccordion>
<CustomAccordion title="BGM/SE">
<BGMPanel />
</CustomAccordion>
<CustomAccordion title="About">
<CreditPanel />
</CustomAccordion>
</div>
</div>
{/* ************************************** */}
{/* ***** Hidden Elements ***** */}
{/* ************************************** */}
<div>
<audio id="for-speaker" style={{display:"none"}}/>
</div>
</ThemeProvider>
)
}
|
diitalk/flect-chime-sdk-demo | frontend3/src/frameProcessors/VirtualBackground.ts | import { CanvasVideoFrameBuffer, VideoFrameBuffer, VideoFrameProcessor } from "amazon-chime-sdk-js";
import { BodypixWorkerManager, generateBodyPixDefaultConfig, generateDefaultBodyPixParams, ModelConfigMobileNetV1_05, SemanticPersonSegmentation } from "@dannadori/bodypix-worker-js"
import { generateGoogleMeetSegmentationDefaultConfig, generateDefaultGoogleMeetSegmentationParams, GoogleMeetSegmentationWorkerManager, GoogleMeetSegmentationSmoothingType } from '@dannadori/googlemeet-segmentation-worker-js'
import { generateDefaultGoogleMeetSegmentationTFLiteParams, generateGoogleMeetSegmentationTFLiteDefaultConfig, GoogleMeetSegmentationTFLiteWorkerManager } from "@dannadori/googlemeet-segmentation-tflite-worker-js"
export type VirtualBackgroundSegmentationType = "None" | "BodyPix" | "GoogleMeet" | "GoogleMeetTFLite"
export type BackgroundMode = "Image" | "Blur" | "Color"
interface VirtualBackgroundConfig {
frontPositionX: number, // ratio (position and size of front image)
frontPositionY: number, // ratio (position and size of front image)
frontWidth: number, // ratio (position and size of front image)
frontHeight: number, // ratio (position and size of front image)
width: number, // pixel (output size. If =<0, fit the background canvas size )
height: number, // pixel (output size. If =<0, fit the background canvas size )
type: VirtualBackgroundSegmentationType,
backgroundMode: BackgroundMode,
backgroundImage: HTMLCanvasElement | HTMLImageElement | null,
backgroundColor: string,
}
export class VirtualBackground implements VideoFrameProcessor {
canvasFront = document.createElement('canvas')
canvasFrontResized = document.createElement("canvas")
canvasBackground = document.createElement("canvas")
inputCanvas = document.createElement("canvas")
personCanvas = document.createElement("canvas")
personMaskCanvas = document.createElement("canvas")
lightWrapCanvas = document.createElement("canvas")
private config: VirtualBackgroundConfig = {
frontPositionX: 0, // ratio (position and size of front image)
frontPositionY: 0, // ratio (position and size of front image)
frontWidth: 1, // ratio (position and size of front image)
frontHeight: 1, // ratio (position and size of front image)
width: -1, // pixel (output size. If =<0, fit the background canvas size )
height: -1, // pixel (output size. If =<0, fit the background canvas size )
type: "None",
backgroundMode: "Color",
backgroundImage: null,
backgroundColor: "#000000"
}
//////////////////////////////
// Video Processing API RSC //
//////////////////////////////
targetCanvas = document.createElement('canvas')
targetCanvasCtx = this.targetCanvas!.getContext('2d')
canvasVideoFrameBuffer = new CanvasVideoFrameBuffer(this.targetCanvas!);
/////////////////////
// WorkerManagers //
/////////////////////
bodyPixModelReady = false
bodyPixConfig = (() => {
const c = generateBodyPixDefaultConfig()
c.model = ModelConfigMobileNetV1_05
c.processOnLocal = true
return c
})()
bodyPixParams = (() => {
const p = generateDefaultBodyPixParams()
p.processWidth = 640
p.processHeight = 480
return p
})()
bodyPixManager = (() => {
const m = new BodypixWorkerManager()
m.init(this.bodyPixConfig).then(
()=>{
this.bodyPixModelReady=true
}
)
return m
})()
googlemeetModelReady = false
googlemeetConfig = (() => {
const c = generateGoogleMeetSegmentationDefaultConfig()
c.processOnLocal = true
return c
})()
googlemeetParams = (() => {
const p = generateDefaultGoogleMeetSegmentationParams()
p.processWidth = 128
p.processHeight = 128
p.smoothingR = 1
p.smoothingS = 1
p.jbfWidth = 256
p.jbfHeight = 256
p.lightWrapping = true
p.smoothingType = GoogleMeetSegmentationSmoothingType.JS
return p
})()
googlemeetManager = (() => {
console.log("GOOGLE!")
const m = new GoogleMeetSegmentationWorkerManager()
m.init(this.googlemeetConfig).then(
()=>{
this.googlemeetModelReady=true
}
)
return m
})()
googleMeetLightWrappingEnable = true
googlemeetTFLiteModelReady = false
googlemeetTFLiteConfig = (() => {
const c = generateGoogleMeetSegmentationTFLiteDefaultConfig()
c.processOnLocal = true
c.modelPath = `${process.env.PUBLIC_URL}/models/96x160/segm_lite_v681.tflite`
// c.modelPath = `${process.env.PUBLIC_URL}/models/128x128/segm_lite_v509.tflite`
// c.modelPath = ${process.env.PUBLIC_URL}/models/144x256/segm_full_v679.tflite`
return c
})()
googlemeetTFLiteParams = (() => {
const p = generateDefaultGoogleMeetSegmentationTFLiteParams()
p.processWidth = 256
p.processHeight = 256
p.kernelSize = 0
p.useSoftmax = true
p.usePadding = false
p.interpolation = 1
return p
})()
googlemeetTFLiteManager = (() => {
console.log("GOOGLE!")
const m = new GoogleMeetSegmentationTFLiteWorkerManager()
m.init(this.googlemeetTFLiteConfig).then(
()=>{
this.googlemeetTFLiteModelReady=true
}
)
return m
})()
lwBlur = 30
////////////////////////////
// constructor & destory ///
////////////////////////////
constructor() {
console.log("NEWVBGP!!!")
const bg = new Image();
bg.src = "/bg1.jpg"
bg.onload = () => {
this.canvasBackground.getContext("2d")!.drawImage(bg, 0, 0, this.canvasBackground.width, this.canvasBackground.height)
}
}
async destroy() {
this.targetCanvasCtx = null;
this.canvasVideoFrameBuffer.destroy();
return;
}
///////////////////////
// Parameter Setter ///
///////////////////////
setVirtualBackgroundType(type: VirtualBackgroundSegmentationType) {
this.config.type = type
}
setBackgroundMode(mode: BackgroundMode) {
this.config.backgroundMode = mode
}
setBackgroundImage(path: string) {
const bg = new Image();
bg.src = path
bg.onload = () => {
this.canvasBackground.getContext("2d")!.drawImage(bg, 0, 0, this.canvasBackground.width, this.canvasBackground.height)
}
}
setBackgroundColor(color: string) {
this.config.backgroundColor = color
}
////////////////
// Processor //
////////////////
async process(buffers: VideoFrameBuffer[]) {
if (buffers.length === 0) {
return Promise.resolve(buffers);
}
// @ts-ignore
const canvas = buffers[0].asCanvasElement()
const frameWidth = canvas!.width;
const frameHeight = canvas!.height;
if (frameWidth === 0 || frameHeight === 0) {
return Promise.resolve(buffers);
}
for (const f of buffers) {
try {
// @ts-ignore
const canvas = f.asCanvasElement() as HTMLCanvasElement
// let result: any
switch (this.config.type) {
case "BodyPix":
// result = await this.bodyPixManager!.predict(canvas, this.bodyPixParams!)
if(this.bodyPixModelReady){
const result = await this.bodyPixManager!.predict(canvas, this.bodyPixParams!)
this.convert_bodypix(canvas, this.canvasBackground, result, this.config)
}
break
case "GoogleMeet":
// result = await this.googleMeetManager!.predict(canvas, this.googleMeetParams!)
if(this.googlemeetModelReady){
const result = await this.googlemeetManager!.predict(canvas, this.googlemeetParams!)
this.convert_googlemeet(canvas, this.canvasBackground, result, this.config)
}
break
case "GoogleMeetTFLite":
// result = await this.googleMeetManager!.predict(canvas, this.googleMeetParams!)
if(this.googlemeetTFLiteModelReady){
const result = await this.googlemeetTFLiteManager!.predict(canvas, this.googlemeetTFLiteParams!)
this.convert_googlemeet_tflite(canvas, this.canvasBackground, result, this.config)
}
break
default:
this.convert_none(canvas)
}
} catch (err) {
console.log("Exception:: ", err)
}
}
buffers[0] = this.canvasVideoFrameBuffer;
return Promise.resolve(buffers)
}
convert_bodypix = (foreground: HTMLCanvasElement, background: HTMLCanvasElement,
segmentation: any, conf: VirtualBackgroundConfig) => {
// (1) resize output canvas and draw background
if (conf.width <= 0 || conf.height <= 0) {
conf.width = foreground.width > background.width ? foreground.width : background.width
conf.height = foreground.height > background.height ? foreground.height : background.height
}
this.targetCanvas.width = conf.width
this.targetCanvas.height = conf.height
this.targetCanvas.getContext("2d")!.drawImage(background, 0, 0, conf.width, conf.height)
if (conf.type === "None") { // Depends on timing, bodypixResult is null
this.targetCanvas.getContext("2d")!.drawImage(foreground, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
return this.targetCanvas
}
// (2) generate foreground transparent
const bodypixResult = segmentation as SemanticPersonSegmentation
this.canvasFront.width = bodypixResult.width
this.canvasFront.height = bodypixResult.height
const frontCtx = this.canvasFront.getContext("2d")!
frontCtx.drawImage(foreground, 0, 0, bodypixResult.width, bodypixResult.height)
const imageData = frontCtx.getImageData(0, 0, this.canvasFront.width, this.canvasFront.height)
const pixelData = imageData.data
for (let rowIndex = 0; rowIndex < bodypixResult.height; rowIndex++) {
for (let colIndex = 0; colIndex < bodypixResult.width; colIndex++) {
const seg_offset = ((rowIndex * bodypixResult.width) + colIndex)
const pix_offset = ((rowIndex * bodypixResult.width) + colIndex) * 4
if (bodypixResult.data[seg_offset] === 0) {
pixelData[pix_offset] = 0
pixelData[pix_offset + 1] = 0
pixelData[pix_offset + 2] = 0
pixelData[pix_offset + 3] = 0
} else {
pixelData[pix_offset] = 255
pixelData[pix_offset + 1] = 255
pixelData[pix_offset + 2] = 255
pixelData[pix_offset + 3] = 255
}
}
}
const fgImageDataTransparent = new ImageData(pixelData, bodypixResult.width, bodypixResult.height);
frontCtx.putImageData(fgImageDataTransparent, 0, 0)
this.canvasFrontResized.width = foreground.width
this.canvasFrontResized.height = foreground.height
this.canvasFrontResized.getContext("2d")!.drawImage(this.canvasFront, 0, 0, this.canvasFrontResized.width, this.canvasFrontResized.height)
this.canvasFrontResized.getContext("2d")!.globalCompositeOperation = 'source-in';
this.canvasFrontResized.getContext("2d")!.drawImage(foreground, 0, 0, this.canvasFrontResized.width, this.canvasFrontResized.height)
// (3) merge Front into Bacground
const frontPositionX = conf.width * conf.frontPositionX
const frontPositionY = conf.height * conf.frontPositionY
const frontWidth = conf.width * conf.frontWidth
const frontHeight = conf.height * conf.frontHeight
this.targetCanvas.getContext("2d")!.drawImage(this.canvasFrontResized, frontPositionX, frontPositionY, frontWidth, frontHeight)
}
convert_googlemeet = (foreground: HTMLCanvasElement, background: HTMLCanvasElement,
segmentation: any, conf: VirtualBackgroundConfig) => {
// (1) resize output canvas and draw background
if (conf.width <= 0 || conf.height <= 0) {
conf.width = foreground.width > background.width ? foreground.width : background.width
conf.height = foreground.height > background.height ? foreground.height : background.height
}
this.targetCanvas.width = conf.width
this.targetCanvas.height = conf.height
this.targetCanvas.getContext("2d")!.drawImage(background, 0, 0, conf.width, conf.height)
if (conf.type === "None") { // Depends on timing, bodypixResult is null
this.targetCanvas.getContext("2d")!.drawImage(foreground, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
return this.targetCanvas
}
// (2) generate foreground transparent
const prediction = segmentation as number[][]
// console.log(prediction)
// Person Canvas Mask
this.personMaskCanvas.width = prediction[0].length
this.personMaskCanvas.height = prediction.length
const maskCtx = this.personMaskCanvas.getContext("2d")!
maskCtx.clearRect(0, 0, this.personMaskCanvas.width, this.personMaskCanvas.height)
const imageData = maskCtx.getImageData(0, 0, this.personMaskCanvas.width, this.personMaskCanvas.height)
const data = imageData.data
for (let rowIndex = 0; rowIndex < this.personMaskCanvas.height; rowIndex++) {
for (let colIndex = 0; colIndex < this.personMaskCanvas.width; colIndex++) {
const pix_offset = ((rowIndex * this.personMaskCanvas.width) + colIndex) * 4
if (prediction[rowIndex][colIndex] >= 128) {
data[pix_offset + 0] = 0
data[pix_offset + 1] = 0
data[pix_offset + 2] = 0
data[pix_offset + 3] = 0
} else {
data[pix_offset + 0] = 255
data[pix_offset + 1] = 255
data[pix_offset + 2] = 255
data[pix_offset + 3] = 255
}
}
}
const imageDataTransparent = new ImageData(data, this.personMaskCanvas.width, this.personMaskCanvas.height);
maskCtx.putImageData(imageDataTransparent, 0, 0)
// Person Canvas
this.personCanvas.width = this.targetCanvas.width
this.personCanvas.height = this.targetCanvas.height
const personCtx = this.personCanvas.getContext("2d")!
personCtx.clearRect(0, 0, this.personCanvas.width, this.personCanvas.height)
personCtx.drawImage(this.personMaskCanvas, 0, 0, this.personCanvas.width, this.personCanvas.height)
personCtx.globalCompositeOperation = "source-atop";
personCtx.drawImage(foreground, 0, 0, this.personCanvas.width, this.personCanvas.height)
this.personCanvas.getContext("2d")!.globalCompositeOperation = "source-over";
// light wrapping
if(this.googleMeetLightWrappingEnable){
this.lightWrapCanvas.width = prediction[0].length
this.lightWrapCanvas.height = prediction.length
const lightWrapImageData = this.lightWrapCanvas.getContext("2d")!.getImageData(0, 0, this.lightWrapCanvas.width, this.lightWrapCanvas.height)
const lightWrapdata = lightWrapImageData.data
for (let rowIndex = 0; rowIndex < this.lightWrapCanvas.height; rowIndex++) {
for (let colIndex = 0; colIndex < this.lightWrapCanvas.width; colIndex++) {
const pix_offset = ((rowIndex * this.lightWrapCanvas.width) + colIndex) * 4
if (prediction[rowIndex][colIndex] > 140) {
lightWrapdata[pix_offset + 0] = 0
lightWrapdata[pix_offset + 1] = 0
lightWrapdata[pix_offset + 2] = 0
lightWrapdata[pix_offset + 3] = 0
} else {
lightWrapdata[pix_offset + 0] = 255
lightWrapdata[pix_offset + 1] = 255
lightWrapdata[pix_offset + 2] = 255
lightWrapdata[pix_offset + 3] = 255
}
}
}
const lightWrapimageDataTransparent = new ImageData(lightWrapdata, this.lightWrapCanvas.width, this.lightWrapCanvas.height);
this.lightWrapCanvas.getContext("2d")!.putImageData(lightWrapimageDataTransparent, 0, 0)
}
// Background
// (3) merge Front into Bacground
const targetCtx = this.targetCanvas.getContext("2d")!
targetCtx.drawImage(this.canvasBackground, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
if(this.googleMeetLightWrappingEnable){
targetCtx.filter = 'blur(2px)';
targetCtx.drawImage(this.lightWrapCanvas, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
targetCtx.filter = 'none';
}
this.targetCanvas.getContext("2d")!.drawImage(this.personCanvas, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
}
convert_googlemeet_tflite = (foreground: HTMLCanvasElement, background: HTMLCanvasElement,
prediction: number[]|Uint8Array|null, conf: VirtualBackgroundConfig) => {
// (1) resize output canvas and draw background
if (conf.width <= 0 || conf.height <= 0) {
conf.width = foreground.width > background.width ? foreground.width : background.width
conf.height = foreground.height > background.height ? foreground.height : background.height
}
this.targetCanvas.width = conf.width
this.targetCanvas.height = conf.height
this.targetCanvas.getContext("2d")!.drawImage(background, 0, 0, conf.width, conf.height)
if (conf.type === "None") { // Depends on timing, result is null
this.targetCanvas.getContext("2d")!.drawImage(foreground, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
return this.targetCanvas
}
// (2) generate foreground transparent
if(!prediction){
return this.targetCanvas
}
const res = new ImageData(this.googlemeetTFLiteParams.processWidth, this.googlemeetTFLiteParams.processHeight)
for(let i = 0;i < this.googlemeetTFLiteParams.processWidth * this.googlemeetTFLiteParams.processHeight; i++){
// res.data[i * 4 + 0] = prediction![i] >128 ? 255 : prediction![i]
// res.data[i * 4 + 1] = prediction![i] >128 ? 255 : prediction![i]
// res.data[i * 4 + 2] = prediction![i] >128 ? 255 : prediction![i]
// res.data[i * 4 + 3] = prediction![i] > 128 ? 255 : prediction![i]
res.data[i * 4 + 3] = prediction![i] > 128 ? 255 : 0
// res.data[i * 4 + 3] = prediction![i] < 64 ? 0 : prediction[i]
}
this.personMaskCanvas.width = this.googlemeetTFLiteParams.processWidth
this.personMaskCanvas.height = this.googlemeetTFLiteParams.processHeight
this.personMaskCanvas.getContext("2d")!.putImageData(res, 0, 0)
// (3) generarte Person Canvas
this.personCanvas.width = conf.width
this.personCanvas.height = conf.height
const personCtx = this.personCanvas.getContext("2d")!
personCtx.clearRect(0, 0, this.personCanvas.width, this.personCanvas.height)
personCtx.drawImage(this.personMaskCanvas, 0, 0, this.personCanvas.width, this.personCanvas.height)
personCtx.globalCompositeOperation = "source-atop";
personCtx.drawImage(foreground, 0, 0, this.personCanvas.width, this.personCanvas.height)
this.personCanvas.getContext("2d")!.globalCompositeOperation = "source-over";
// (4) apply LightWrapping
const dstCtx = this.targetCanvas.getContext("2d")!
dstCtx.filter = `blur(${this.lwBlur}px)`;
dstCtx.drawImage(this.personMaskCanvas, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
dstCtx.filter = 'none';
// (5) draw personcanvas
dstCtx.drawImage(this.personCanvas, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
}
convert_none = (foreground: HTMLCanvasElement) => {
// TODO: Width and Height
this.targetCanvas.getContext("2d")!.drawImage(foreground, 0, 0, this.targetCanvas.width, this.targetCanvas.height)
}
} |
diitalk/flect-chime-sdk-demo | backend/bin/config.ts | export const BACKEND_STACK_NAME = 'f-BackendStack'
export const FRONTEND_LOCAL_DEV = false
export const USE_DOCKER = false
|
diitalk/flect-chime-sdk-demo | frontend3/src/Config.ts | <gh_stars>0
import { UserPoolId, UserPoolClientId, RestAPIEndpoint } from "./BackendConfig"
export const awsConfiguration = {
region: 'us-east-1',
userPoolId: UserPoolId,
clientId: UserPoolClientId,
}
export const BASE_URL = RestAPIEndpoint
export const DEFAULT_USERID = ""
export const DEFAULT_PASSWORD = ""
|
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/appbars/DeviceEnabler.tsx | <gh_stars>0
import { IconButton, Tooltip } from "@material-ui/core"
import {Mic, MicOff, Videocam, VideocamOff, VolumeUp, VolumeOff} from '@material-ui/icons'
import React, { useMemo } from "react"
import clsx from 'clsx';
import { useStyles } from "../../css";
type DeviceType = "Mic" | "Camera" | "Speaker"
type DeviceEnablerProps = {
type: DeviceType
enable:boolean
setEnable:(val:boolean)=>void
}
export const DeviceEnabler = (props:DeviceEnablerProps) =>{
const classes = useStyles()
const icon = useMemo(()=>{
const index = props.enable? 0 : 1
switch(props.type){
case "Mic":
return [<Mic />, <MicOff />][index]
case "Camera":
return [<Videocam/>, <VideocamOff/>][index]
case "Speaker":
return [<VolumeUp/>, <VolumeOff/>][index]
}
},[props.enable, props.type])
const tooltip = useMemo(()=>{
const index = props.enable? 0 : 1
switch(props.type){
case "Mic":
return ["Mic Off", "Mic On"][index]
case "Camera":
return ["Camera Off", "Camera On"][index]
case "Speaker":
return ["Speaker Off", "Speaker On"][index]
}
},[props.enable, props.type])
const enabler = useMemo(()=>{
return(
<Tooltip title={tooltip}>
<IconButton color="inherit" className={clsx(classes.menuButton)} onClick={()=>{props.setEnable(!props.enable)}}>
{icon}
</IconButton>
</Tooltip>
)
},[props.enable, props.type]) // eslint-disable-line
return(
<>
{enabler}
</>
)
} |
diitalk/flect-chime-sdk-demo | frontend3/src/pages/023_meetingRoom/components/ScreenView/FeatureView.tsx | import React, { useMemo } from "react";
import { FocustTarget, PictureInPictureType } from "./const";
import { FullScreenView } from "./FullScreenView";
import { LineView } from "./LineView";
type FeatureViewProps = {
pictureInPicture: PictureInPictureType
focusTarget: FocustTarget
width:number
height:number
};
export const FeatureView = ({ pictureInPicture, focusTarget, width, height}: FeatureViewProps) => {
const lineViewOffset = height * 0.7
const mainView = useMemo(()=>{
return <FullScreenView height={height * 0.7} width={width} pictureInPicture={"None"} focusTarget={"SharedContent"}/>
},[width, height])
const attendeeView = useMemo(()=>{
return <LineView height={height * 0.3} width={width} excludeSharedContent={false} excludeSpeaker={false} viewInLine={5}/>
},[width, height])
return(
<>
<div>
{mainView}
</div>
<div style={{position:"relative", top:lineViewOffset }}>
{attendeeView}
</div>
</>
)
} |